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/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is at least the desired 113 /// number. This is useful when doing custom type-checking on a variadic 114 /// function. Returns true on error. 115 static bool checkArgCountAtLeast(Sema &S, CallExpr *Call, 116 unsigned MinArgCount) { 117 unsigned ArgCount = Call->getNumArgs(); 118 if (ArgCount >= MinArgCount) 119 return false; 120 121 return S.Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args) 122 << 0 /*function call*/ << MinArgCount << ArgCount 123 << Call->getSourceRange(); 124 } 125 126 /// Checks that a call expression's argument count is the desired number. 127 /// This is useful when doing custom type-checking. Returns true on error. 128 static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount) { 129 unsigned ArgCount = Call->getNumArgs(); 130 if (ArgCount == DesiredArgCount) 131 return false; 132 133 if (checkArgCountAtLeast(S, Call, DesiredArgCount)) 134 return true; 135 assert(ArgCount > DesiredArgCount && "should have diagnosed this"); 136 137 // Highlight all the excess arguments. 138 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(), 139 Call->getArg(ArgCount - 1)->getEndLoc()); 140 141 return S.Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args) 142 << 0 /*function call*/ << DesiredArgCount << ArgCount 143 << Call->getArg(1)->getSourceRange(); 144 } 145 146 /// Check that the first argument to __builtin_annotation is an integer 147 /// and the second argument is a non-wide string literal. 148 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 149 if (checkArgCount(S, TheCall, 2)) 150 return true; 151 152 // First argument should be an integer. 153 Expr *ValArg = TheCall->getArg(0); 154 QualType Ty = ValArg->getType(); 155 if (!Ty->isIntegerType()) { 156 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 157 << ValArg->getSourceRange(); 158 return true; 159 } 160 161 // Second argument should be a constant string. 162 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 163 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 164 if (!Literal || !Literal->isAscii()) { 165 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 166 << StrArg->getSourceRange(); 167 return true; 168 } 169 170 TheCall->setType(Ty); 171 return false; 172 } 173 174 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 175 // We need at least one argument. 176 if (TheCall->getNumArgs() < 1) { 177 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 178 << 0 << 1 << TheCall->getNumArgs() 179 << TheCall->getCallee()->getSourceRange(); 180 return true; 181 } 182 183 // All arguments should be wide string literals. 184 for (Expr *Arg : TheCall->arguments()) { 185 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 186 if (!Literal || !Literal->isWide()) { 187 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 188 << Arg->getSourceRange(); 189 return true; 190 } 191 } 192 193 return false; 194 } 195 196 /// Check that the argument to __builtin_addressof is a glvalue, and set the 197 /// result type to the corresponding pointer type. 198 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 199 if (checkArgCount(S, TheCall, 1)) 200 return true; 201 202 ExprResult Arg(TheCall->getArg(0)); 203 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 204 if (ResultType.isNull()) 205 return true; 206 207 TheCall->setArg(0, Arg.get()); 208 TheCall->setType(ResultType); 209 return false; 210 } 211 212 /// Check that the argument to __builtin_function_start is a function. 213 static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) { 214 if (checkArgCount(S, TheCall, 1)) 215 return true; 216 217 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 218 if (Arg.isInvalid()) 219 return true; 220 221 TheCall->setArg(0, Arg.get()); 222 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>( 223 Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext())); 224 225 if (!FD) { 226 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type) 227 << TheCall->getSourceRange(); 228 return true; 229 } 230 231 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 232 TheCall->getBeginLoc()); 233 } 234 235 /// Check the number of arguments and set the result type to 236 /// the argument type. 237 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 238 if (checkArgCount(S, TheCall, 1)) 239 return true; 240 241 TheCall->setType(TheCall->getArg(0)->getType()); 242 return false; 243 } 244 245 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 246 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 247 /// type (but not a function pointer) and that the alignment is a power-of-two. 248 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 249 if (checkArgCount(S, TheCall, 2)) 250 return true; 251 252 clang::Expr *Source = TheCall->getArg(0); 253 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 254 255 auto IsValidIntegerType = [](QualType Ty) { 256 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 257 }; 258 QualType SrcTy = Source->getType(); 259 // We should also be able to use it with arrays (but not functions!). 260 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 261 SrcTy = S.Context.getDecayedType(SrcTy); 262 } 263 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 264 SrcTy->isFunctionPointerType()) { 265 // FIXME: this is not quite the right error message since we don't allow 266 // floating point types, or member pointers. 267 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 268 << SrcTy; 269 return true; 270 } 271 272 clang::Expr *AlignOp = TheCall->getArg(1); 273 if (!IsValidIntegerType(AlignOp->getType())) { 274 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 275 << AlignOp->getType(); 276 return true; 277 } 278 Expr::EvalResult AlignResult; 279 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 280 // We can't check validity of alignment if it is value dependent. 281 if (!AlignOp->isValueDependent() && 282 AlignOp->EvaluateAsInt(AlignResult, S.Context, 283 Expr::SE_AllowSideEffects)) { 284 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 285 llvm::APSInt MaxValue( 286 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 287 if (AlignValue < 1) { 288 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 289 return true; 290 } 291 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 292 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 293 << toString(MaxValue, 10); 294 return true; 295 } 296 if (!AlignValue.isPowerOf2()) { 297 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 298 return true; 299 } 300 if (AlignValue == 1) { 301 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 302 << IsBooleanAlignBuiltin; 303 } 304 } 305 306 ExprResult SrcArg = S.PerformCopyInitialization( 307 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 308 SourceLocation(), Source); 309 if (SrcArg.isInvalid()) 310 return true; 311 TheCall->setArg(0, SrcArg.get()); 312 ExprResult AlignArg = 313 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 314 S.Context, AlignOp->getType(), false), 315 SourceLocation(), AlignOp); 316 if (AlignArg.isInvalid()) 317 return true; 318 TheCall->setArg(1, AlignArg.get()); 319 // For align_up/align_down, the return type is the same as the (potentially 320 // decayed) argument type including qualifiers. For is_aligned(), the result 321 // is always bool. 322 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 323 return false; 324 } 325 326 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 327 unsigned BuiltinID) { 328 if (checkArgCount(S, TheCall, 3)) 329 return true; 330 331 // First two arguments should be integers. 332 for (unsigned I = 0; I < 2; ++I) { 333 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 334 if (Arg.isInvalid()) return true; 335 TheCall->setArg(I, Arg.get()); 336 337 QualType Ty = Arg.get()->getType(); 338 if (!Ty->isIntegerType()) { 339 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 340 << Ty << Arg.get()->getSourceRange(); 341 return true; 342 } 343 } 344 345 // Third argument should be a pointer to a non-const integer. 346 // IRGen correctly handles volatile, restrict, and address spaces, and 347 // the other qualifiers aren't possible. 348 { 349 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 350 if (Arg.isInvalid()) return true; 351 TheCall->setArg(2, Arg.get()); 352 353 QualType Ty = Arg.get()->getType(); 354 const auto *PtrTy = Ty->getAs<PointerType>(); 355 if (!PtrTy || 356 !PtrTy->getPointeeType()->isIntegerType() || 357 PtrTy->getPointeeType().isConstQualified()) { 358 S.Diag(Arg.get()->getBeginLoc(), 359 diag::err_overflow_builtin_must_be_ptr_int) 360 << Ty << Arg.get()->getSourceRange(); 361 return true; 362 } 363 } 364 365 // Disallow signed bit-precise integer args larger than 128 bits to mul 366 // function until we improve backend support. 367 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 368 for (unsigned I = 0; I < 3; ++I) { 369 const auto Arg = TheCall->getArg(I); 370 // Third argument will be a pointer. 371 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 372 if (Ty->isBitIntType() && Ty->isSignedIntegerType() && 373 S.getASTContext().getIntWidth(Ty) > 128) 374 return S.Diag(Arg->getBeginLoc(), 375 diag::err_overflow_builtin_bit_int_max_size) 376 << 128; 377 } 378 } 379 380 return false; 381 } 382 383 namespace { 384 struct BuiltinDumpStructGenerator { 385 Sema &S; 386 CallExpr *TheCall; 387 SourceLocation Loc = TheCall->getBeginLoc(); 388 SmallVector<Expr *, 32> Actions; 389 DiagnosticErrorTrap ErrorTracker; 390 PrintingPolicy Policy; 391 392 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall) 393 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()), 394 Policy(S.Context.getPrintingPolicy()) { 395 Policy.AnonymousTagLocations = false; 396 } 397 398 Expr *makeOpaqueValueExpr(Expr *Inner) { 399 auto *OVE = new (S.Context) 400 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(), 401 Inner->getObjectKind(), Inner); 402 Actions.push_back(OVE); 403 return OVE; 404 } 405 406 Expr *getStringLiteral(llvm::StringRef Str) { 407 Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Str); 408 // Wrap the literal in parentheses to attach a source location. 409 return new (S.Context) ParenExpr(Loc, Loc, Lit); 410 } 411 412 bool callPrintFunction(llvm::StringRef Format, 413 llvm::ArrayRef<Expr *> Exprs = {}) { 414 SmallVector<Expr *, 8> Args; 415 assert(TheCall->getNumArgs() >= 2); 416 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size()); 417 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end()); 418 Args.push_back(getStringLiteral(Format)); 419 Args.insert(Args.end(), Exprs.begin(), Exprs.end()); 420 421 // Register a note to explain why we're performing the call. 422 Sema::CodeSynthesisContext Ctx; 423 Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall; 424 Ctx.PointOfInstantiation = Loc; 425 Ctx.CallArgs = Args.data(); 426 Ctx.NumCallArgs = Args.size(); 427 S.pushCodeSynthesisContext(Ctx); 428 429 ExprResult RealCall = 430 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1), 431 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc()); 432 433 S.popCodeSynthesisContext(); 434 if (!RealCall.isInvalid()) 435 Actions.push_back(RealCall.get()); 436 // Bail out if we've hit any errors, even if we managed to build the 437 // call. We don't want to produce more than one error. 438 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred(); 439 } 440 441 Expr *getIndentString(unsigned Depth) { 442 if (!Depth) 443 return nullptr; 444 445 llvm::SmallString<32> Indent; 446 Indent.resize(Depth * Policy.Indentation, ' '); 447 return getStringLiteral(Indent); 448 } 449 450 Expr *getTypeString(QualType T) { 451 return getStringLiteral(T.getAsString(Policy)); 452 } 453 454 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) { 455 llvm::raw_svector_ostream OS(Str); 456 457 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather 458 // than trying to print a single character. 459 if (auto *BT = T->getAs<BuiltinType>()) { 460 switch (BT->getKind()) { 461 case BuiltinType::Bool: 462 OS << "%d"; 463 return true; 464 case BuiltinType::Char_U: 465 case BuiltinType::UChar: 466 OS << "%hhu"; 467 return true; 468 case BuiltinType::Char_S: 469 case BuiltinType::SChar: 470 OS << "%hhd"; 471 return true; 472 default: 473 break; 474 } 475 } 476 477 analyze_printf::PrintfSpecifier Specifier; 478 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) { 479 // We were able to guess how to format this. 480 if (Specifier.getConversionSpecifier().getKind() == 481 analyze_printf::PrintfConversionSpecifier::sArg) { 482 // Wrap double-quotes around a '%s' specifier and limit its maximum 483 // length. Ideally we'd also somehow escape special characters in the 484 // contents but printf doesn't support that. 485 // FIXME: '%s' formatting is not safe in general. 486 OS << '"'; 487 Specifier.setPrecision(analyze_printf::OptionalAmount(32u)); 488 Specifier.toString(OS); 489 OS << '"'; 490 // FIXME: It would be nice to include a '...' if the string doesn't fit 491 // in the length limit. 492 } else { 493 Specifier.toString(OS); 494 } 495 return true; 496 } 497 498 if (T->isPointerType()) { 499 // Format all pointers with '%p'. 500 OS << "%p"; 501 return true; 502 } 503 504 return false; 505 } 506 507 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) { 508 Expr *IndentLit = getIndentString(Depth); 509 Expr *TypeLit = getTypeString(S.Context.getRecordType(RD)); 510 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit}) 511 : callPrintFunction("%s", {TypeLit})) 512 return true; 513 514 return dumpRecordValue(RD, E, IndentLit, Depth); 515 } 516 517 // Dump a record value. E should be a pointer or lvalue referring to an RD. 518 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent, 519 unsigned Depth) { 520 // FIXME: Decide what to do if RD is a union. At least we should probably 521 // turn off printing `const char*` members with `%s`, because that is very 522 // likely to crash if that's not the active member. Whatever we decide, we 523 // should document it. 524 525 // Build an OpaqueValueExpr so we can refer to E more than once without 526 // triggering re-evaluation. 527 Expr *RecordArg = makeOpaqueValueExpr(E); 528 bool RecordArgIsPtr = RecordArg->getType()->isPointerType(); 529 530 if (callPrintFunction(" {\n")) 531 return true; 532 533 // Dump each base class, regardless of whether they're aggregates. 534 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 535 for (const auto &Base : CXXRD->bases()) { 536 QualType BaseType = 537 RecordArgIsPtr ? S.Context.getPointerType(Base.getType()) 538 : S.Context.getLValueReferenceType(Base.getType()); 539 ExprResult BasePtr = S.BuildCStyleCastExpr( 540 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc, 541 RecordArg); 542 if (BasePtr.isInvalid() || 543 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(), 544 Depth + 1)) 545 return true; 546 } 547 } 548 549 Expr *FieldIndentArg = getIndentString(Depth + 1); 550 551 // Dump each field. 552 for (auto *D : RD->decls()) { 553 auto *IFD = dyn_cast<IndirectFieldDecl>(D); 554 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D); 555 if (!FD || FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion()) 556 continue; 557 558 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s "); 559 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg, 560 getTypeString(FD->getType()), 561 getStringLiteral(FD->getName())}; 562 563 if (FD->isBitField()) { 564 Format += ": %zu "; 565 QualType SizeT = S.Context.getSizeType(); 566 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT), 567 FD->getBitWidthValue(S.Context)); 568 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc)); 569 } 570 571 Format += "="; 572 573 ExprResult Field = 574 IFD ? S.BuildAnonymousStructUnionMemberReference( 575 CXXScopeSpec(), Loc, IFD, 576 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc) 577 : S.BuildFieldReferenceExpr( 578 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD, 579 DeclAccessPair::make(FD, AS_public), 580 DeclarationNameInfo(FD->getDeclName(), Loc)); 581 if (Field.isInvalid()) 582 return true; 583 584 auto *InnerRD = FD->getType()->getAsRecordDecl(); 585 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD); 586 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) { 587 // Recursively print the values of members of aggregate record type. 588 if (callPrintFunction(Format, Args) || 589 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1)) 590 return true; 591 } else { 592 Format += " "; 593 if (appendFormatSpecifier(FD->getType(), Format)) { 594 // We know how to print this field. 595 Args.push_back(Field.get()); 596 } else { 597 // We don't know how to print this field. Print out its address 598 // with a format specifier that a smart tool will be able to 599 // recognize and treat specially. 600 Format += "*%p"; 601 ExprResult FieldAddr = 602 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get()); 603 if (FieldAddr.isInvalid()) 604 return true; 605 Args.push_back(FieldAddr.get()); 606 } 607 Format += "\n"; 608 if (callPrintFunction(Format, Args)) 609 return true; 610 } 611 } 612 613 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent) 614 : callPrintFunction("}\n"); 615 } 616 617 Expr *buildWrapper() { 618 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions, 619 PseudoObjectExpr::NoResult); 620 TheCall->setType(Wrapper->getType()); 621 TheCall->setValueKind(Wrapper->getValueKind()); 622 return Wrapper; 623 } 624 }; 625 } // namespace 626 627 static ExprResult SemaBuiltinDumpStruct(Sema &S, CallExpr *TheCall) { 628 if (checkArgCountAtLeast(S, TheCall, 2)) 629 return ExprError(); 630 631 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0)); 632 if (PtrArgResult.isInvalid()) 633 return ExprError(); 634 TheCall->setArg(0, PtrArgResult.get()); 635 636 // First argument should be a pointer to a struct. 637 QualType PtrArgType = PtrArgResult.get()->getType(); 638 if (!PtrArgType->isPointerType() || 639 !PtrArgType->getPointeeType()->isRecordType()) { 640 S.Diag(PtrArgResult.get()->getBeginLoc(), 641 diag::err_expected_struct_pointer_argument) 642 << 1 << TheCall->getDirectCallee() << PtrArgType; 643 return ExprError(); 644 } 645 const RecordDecl *RD = PtrArgType->getPointeeType()->getAsRecordDecl(); 646 647 // Second argument is a callable, but we can't fully validate it until we try 648 // calling it. 649 QualType FnArgType = TheCall->getArg(1)->getType(); 650 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() && 651 !FnArgType->isBlockPointerType() && 652 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) { 653 auto *BT = FnArgType->getAs<BuiltinType>(); 654 switch (BT ? BT->getKind() : BuiltinType::Void) { 655 case BuiltinType::Dependent: 656 case BuiltinType::Overload: 657 case BuiltinType::BoundMember: 658 case BuiltinType::PseudoObject: 659 case BuiltinType::UnknownAny: 660 case BuiltinType::BuiltinFn: 661 // This might be a callable. 662 break; 663 664 default: 665 S.Diag(TheCall->getArg(1)->getBeginLoc(), 666 diag::err_expected_callable_argument) 667 << 2 << TheCall->getDirectCallee() << FnArgType; 668 return ExprError(); 669 } 670 } 671 672 BuiltinDumpStructGenerator Generator(S, TheCall); 673 674 // Wrap parentheses around the given pointer. This is not necessary for 675 // correct code generation, but it means that when we pretty-print the call 676 // arguments in our diagnostics we will produce '(&s)->n' instead of the 677 // incorrect '&s->n'. 678 Expr *PtrArg = PtrArgResult.get(); 679 PtrArg = new (S.Context) 680 ParenExpr(PtrArg->getBeginLoc(), 681 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg); 682 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0)) 683 return ExprError(); 684 685 return Generator.buildWrapper(); 686 } 687 688 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 689 if (checkArgCount(S, BuiltinCall, 2)) 690 return true; 691 692 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 693 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 694 Expr *Call = BuiltinCall->getArg(0); 695 Expr *Chain = BuiltinCall->getArg(1); 696 697 if (Call->getStmtClass() != Stmt::CallExprClass) { 698 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 699 << Call->getSourceRange(); 700 return true; 701 } 702 703 auto CE = cast<CallExpr>(Call); 704 if (CE->getCallee()->getType()->isBlockPointerType()) { 705 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 706 << Call->getSourceRange(); 707 return true; 708 } 709 710 const Decl *TargetDecl = CE->getCalleeDecl(); 711 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 712 if (FD->getBuiltinID()) { 713 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 714 << Call->getSourceRange(); 715 return true; 716 } 717 718 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 719 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 720 << Call->getSourceRange(); 721 return true; 722 } 723 724 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 725 if (ChainResult.isInvalid()) 726 return true; 727 if (!ChainResult.get()->getType()->isPointerType()) { 728 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 729 << Chain->getSourceRange(); 730 return true; 731 } 732 733 QualType ReturnTy = CE->getCallReturnType(S.Context); 734 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 735 QualType BuiltinTy = S.Context.getFunctionType( 736 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 737 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 738 739 Builtin = 740 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 741 742 BuiltinCall->setType(CE->getType()); 743 BuiltinCall->setValueKind(CE->getValueKind()); 744 BuiltinCall->setObjectKind(CE->getObjectKind()); 745 BuiltinCall->setCallee(Builtin); 746 BuiltinCall->setArg(1, ChainResult.get()); 747 748 return false; 749 } 750 751 namespace { 752 753 class ScanfDiagnosticFormatHandler 754 : public analyze_format_string::FormatStringHandler { 755 // Accepts the argument index (relative to the first destination index) of the 756 // argument whose size we want. 757 using ComputeSizeFunction = 758 llvm::function_ref<Optional<llvm::APSInt>(unsigned)>; 759 760 // Accepts the argument index (relative to the first destination index), the 761 // destination size, and the source size). 762 using DiagnoseFunction = 763 llvm::function_ref<void(unsigned, unsigned, unsigned)>; 764 765 ComputeSizeFunction ComputeSizeArgument; 766 DiagnoseFunction Diagnose; 767 768 public: 769 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument, 770 DiagnoseFunction Diagnose) 771 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {} 772 773 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 774 const char *StartSpecifier, 775 unsigned specifierLen) override { 776 if (!FS.consumesDataArgument()) 777 return true; 778 779 unsigned NulByte = 0; 780 switch ((FS.getConversionSpecifier().getKind())) { 781 default: 782 return true; 783 case analyze_format_string::ConversionSpecifier::sArg: 784 case analyze_format_string::ConversionSpecifier::ScanListArg: 785 NulByte = 1; 786 break; 787 case analyze_format_string::ConversionSpecifier::cArg: 788 break; 789 } 790 791 analyze_format_string::OptionalAmount FW = FS.getFieldWidth(); 792 if (FW.getHowSpecified() != 793 analyze_format_string::OptionalAmount::HowSpecified::Constant) 794 return true; 795 796 unsigned SourceSize = FW.getConstantAmount() + NulByte; 797 798 Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex()); 799 if (!DestSizeAPS) 800 return true; 801 802 unsigned DestSize = DestSizeAPS->getZExtValue(); 803 804 if (DestSize < SourceSize) 805 Diagnose(FS.getArgIndex(), DestSize, SourceSize); 806 807 return true; 808 } 809 }; 810 811 class EstimateSizeFormatHandler 812 : public analyze_format_string::FormatStringHandler { 813 size_t Size; 814 815 public: 816 EstimateSizeFormatHandler(StringRef Format) 817 : Size(std::min(Format.find(0), Format.size()) + 818 1 /* null byte always written by sprintf */) {} 819 820 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 821 const char *, unsigned SpecifierLen, 822 const TargetInfo &) override { 823 824 const size_t FieldWidth = computeFieldWidth(FS); 825 const size_t Precision = computePrecision(FS); 826 827 // The actual format. 828 switch (FS.getConversionSpecifier().getKind()) { 829 // Just a char. 830 case analyze_format_string::ConversionSpecifier::cArg: 831 case analyze_format_string::ConversionSpecifier::CArg: 832 Size += std::max(FieldWidth, (size_t)1); 833 break; 834 // Just an integer. 835 case analyze_format_string::ConversionSpecifier::dArg: 836 case analyze_format_string::ConversionSpecifier::DArg: 837 case analyze_format_string::ConversionSpecifier::iArg: 838 case analyze_format_string::ConversionSpecifier::oArg: 839 case analyze_format_string::ConversionSpecifier::OArg: 840 case analyze_format_string::ConversionSpecifier::uArg: 841 case analyze_format_string::ConversionSpecifier::UArg: 842 case analyze_format_string::ConversionSpecifier::xArg: 843 case analyze_format_string::ConversionSpecifier::XArg: 844 Size += std::max(FieldWidth, Precision); 845 break; 846 847 // %g style conversion switches between %f or %e style dynamically. 848 // %f always takes less space, so default to it. 849 case analyze_format_string::ConversionSpecifier::gArg: 850 case analyze_format_string::ConversionSpecifier::GArg: 851 852 // Floating point number in the form '[+]ddd.ddd'. 853 case analyze_format_string::ConversionSpecifier::fArg: 854 case analyze_format_string::ConversionSpecifier::FArg: 855 Size += std::max(FieldWidth, 1 /* integer part */ + 856 (Precision ? 1 + Precision 857 : 0) /* period + decimal */); 858 break; 859 860 // Floating point number in the form '[-]d.ddde[+-]dd'. 861 case analyze_format_string::ConversionSpecifier::eArg: 862 case analyze_format_string::ConversionSpecifier::EArg: 863 Size += 864 std::max(FieldWidth, 865 1 /* integer part */ + 866 (Precision ? 1 + Precision : 0) /* period + decimal */ + 867 1 /* e or E letter */ + 2 /* exponent */); 868 break; 869 870 // Floating point number in the form '[-]0xh.hhhhp±dd'. 871 case analyze_format_string::ConversionSpecifier::aArg: 872 case analyze_format_string::ConversionSpecifier::AArg: 873 Size += 874 std::max(FieldWidth, 875 2 /* 0x */ + 1 /* integer part */ + 876 (Precision ? 1 + Precision : 0) /* period + decimal */ + 877 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 878 break; 879 880 // Just a string. 881 case analyze_format_string::ConversionSpecifier::sArg: 882 case analyze_format_string::ConversionSpecifier::SArg: 883 Size += FieldWidth; 884 break; 885 886 // Just a pointer in the form '0xddd'. 887 case analyze_format_string::ConversionSpecifier::pArg: 888 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 889 break; 890 891 // A plain percent. 892 case analyze_format_string::ConversionSpecifier::PercentArg: 893 Size += 1; 894 break; 895 896 default: 897 break; 898 } 899 900 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 901 902 if (FS.hasAlternativeForm()) { 903 switch (FS.getConversionSpecifier().getKind()) { 904 default: 905 break; 906 // Force a leading '0'. 907 case analyze_format_string::ConversionSpecifier::oArg: 908 Size += 1; 909 break; 910 // Force a leading '0x'. 911 case analyze_format_string::ConversionSpecifier::xArg: 912 case analyze_format_string::ConversionSpecifier::XArg: 913 Size += 2; 914 break; 915 // Force a period '.' before decimal, even if precision is 0. 916 case analyze_format_string::ConversionSpecifier::aArg: 917 case analyze_format_string::ConversionSpecifier::AArg: 918 case analyze_format_string::ConversionSpecifier::eArg: 919 case analyze_format_string::ConversionSpecifier::EArg: 920 case analyze_format_string::ConversionSpecifier::fArg: 921 case analyze_format_string::ConversionSpecifier::FArg: 922 case analyze_format_string::ConversionSpecifier::gArg: 923 case analyze_format_string::ConversionSpecifier::GArg: 924 Size += (Precision ? 0 : 1); 925 break; 926 } 927 } 928 assert(SpecifierLen <= Size && "no underflow"); 929 Size -= SpecifierLen; 930 return true; 931 } 932 933 size_t getSizeLowerBound() const { return Size; } 934 935 private: 936 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 937 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 938 size_t FieldWidth = 0; 939 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 940 FieldWidth = FW.getConstantAmount(); 941 return FieldWidth; 942 } 943 944 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 945 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 946 size_t Precision = 0; 947 948 // See man 3 printf for default precision value based on the specifier. 949 switch (FW.getHowSpecified()) { 950 case analyze_format_string::OptionalAmount::NotSpecified: 951 switch (FS.getConversionSpecifier().getKind()) { 952 default: 953 break; 954 case analyze_format_string::ConversionSpecifier::dArg: // %d 955 case analyze_format_string::ConversionSpecifier::DArg: // %D 956 case analyze_format_string::ConversionSpecifier::iArg: // %i 957 Precision = 1; 958 break; 959 case analyze_format_string::ConversionSpecifier::oArg: // %d 960 case analyze_format_string::ConversionSpecifier::OArg: // %D 961 case analyze_format_string::ConversionSpecifier::uArg: // %d 962 case analyze_format_string::ConversionSpecifier::UArg: // %D 963 case analyze_format_string::ConversionSpecifier::xArg: // %d 964 case analyze_format_string::ConversionSpecifier::XArg: // %D 965 Precision = 1; 966 break; 967 case analyze_format_string::ConversionSpecifier::fArg: // %f 968 case analyze_format_string::ConversionSpecifier::FArg: // %F 969 case analyze_format_string::ConversionSpecifier::eArg: // %e 970 case analyze_format_string::ConversionSpecifier::EArg: // %E 971 case analyze_format_string::ConversionSpecifier::gArg: // %g 972 case analyze_format_string::ConversionSpecifier::GArg: // %G 973 Precision = 6; 974 break; 975 case analyze_format_string::ConversionSpecifier::pArg: // %d 976 Precision = 1; 977 break; 978 } 979 break; 980 case analyze_format_string::OptionalAmount::Constant: 981 Precision = FW.getConstantAmount(); 982 break; 983 default: 984 break; 985 } 986 return Precision; 987 } 988 }; 989 990 } // namespace 991 992 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 993 CallExpr *TheCall) { 994 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 995 isConstantEvaluated()) 996 return; 997 998 bool UseDABAttr = false; 999 const FunctionDecl *UseDecl = FD; 1000 1001 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>(); 1002 if (DABAttr) { 1003 UseDecl = DABAttr->getFunction(); 1004 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!"); 1005 UseDABAttr = true; 1006 } 1007 1008 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true); 1009 1010 if (!BuiltinID) 1011 return; 1012 1013 const TargetInfo &TI = getASTContext().getTargetInfo(); 1014 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 1015 1016 auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> { 1017 // If we refer to a diagnose_as_builtin attribute, we need to change the 1018 // argument index to refer to the arguments of the called function. Unless 1019 // the index is out of bounds, which presumably means it's a variadic 1020 // function. 1021 if (!UseDABAttr) 1022 return Index; 1023 unsigned DABIndices = DABAttr->argIndices_size(); 1024 unsigned NewIndex = Index < DABIndices 1025 ? DABAttr->argIndices_begin()[Index] 1026 : Index - DABIndices + FD->getNumParams(); 1027 if (NewIndex >= TheCall->getNumArgs()) 1028 return llvm::None; 1029 return NewIndex; 1030 }; 1031 1032 auto ComputeExplicitObjectSizeArgument = 1033 [&](unsigned Index) -> Optional<llvm::APSInt> { 1034 Optional<unsigned> IndexOptional = TranslateIndex(Index); 1035 if (!IndexOptional) 1036 return llvm::None; 1037 unsigned NewIndex = IndexOptional.getValue(); 1038 Expr::EvalResult Result; 1039 Expr *SizeArg = TheCall->getArg(NewIndex); 1040 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 1041 return llvm::None; 1042 llvm::APSInt Integer = Result.Val.getInt(); 1043 Integer.setIsUnsigned(true); 1044 return Integer; 1045 }; 1046 1047 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 1048 // If the parameter has a pass_object_size attribute, then we should use its 1049 // (potentially) more strict checking mode. Otherwise, conservatively assume 1050 // type 0. 1051 int BOSType = 0; 1052 // This check can fail for variadic functions. 1053 if (Index < FD->getNumParams()) { 1054 if (const auto *POS = 1055 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 1056 BOSType = POS->getType(); 1057 } 1058 1059 Optional<unsigned> IndexOptional = TranslateIndex(Index); 1060 if (!IndexOptional) 1061 return llvm::None; 1062 unsigned NewIndex = IndexOptional.getValue(); 1063 1064 const Expr *ObjArg = TheCall->getArg(NewIndex); 1065 uint64_t Result; 1066 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 1067 return llvm::None; 1068 1069 // Get the object size in the target's size_t width. 1070 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 1071 }; 1072 1073 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 1074 Optional<unsigned> IndexOptional = TranslateIndex(Index); 1075 if (!IndexOptional) 1076 return llvm::None; 1077 unsigned NewIndex = IndexOptional.getValue(); 1078 1079 const Expr *ObjArg = TheCall->getArg(NewIndex); 1080 uint64_t Result; 1081 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 1082 return llvm::None; 1083 // Add 1 for null byte. 1084 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 1085 }; 1086 1087 Optional<llvm::APSInt> SourceSize; 1088 Optional<llvm::APSInt> DestinationSize; 1089 unsigned DiagID = 0; 1090 bool IsChkVariant = false; 1091 1092 auto GetFunctionName = [&]() { 1093 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 1094 // Skim off the details of whichever builtin was called to produce a better 1095 // diagnostic, as it's unlikely that the user wrote the __builtin 1096 // explicitly. 1097 if (IsChkVariant) { 1098 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 1099 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 1100 } else if (FunctionName.startswith("__builtin_")) { 1101 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 1102 } 1103 return FunctionName; 1104 }; 1105 1106 switch (BuiltinID) { 1107 default: 1108 return; 1109 case Builtin::BI__builtin_strcpy: 1110 case Builtin::BIstrcpy: { 1111 DiagID = diag::warn_fortify_strlen_overflow; 1112 SourceSize = ComputeStrLenArgument(1); 1113 DestinationSize = ComputeSizeArgument(0); 1114 break; 1115 } 1116 1117 case Builtin::BI__builtin___strcpy_chk: { 1118 DiagID = diag::warn_fortify_strlen_overflow; 1119 SourceSize = ComputeStrLenArgument(1); 1120 DestinationSize = ComputeExplicitObjectSizeArgument(2); 1121 IsChkVariant = true; 1122 break; 1123 } 1124 1125 case Builtin::BIscanf: 1126 case Builtin::BIfscanf: 1127 case Builtin::BIsscanf: { 1128 unsigned FormatIndex = 1; 1129 unsigned DataIndex = 2; 1130 if (BuiltinID == Builtin::BIscanf) { 1131 FormatIndex = 0; 1132 DataIndex = 1; 1133 } 1134 1135 const auto *FormatExpr = 1136 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 1137 1138 const auto *Format = dyn_cast<StringLiteral>(FormatExpr); 1139 if (!Format) 1140 return; 1141 1142 if (!Format->isAscii() && !Format->isUTF8()) 1143 return; 1144 1145 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize, 1146 unsigned SourceSize) { 1147 DiagID = diag::warn_fortify_scanf_overflow; 1148 unsigned Index = ArgIndex + DataIndex; 1149 StringRef FunctionName = GetFunctionName(); 1150 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall, 1151 PDiag(DiagID) << FunctionName << (Index + 1) 1152 << DestSize << SourceSize); 1153 }; 1154 1155 StringRef FormatStrRef = Format->getString(); 1156 auto ShiftedComputeSizeArgument = [&](unsigned Index) { 1157 return ComputeSizeArgument(Index + DataIndex); 1158 }; 1159 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose); 1160 const char *FormatBytes = FormatStrRef.data(); 1161 const ConstantArrayType *T = 1162 Context.getAsConstantArrayType(Format->getType()); 1163 assert(T && "String literal not of constant array type!"); 1164 size_t TypeSize = T->getSize().getZExtValue(); 1165 1166 // In case there's a null byte somewhere. 1167 size_t StrLen = 1168 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 1169 1170 analyze_format_string::ParseScanfString(H, FormatBytes, 1171 FormatBytes + StrLen, getLangOpts(), 1172 Context.getTargetInfo()); 1173 1174 // Unlike the other cases, in this one we have already issued the diagnostic 1175 // here, so no need to continue (because unlike the other cases, here the 1176 // diagnostic refers to the argument number). 1177 return; 1178 } 1179 1180 case Builtin::BIsprintf: 1181 case Builtin::BI__builtin___sprintf_chk: { 1182 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 1183 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 1184 1185 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 1186 1187 if (!Format->isAscii() && !Format->isUTF8()) 1188 return; 1189 1190 StringRef FormatStrRef = Format->getString(); 1191 EstimateSizeFormatHandler H(FormatStrRef); 1192 const char *FormatBytes = FormatStrRef.data(); 1193 const ConstantArrayType *T = 1194 Context.getAsConstantArrayType(Format->getType()); 1195 assert(T && "String literal not of constant array type!"); 1196 size_t TypeSize = T->getSize().getZExtValue(); 1197 1198 // In case there's a null byte somewhere. 1199 size_t StrLen = 1200 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 1201 if (!analyze_format_string::ParsePrintfString( 1202 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 1203 Context.getTargetInfo(), false)) { 1204 DiagID = diag::warn_fortify_source_format_overflow; 1205 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 1206 .extOrTrunc(SizeTypeWidth); 1207 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 1208 DestinationSize = ComputeExplicitObjectSizeArgument(2); 1209 IsChkVariant = true; 1210 } else { 1211 DestinationSize = ComputeSizeArgument(0); 1212 } 1213 break; 1214 } 1215 } 1216 return; 1217 } 1218 case Builtin::BI__builtin___memcpy_chk: 1219 case Builtin::BI__builtin___memmove_chk: 1220 case Builtin::BI__builtin___memset_chk: 1221 case Builtin::BI__builtin___strlcat_chk: 1222 case Builtin::BI__builtin___strlcpy_chk: 1223 case Builtin::BI__builtin___strncat_chk: 1224 case Builtin::BI__builtin___strncpy_chk: 1225 case Builtin::BI__builtin___stpncpy_chk: 1226 case Builtin::BI__builtin___memccpy_chk: 1227 case Builtin::BI__builtin___mempcpy_chk: { 1228 DiagID = diag::warn_builtin_chk_overflow; 1229 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 1230 DestinationSize = 1231 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 1232 IsChkVariant = true; 1233 break; 1234 } 1235 1236 case Builtin::BI__builtin___snprintf_chk: 1237 case Builtin::BI__builtin___vsnprintf_chk: { 1238 DiagID = diag::warn_builtin_chk_overflow; 1239 SourceSize = ComputeExplicitObjectSizeArgument(1); 1240 DestinationSize = ComputeExplicitObjectSizeArgument(3); 1241 IsChkVariant = true; 1242 break; 1243 } 1244 1245 case Builtin::BIstrncat: 1246 case Builtin::BI__builtin_strncat: 1247 case Builtin::BIstrncpy: 1248 case Builtin::BI__builtin_strncpy: 1249 case Builtin::BIstpncpy: 1250 case Builtin::BI__builtin_stpncpy: { 1251 // Whether these functions overflow depends on the runtime strlen of the 1252 // string, not just the buffer size, so emitting the "always overflow" 1253 // diagnostic isn't quite right. We should still diagnose passing a buffer 1254 // size larger than the destination buffer though; this is a runtime abort 1255 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 1256 DiagID = diag::warn_fortify_source_size_mismatch; 1257 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 1258 DestinationSize = ComputeSizeArgument(0); 1259 break; 1260 } 1261 1262 case Builtin::BImemcpy: 1263 case Builtin::BI__builtin_memcpy: 1264 case Builtin::BImemmove: 1265 case Builtin::BI__builtin_memmove: 1266 case Builtin::BImemset: 1267 case Builtin::BI__builtin_memset: 1268 case Builtin::BImempcpy: 1269 case Builtin::BI__builtin_mempcpy: { 1270 DiagID = diag::warn_fortify_source_overflow; 1271 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 1272 DestinationSize = ComputeSizeArgument(0); 1273 break; 1274 } 1275 case Builtin::BIsnprintf: 1276 case Builtin::BI__builtin_snprintf: 1277 case Builtin::BIvsnprintf: 1278 case Builtin::BI__builtin_vsnprintf: { 1279 DiagID = diag::warn_fortify_source_size_mismatch; 1280 SourceSize = ComputeExplicitObjectSizeArgument(1); 1281 DestinationSize = ComputeSizeArgument(0); 1282 break; 1283 } 1284 } 1285 1286 if (!SourceSize || !DestinationSize || 1287 llvm::APSInt::compareValues(SourceSize.getValue(), 1288 DestinationSize.getValue()) <= 0) 1289 return; 1290 1291 StringRef FunctionName = GetFunctionName(); 1292 1293 SmallString<16> DestinationStr; 1294 SmallString<16> SourceStr; 1295 DestinationSize->toString(DestinationStr, /*Radix=*/10); 1296 SourceSize->toString(SourceStr, /*Radix=*/10); 1297 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 1298 PDiag(DiagID) 1299 << FunctionName << DestinationStr << SourceStr); 1300 } 1301 1302 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 1303 Scope::ScopeFlags NeededScopeFlags, 1304 unsigned DiagID) { 1305 // Scopes aren't available during instantiation. Fortunately, builtin 1306 // functions cannot be template args so they cannot be formed through template 1307 // instantiation. Therefore checking once during the parse is sufficient. 1308 if (SemaRef.inTemplateInstantiation()) 1309 return false; 1310 1311 Scope *S = SemaRef.getCurScope(); 1312 while (S && !S->isSEHExceptScope()) 1313 S = S->getParent(); 1314 if (!S || !(S->getFlags() & NeededScopeFlags)) { 1315 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1316 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 1317 << DRE->getDecl()->getIdentifier(); 1318 return true; 1319 } 1320 1321 return false; 1322 } 1323 1324 static inline bool isBlockPointer(Expr *Arg) { 1325 return Arg->getType()->isBlockPointerType(); 1326 } 1327 1328 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 1329 /// void*, which is a requirement of device side enqueue. 1330 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 1331 const BlockPointerType *BPT = 1332 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1333 ArrayRef<QualType> Params = 1334 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 1335 unsigned ArgCounter = 0; 1336 bool IllegalParams = false; 1337 // Iterate through the block parameters until either one is found that is not 1338 // a local void*, or the block is valid. 1339 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 1340 I != E; ++I, ++ArgCounter) { 1341 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 1342 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 1343 LangAS::opencl_local) { 1344 // Get the location of the error. If a block literal has been passed 1345 // (BlockExpr) then we can point straight to the offending argument, 1346 // else we just point to the variable reference. 1347 SourceLocation ErrorLoc; 1348 if (isa<BlockExpr>(BlockArg)) { 1349 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 1350 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 1351 } else if (isa<DeclRefExpr>(BlockArg)) { 1352 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 1353 } 1354 S.Diag(ErrorLoc, 1355 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 1356 IllegalParams = true; 1357 } 1358 } 1359 1360 return IllegalParams; 1361 } 1362 1363 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 1364 // OpenCL device can support extension but not the feature as extension 1365 // requires subgroup independent forward progress, but subgroup independent 1366 // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature. 1367 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) && 1368 !S.getOpenCLOptions().isSupported("__opencl_c_subgroups", 1369 S.getLangOpts())) { 1370 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 1371 << 1 << Call->getDirectCallee() 1372 << "cl_khr_subgroups or __opencl_c_subgroups"; 1373 return true; 1374 } 1375 return false; 1376 } 1377 1378 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 1379 if (checkArgCount(S, TheCall, 2)) 1380 return true; 1381 1382 if (checkOpenCLSubgroupExt(S, TheCall)) 1383 return true; 1384 1385 // First argument is an ndrange_t type. 1386 Expr *NDRangeArg = TheCall->getArg(0); 1387 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1388 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1389 << TheCall->getDirectCallee() << "'ndrange_t'"; 1390 return true; 1391 } 1392 1393 Expr *BlockArg = TheCall->getArg(1); 1394 if (!isBlockPointer(BlockArg)) { 1395 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1396 << TheCall->getDirectCallee() << "block"; 1397 return true; 1398 } 1399 return checkOpenCLBlockArgs(S, BlockArg); 1400 } 1401 1402 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 1403 /// get_kernel_work_group_size 1404 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 1405 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 1406 if (checkArgCount(S, TheCall, 1)) 1407 return true; 1408 1409 Expr *BlockArg = TheCall->getArg(0); 1410 if (!isBlockPointer(BlockArg)) { 1411 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1412 << TheCall->getDirectCallee() << "block"; 1413 return true; 1414 } 1415 return checkOpenCLBlockArgs(S, BlockArg); 1416 } 1417 1418 /// Diagnose integer type and any valid implicit conversion to it. 1419 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 1420 const QualType &IntType); 1421 1422 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 1423 unsigned Start, unsigned End) { 1424 bool IllegalParams = false; 1425 for (unsigned I = Start; I <= End; ++I) 1426 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 1427 S.Context.getSizeType()); 1428 return IllegalParams; 1429 } 1430 1431 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 1432 /// 'local void*' parameter of passed block. 1433 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 1434 Expr *BlockArg, 1435 unsigned NumNonVarArgs) { 1436 const BlockPointerType *BPT = 1437 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1438 unsigned NumBlockParams = 1439 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 1440 unsigned TotalNumArgs = TheCall->getNumArgs(); 1441 1442 // For each argument passed to the block, a corresponding uint needs to 1443 // be passed to describe the size of the local memory. 1444 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 1445 S.Diag(TheCall->getBeginLoc(), 1446 diag::err_opencl_enqueue_kernel_local_size_args); 1447 return true; 1448 } 1449 1450 // Check that the sizes of the local memory are specified by integers. 1451 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 1452 TotalNumArgs - 1); 1453 } 1454 1455 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 1456 /// overload formats specified in Table 6.13.17.1. 1457 /// int enqueue_kernel(queue_t queue, 1458 /// kernel_enqueue_flags_t flags, 1459 /// const ndrange_t ndrange, 1460 /// void (^block)(void)) 1461 /// int enqueue_kernel(queue_t queue, 1462 /// kernel_enqueue_flags_t flags, 1463 /// const ndrange_t ndrange, 1464 /// uint num_events_in_wait_list, 1465 /// clk_event_t *event_wait_list, 1466 /// clk_event_t *event_ret, 1467 /// void (^block)(void)) 1468 /// int enqueue_kernel(queue_t queue, 1469 /// kernel_enqueue_flags_t flags, 1470 /// const ndrange_t ndrange, 1471 /// void (^block)(local void*, ...), 1472 /// uint size0, ...) 1473 /// int enqueue_kernel(queue_t queue, 1474 /// kernel_enqueue_flags_t flags, 1475 /// const ndrange_t ndrange, 1476 /// uint num_events_in_wait_list, 1477 /// clk_event_t *event_wait_list, 1478 /// clk_event_t *event_ret, 1479 /// void (^block)(local void*, ...), 1480 /// uint size0, ...) 1481 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 1482 unsigned NumArgs = TheCall->getNumArgs(); 1483 1484 if (NumArgs < 4) { 1485 S.Diag(TheCall->getBeginLoc(), 1486 diag::err_typecheck_call_too_few_args_at_least) 1487 << 0 << 4 << NumArgs; 1488 return true; 1489 } 1490 1491 Expr *Arg0 = TheCall->getArg(0); 1492 Expr *Arg1 = TheCall->getArg(1); 1493 Expr *Arg2 = TheCall->getArg(2); 1494 Expr *Arg3 = TheCall->getArg(3); 1495 1496 // First argument always needs to be a queue_t type. 1497 if (!Arg0->getType()->isQueueT()) { 1498 S.Diag(TheCall->getArg(0)->getBeginLoc(), 1499 diag::err_opencl_builtin_expected_type) 1500 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 1501 return true; 1502 } 1503 1504 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 1505 if (!Arg1->getType()->isIntegerType()) { 1506 S.Diag(TheCall->getArg(1)->getBeginLoc(), 1507 diag::err_opencl_builtin_expected_type) 1508 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 1509 return true; 1510 } 1511 1512 // Third argument is always an ndrange_t type. 1513 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1514 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1515 diag::err_opencl_builtin_expected_type) 1516 << TheCall->getDirectCallee() << "'ndrange_t'"; 1517 return true; 1518 } 1519 1520 // With four arguments, there is only one form that the function could be 1521 // called in: no events and no variable arguments. 1522 if (NumArgs == 4) { 1523 // check that the last argument is the right block type. 1524 if (!isBlockPointer(Arg3)) { 1525 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1526 << TheCall->getDirectCallee() << "block"; 1527 return true; 1528 } 1529 // we have a block type, check the prototype 1530 const BlockPointerType *BPT = 1531 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1532 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1533 S.Diag(Arg3->getBeginLoc(), 1534 diag::err_opencl_enqueue_kernel_blocks_no_args); 1535 return true; 1536 } 1537 return false; 1538 } 1539 // we can have block + varargs. 1540 if (isBlockPointer(Arg3)) 1541 return (checkOpenCLBlockArgs(S, Arg3) || 1542 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1543 // last two cases with either exactly 7 args or 7 args and varargs. 1544 if (NumArgs >= 7) { 1545 // check common block argument. 1546 Expr *Arg6 = TheCall->getArg(6); 1547 if (!isBlockPointer(Arg6)) { 1548 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1549 << TheCall->getDirectCallee() << "block"; 1550 return true; 1551 } 1552 if (checkOpenCLBlockArgs(S, Arg6)) 1553 return true; 1554 1555 // Forth argument has to be any integer type. 1556 if (!Arg3->getType()->isIntegerType()) { 1557 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1558 diag::err_opencl_builtin_expected_type) 1559 << TheCall->getDirectCallee() << "integer"; 1560 return true; 1561 } 1562 // check remaining common arguments. 1563 Expr *Arg4 = TheCall->getArg(4); 1564 Expr *Arg5 = TheCall->getArg(5); 1565 1566 // Fifth argument is always passed as a pointer to clk_event_t. 1567 if (!Arg4->isNullPointerConstant(S.Context, 1568 Expr::NPC_ValueDependentIsNotNull) && 1569 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1570 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1571 diag::err_opencl_builtin_expected_type) 1572 << TheCall->getDirectCallee() 1573 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1574 return true; 1575 } 1576 1577 // Sixth argument is always passed as a pointer to clk_event_t. 1578 if (!Arg5->isNullPointerConstant(S.Context, 1579 Expr::NPC_ValueDependentIsNotNull) && 1580 !(Arg5->getType()->isPointerType() && 1581 Arg5->getType()->getPointeeType()->isClkEventT())) { 1582 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1583 diag::err_opencl_builtin_expected_type) 1584 << TheCall->getDirectCallee() 1585 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1586 return true; 1587 } 1588 1589 if (NumArgs == 7) 1590 return false; 1591 1592 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1593 } 1594 1595 // None of the specific case has been detected, give generic error 1596 S.Diag(TheCall->getBeginLoc(), 1597 diag::err_opencl_enqueue_kernel_incorrect_args); 1598 return true; 1599 } 1600 1601 /// Returns OpenCL access qual. 1602 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1603 return D->getAttr<OpenCLAccessAttr>(); 1604 } 1605 1606 /// Returns true if pipe element type is different from the pointer. 1607 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1608 const Expr *Arg0 = Call->getArg(0); 1609 // First argument type should always be pipe. 1610 if (!Arg0->getType()->isPipeType()) { 1611 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1612 << Call->getDirectCallee() << Arg0->getSourceRange(); 1613 return true; 1614 } 1615 OpenCLAccessAttr *AccessQual = 1616 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1617 // Validates the access qualifier is compatible with the call. 1618 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1619 // read_only and write_only, and assumed to be read_only if no qualifier is 1620 // specified. 1621 switch (Call->getDirectCallee()->getBuiltinID()) { 1622 case Builtin::BIread_pipe: 1623 case Builtin::BIreserve_read_pipe: 1624 case Builtin::BIcommit_read_pipe: 1625 case Builtin::BIwork_group_reserve_read_pipe: 1626 case Builtin::BIsub_group_reserve_read_pipe: 1627 case Builtin::BIwork_group_commit_read_pipe: 1628 case Builtin::BIsub_group_commit_read_pipe: 1629 if (!(!AccessQual || AccessQual->isReadOnly())) { 1630 S.Diag(Arg0->getBeginLoc(), 1631 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1632 << "read_only" << Arg0->getSourceRange(); 1633 return true; 1634 } 1635 break; 1636 case Builtin::BIwrite_pipe: 1637 case Builtin::BIreserve_write_pipe: 1638 case Builtin::BIcommit_write_pipe: 1639 case Builtin::BIwork_group_reserve_write_pipe: 1640 case Builtin::BIsub_group_reserve_write_pipe: 1641 case Builtin::BIwork_group_commit_write_pipe: 1642 case Builtin::BIsub_group_commit_write_pipe: 1643 if (!(AccessQual && AccessQual->isWriteOnly())) { 1644 S.Diag(Arg0->getBeginLoc(), 1645 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1646 << "write_only" << Arg0->getSourceRange(); 1647 return true; 1648 } 1649 break; 1650 default: 1651 break; 1652 } 1653 return false; 1654 } 1655 1656 /// Returns true if pipe element type is different from the pointer. 1657 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1658 const Expr *Arg0 = Call->getArg(0); 1659 const Expr *ArgIdx = Call->getArg(Idx); 1660 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1661 const QualType EltTy = PipeTy->getElementType(); 1662 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1663 // The Idx argument should be a pointer and the type of the pointer and 1664 // the type of pipe element should also be the same. 1665 if (!ArgTy || 1666 !S.Context.hasSameType( 1667 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1668 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1669 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1670 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1671 return true; 1672 } 1673 return false; 1674 } 1675 1676 // Performs semantic analysis for the read/write_pipe call. 1677 // \param S Reference to the semantic analyzer. 1678 // \param Call A pointer to the builtin call. 1679 // \return True if a semantic error has been found, false otherwise. 1680 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1681 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1682 // functions have two forms. 1683 switch (Call->getNumArgs()) { 1684 case 2: 1685 if (checkOpenCLPipeArg(S, Call)) 1686 return true; 1687 // The call with 2 arguments should be 1688 // read/write_pipe(pipe T, T*). 1689 // Check packet type T. 1690 if (checkOpenCLPipePacketType(S, Call, 1)) 1691 return true; 1692 break; 1693 1694 case 4: { 1695 if (checkOpenCLPipeArg(S, Call)) 1696 return true; 1697 // The call with 4 arguments should be 1698 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1699 // Check reserve_id_t. 1700 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1701 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1702 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1703 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1704 return true; 1705 } 1706 1707 // Check the index. 1708 const Expr *Arg2 = Call->getArg(2); 1709 if (!Arg2->getType()->isIntegerType() && 1710 !Arg2->getType()->isUnsignedIntegerType()) { 1711 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1712 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1713 << Arg2->getType() << Arg2->getSourceRange(); 1714 return true; 1715 } 1716 1717 // Check packet type T. 1718 if (checkOpenCLPipePacketType(S, Call, 3)) 1719 return true; 1720 } break; 1721 default: 1722 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1723 << Call->getDirectCallee() << Call->getSourceRange(); 1724 return true; 1725 } 1726 1727 return false; 1728 } 1729 1730 // Performs a semantic analysis on the {work_group_/sub_group_ 1731 // /_}reserve_{read/write}_pipe 1732 // \param S Reference to the semantic analyzer. 1733 // \param Call The call to the builtin function to be analyzed. 1734 // \return True if a semantic error was found, false otherwise. 1735 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1736 if (checkArgCount(S, Call, 2)) 1737 return true; 1738 1739 if (checkOpenCLPipeArg(S, Call)) 1740 return true; 1741 1742 // Check the reserve size. 1743 if (!Call->getArg(1)->getType()->isIntegerType() && 1744 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1745 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1746 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1747 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1748 return true; 1749 } 1750 1751 // Since return type of reserve_read/write_pipe built-in function is 1752 // reserve_id_t, which is not defined in the builtin def file , we used int 1753 // as return type and need to override the return type of these functions. 1754 Call->setType(S.Context.OCLReserveIDTy); 1755 1756 return false; 1757 } 1758 1759 // Performs a semantic analysis on {work_group_/sub_group_ 1760 // /_}commit_{read/write}_pipe 1761 // \param S Reference to the semantic analyzer. 1762 // \param Call The call to the builtin function to be analyzed. 1763 // \return True if a semantic error was found, false otherwise. 1764 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1765 if (checkArgCount(S, Call, 2)) 1766 return true; 1767 1768 if (checkOpenCLPipeArg(S, Call)) 1769 return true; 1770 1771 // Check reserve_id_t. 1772 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1773 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1774 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1775 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1776 return true; 1777 } 1778 1779 return false; 1780 } 1781 1782 // Performs a semantic analysis on the call to built-in Pipe 1783 // Query Functions. 1784 // \param S Reference to the semantic analyzer. 1785 // \param Call The call to the builtin function to be analyzed. 1786 // \return True if a semantic error was found, false otherwise. 1787 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1788 if (checkArgCount(S, Call, 1)) 1789 return true; 1790 1791 if (!Call->getArg(0)->getType()->isPipeType()) { 1792 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1793 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1794 return true; 1795 } 1796 1797 return false; 1798 } 1799 1800 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1801 // Performs semantic analysis for the to_global/local/private call. 1802 // \param S Reference to the semantic analyzer. 1803 // \param BuiltinID ID of the builtin function. 1804 // \param Call A pointer to the builtin call. 1805 // \return True if a semantic error has been found, false otherwise. 1806 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1807 CallExpr *Call) { 1808 if (checkArgCount(S, Call, 1)) 1809 return true; 1810 1811 auto RT = Call->getArg(0)->getType(); 1812 if (!RT->isPointerType() || RT->getPointeeType() 1813 .getAddressSpace() == LangAS::opencl_constant) { 1814 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1815 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1816 return true; 1817 } 1818 1819 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1820 S.Diag(Call->getArg(0)->getBeginLoc(), 1821 diag::warn_opencl_generic_address_space_arg) 1822 << Call->getDirectCallee()->getNameInfo().getAsString() 1823 << Call->getArg(0)->getSourceRange(); 1824 } 1825 1826 RT = RT->getPointeeType(); 1827 auto Qual = RT.getQualifiers(); 1828 switch (BuiltinID) { 1829 case Builtin::BIto_global: 1830 Qual.setAddressSpace(LangAS::opencl_global); 1831 break; 1832 case Builtin::BIto_local: 1833 Qual.setAddressSpace(LangAS::opencl_local); 1834 break; 1835 case Builtin::BIto_private: 1836 Qual.setAddressSpace(LangAS::opencl_private); 1837 break; 1838 default: 1839 llvm_unreachable("Invalid builtin function"); 1840 } 1841 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1842 RT.getUnqualifiedType(), Qual))); 1843 1844 return false; 1845 } 1846 1847 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1848 if (checkArgCount(S, TheCall, 1)) 1849 return ExprError(); 1850 1851 // Compute __builtin_launder's parameter type from the argument. 1852 // The parameter type is: 1853 // * The type of the argument if it's not an array or function type, 1854 // Otherwise, 1855 // * The decayed argument type. 1856 QualType ParamTy = [&]() { 1857 QualType ArgTy = TheCall->getArg(0)->getType(); 1858 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1859 return S.Context.getPointerType(Ty->getElementType()); 1860 if (ArgTy->isFunctionType()) { 1861 return S.Context.getPointerType(ArgTy); 1862 } 1863 return ArgTy; 1864 }(); 1865 1866 TheCall->setType(ParamTy); 1867 1868 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1869 if (!ParamTy->isPointerType()) 1870 return 0; 1871 if (ParamTy->isFunctionPointerType()) 1872 return 1; 1873 if (ParamTy->isVoidPointerType()) 1874 return 2; 1875 return llvm::Optional<unsigned>{}; 1876 }(); 1877 if (DiagSelect.hasValue()) { 1878 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1879 << DiagSelect.getValue() << TheCall->getSourceRange(); 1880 return ExprError(); 1881 } 1882 1883 // We either have an incomplete class type, or we have a class template 1884 // whose instantiation has not been forced. Example: 1885 // 1886 // template <class T> struct Foo { T value; }; 1887 // Foo<int> *p = nullptr; 1888 // auto *d = __builtin_launder(p); 1889 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1890 diag::err_incomplete_type)) 1891 return ExprError(); 1892 1893 assert(ParamTy->getPointeeType()->isObjectType() && 1894 "Unhandled non-object pointer case"); 1895 1896 InitializedEntity Entity = 1897 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1898 ExprResult Arg = 1899 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1900 if (Arg.isInvalid()) 1901 return ExprError(); 1902 TheCall->setArg(0, Arg.get()); 1903 1904 return TheCall; 1905 } 1906 1907 // Emit an error and return true if the current object format type is in the 1908 // list of unsupported types. 1909 static bool CheckBuiltinTargetNotInUnsupported( 1910 Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1911 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) { 1912 llvm::Triple::ObjectFormatType CurObjFormat = 1913 S.getASTContext().getTargetInfo().getTriple().getObjectFormat(); 1914 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) { 1915 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1916 << TheCall->getSourceRange(); 1917 return true; 1918 } 1919 return false; 1920 } 1921 1922 // Emit an error and return true if the current architecture is not in the list 1923 // of supported architectures. 1924 static bool 1925 CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1926 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1927 llvm::Triple::ArchType CurArch = 1928 S.getASTContext().getTargetInfo().getTriple().getArch(); 1929 if (llvm::is_contained(SupportedArchs, CurArch)) 1930 return false; 1931 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1932 << TheCall->getSourceRange(); 1933 return true; 1934 } 1935 1936 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1937 SourceLocation CallSiteLoc); 1938 1939 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1940 CallExpr *TheCall) { 1941 switch (TI.getTriple().getArch()) { 1942 default: 1943 // Some builtins don't require additional checking, so just consider these 1944 // acceptable. 1945 return false; 1946 case llvm::Triple::arm: 1947 case llvm::Triple::armeb: 1948 case llvm::Triple::thumb: 1949 case llvm::Triple::thumbeb: 1950 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1951 case llvm::Triple::aarch64: 1952 case llvm::Triple::aarch64_32: 1953 case llvm::Triple::aarch64_be: 1954 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1955 case llvm::Triple::bpfeb: 1956 case llvm::Triple::bpfel: 1957 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1958 case llvm::Triple::hexagon: 1959 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1960 case llvm::Triple::mips: 1961 case llvm::Triple::mipsel: 1962 case llvm::Triple::mips64: 1963 case llvm::Triple::mips64el: 1964 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1965 case llvm::Triple::systemz: 1966 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1967 case llvm::Triple::x86: 1968 case llvm::Triple::x86_64: 1969 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1970 case llvm::Triple::ppc: 1971 case llvm::Triple::ppcle: 1972 case llvm::Triple::ppc64: 1973 case llvm::Triple::ppc64le: 1974 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1975 case llvm::Triple::amdgcn: 1976 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1977 case llvm::Triple::riscv32: 1978 case llvm::Triple::riscv64: 1979 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1980 } 1981 } 1982 1983 ExprResult 1984 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1985 CallExpr *TheCall) { 1986 ExprResult TheCallResult(TheCall); 1987 1988 // Find out if any arguments are required to be integer constant expressions. 1989 unsigned ICEArguments = 0; 1990 ASTContext::GetBuiltinTypeError Error; 1991 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1992 if (Error != ASTContext::GE_None) 1993 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1994 1995 // If any arguments are required to be ICE's, check and diagnose. 1996 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1997 // Skip arguments not required to be ICE's. 1998 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1999 2000 llvm::APSInt Result; 2001 // If we don't have enough arguments, continue so we can issue better 2002 // diagnostic in checkArgCount(...) 2003 if (ArgNo < TheCall->getNumArgs() && 2004 SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 2005 return true; 2006 ICEArguments &= ~(1 << ArgNo); 2007 } 2008 2009 switch (BuiltinID) { 2010 case Builtin::BI__builtin___CFStringMakeConstantString: 2011 // CFStringMakeConstantString is currently not implemented for GOFF (i.e., 2012 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported 2013 if (CheckBuiltinTargetNotInUnsupported( 2014 *this, BuiltinID, TheCall, 2015 {llvm::Triple::GOFF, llvm::Triple::XCOFF})) 2016 return ExprError(); 2017 assert(TheCall->getNumArgs() == 1 && 2018 "Wrong # arguments to builtin CFStringMakeConstantString"); 2019 if (CheckObjCString(TheCall->getArg(0))) 2020 return ExprError(); 2021 break; 2022 case Builtin::BI__builtin_ms_va_start: 2023 case Builtin::BI__builtin_stdarg_start: 2024 case Builtin::BI__builtin_va_start: 2025 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 2026 return ExprError(); 2027 break; 2028 case Builtin::BI__va_start: { 2029 switch (Context.getTargetInfo().getTriple().getArch()) { 2030 case llvm::Triple::aarch64: 2031 case llvm::Triple::arm: 2032 case llvm::Triple::thumb: 2033 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 2034 return ExprError(); 2035 break; 2036 default: 2037 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 2038 return ExprError(); 2039 break; 2040 } 2041 break; 2042 } 2043 2044 // The acquire, release, and no fence variants are ARM and AArch64 only. 2045 case Builtin::BI_interlockedbittestandset_acq: 2046 case Builtin::BI_interlockedbittestandset_rel: 2047 case Builtin::BI_interlockedbittestandset_nf: 2048 case Builtin::BI_interlockedbittestandreset_acq: 2049 case Builtin::BI_interlockedbittestandreset_rel: 2050 case Builtin::BI_interlockedbittestandreset_nf: 2051 if (CheckBuiltinTargetInSupported( 2052 *this, BuiltinID, TheCall, 2053 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 2054 return ExprError(); 2055 break; 2056 2057 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 2058 case Builtin::BI_bittest64: 2059 case Builtin::BI_bittestandcomplement64: 2060 case Builtin::BI_bittestandreset64: 2061 case Builtin::BI_bittestandset64: 2062 case Builtin::BI_interlockedbittestandreset64: 2063 case Builtin::BI_interlockedbittestandset64: 2064 if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall, 2065 {llvm::Triple::x86_64, llvm::Triple::arm, 2066 llvm::Triple::thumb, 2067 llvm::Triple::aarch64})) 2068 return ExprError(); 2069 break; 2070 2071 case Builtin::BI__builtin_isgreater: 2072 case Builtin::BI__builtin_isgreaterequal: 2073 case Builtin::BI__builtin_isless: 2074 case Builtin::BI__builtin_islessequal: 2075 case Builtin::BI__builtin_islessgreater: 2076 case Builtin::BI__builtin_isunordered: 2077 if (SemaBuiltinUnorderedCompare(TheCall)) 2078 return ExprError(); 2079 break; 2080 case Builtin::BI__builtin_fpclassify: 2081 if (SemaBuiltinFPClassification(TheCall, 6)) 2082 return ExprError(); 2083 break; 2084 case Builtin::BI__builtin_isfinite: 2085 case Builtin::BI__builtin_isinf: 2086 case Builtin::BI__builtin_isinf_sign: 2087 case Builtin::BI__builtin_isnan: 2088 case Builtin::BI__builtin_isnormal: 2089 case Builtin::BI__builtin_signbit: 2090 case Builtin::BI__builtin_signbitf: 2091 case Builtin::BI__builtin_signbitl: 2092 if (SemaBuiltinFPClassification(TheCall, 1)) 2093 return ExprError(); 2094 break; 2095 case Builtin::BI__builtin_shufflevector: 2096 return SemaBuiltinShuffleVector(TheCall); 2097 // TheCall will be freed by the smart pointer here, but that's fine, since 2098 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 2099 case Builtin::BI__builtin_prefetch: 2100 if (SemaBuiltinPrefetch(TheCall)) 2101 return ExprError(); 2102 break; 2103 case Builtin::BI__builtin_alloca_with_align: 2104 case Builtin::BI__builtin_alloca_with_align_uninitialized: 2105 if (SemaBuiltinAllocaWithAlign(TheCall)) 2106 return ExprError(); 2107 LLVM_FALLTHROUGH; 2108 case Builtin::BI__builtin_alloca: 2109 case Builtin::BI__builtin_alloca_uninitialized: 2110 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 2111 << TheCall->getDirectCallee(); 2112 break; 2113 case Builtin::BI__arithmetic_fence: 2114 if (SemaBuiltinArithmeticFence(TheCall)) 2115 return ExprError(); 2116 break; 2117 case Builtin::BI__assume: 2118 case Builtin::BI__builtin_assume: 2119 if (SemaBuiltinAssume(TheCall)) 2120 return ExprError(); 2121 break; 2122 case Builtin::BI__builtin_assume_aligned: 2123 if (SemaBuiltinAssumeAligned(TheCall)) 2124 return ExprError(); 2125 break; 2126 case Builtin::BI__builtin_dynamic_object_size: 2127 case Builtin::BI__builtin_object_size: 2128 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 2129 return ExprError(); 2130 break; 2131 case Builtin::BI__builtin_longjmp: 2132 if (SemaBuiltinLongjmp(TheCall)) 2133 return ExprError(); 2134 break; 2135 case Builtin::BI__builtin_setjmp: 2136 if (SemaBuiltinSetjmp(TheCall)) 2137 return ExprError(); 2138 break; 2139 case Builtin::BI__builtin_classify_type: 2140 if (checkArgCount(*this, TheCall, 1)) return true; 2141 TheCall->setType(Context.IntTy); 2142 break; 2143 case Builtin::BI__builtin_complex: 2144 if (SemaBuiltinComplex(TheCall)) 2145 return ExprError(); 2146 break; 2147 case Builtin::BI__builtin_constant_p: { 2148 if (checkArgCount(*this, TheCall, 1)) return true; 2149 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 2150 if (Arg.isInvalid()) return true; 2151 TheCall->setArg(0, Arg.get()); 2152 TheCall->setType(Context.IntTy); 2153 break; 2154 } 2155 case Builtin::BI__builtin_launder: 2156 return SemaBuiltinLaunder(*this, TheCall); 2157 case Builtin::BI__sync_fetch_and_add: 2158 case Builtin::BI__sync_fetch_and_add_1: 2159 case Builtin::BI__sync_fetch_and_add_2: 2160 case Builtin::BI__sync_fetch_and_add_4: 2161 case Builtin::BI__sync_fetch_and_add_8: 2162 case Builtin::BI__sync_fetch_and_add_16: 2163 case Builtin::BI__sync_fetch_and_sub: 2164 case Builtin::BI__sync_fetch_and_sub_1: 2165 case Builtin::BI__sync_fetch_and_sub_2: 2166 case Builtin::BI__sync_fetch_and_sub_4: 2167 case Builtin::BI__sync_fetch_and_sub_8: 2168 case Builtin::BI__sync_fetch_and_sub_16: 2169 case Builtin::BI__sync_fetch_and_or: 2170 case Builtin::BI__sync_fetch_and_or_1: 2171 case Builtin::BI__sync_fetch_and_or_2: 2172 case Builtin::BI__sync_fetch_and_or_4: 2173 case Builtin::BI__sync_fetch_and_or_8: 2174 case Builtin::BI__sync_fetch_and_or_16: 2175 case Builtin::BI__sync_fetch_and_and: 2176 case Builtin::BI__sync_fetch_and_and_1: 2177 case Builtin::BI__sync_fetch_and_and_2: 2178 case Builtin::BI__sync_fetch_and_and_4: 2179 case Builtin::BI__sync_fetch_and_and_8: 2180 case Builtin::BI__sync_fetch_and_and_16: 2181 case Builtin::BI__sync_fetch_and_xor: 2182 case Builtin::BI__sync_fetch_and_xor_1: 2183 case Builtin::BI__sync_fetch_and_xor_2: 2184 case Builtin::BI__sync_fetch_and_xor_4: 2185 case Builtin::BI__sync_fetch_and_xor_8: 2186 case Builtin::BI__sync_fetch_and_xor_16: 2187 case Builtin::BI__sync_fetch_and_nand: 2188 case Builtin::BI__sync_fetch_and_nand_1: 2189 case Builtin::BI__sync_fetch_and_nand_2: 2190 case Builtin::BI__sync_fetch_and_nand_4: 2191 case Builtin::BI__sync_fetch_and_nand_8: 2192 case Builtin::BI__sync_fetch_and_nand_16: 2193 case Builtin::BI__sync_add_and_fetch: 2194 case Builtin::BI__sync_add_and_fetch_1: 2195 case Builtin::BI__sync_add_and_fetch_2: 2196 case Builtin::BI__sync_add_and_fetch_4: 2197 case Builtin::BI__sync_add_and_fetch_8: 2198 case Builtin::BI__sync_add_and_fetch_16: 2199 case Builtin::BI__sync_sub_and_fetch: 2200 case Builtin::BI__sync_sub_and_fetch_1: 2201 case Builtin::BI__sync_sub_and_fetch_2: 2202 case Builtin::BI__sync_sub_and_fetch_4: 2203 case Builtin::BI__sync_sub_and_fetch_8: 2204 case Builtin::BI__sync_sub_and_fetch_16: 2205 case Builtin::BI__sync_and_and_fetch: 2206 case Builtin::BI__sync_and_and_fetch_1: 2207 case Builtin::BI__sync_and_and_fetch_2: 2208 case Builtin::BI__sync_and_and_fetch_4: 2209 case Builtin::BI__sync_and_and_fetch_8: 2210 case Builtin::BI__sync_and_and_fetch_16: 2211 case Builtin::BI__sync_or_and_fetch: 2212 case Builtin::BI__sync_or_and_fetch_1: 2213 case Builtin::BI__sync_or_and_fetch_2: 2214 case Builtin::BI__sync_or_and_fetch_4: 2215 case Builtin::BI__sync_or_and_fetch_8: 2216 case Builtin::BI__sync_or_and_fetch_16: 2217 case Builtin::BI__sync_xor_and_fetch: 2218 case Builtin::BI__sync_xor_and_fetch_1: 2219 case Builtin::BI__sync_xor_and_fetch_2: 2220 case Builtin::BI__sync_xor_and_fetch_4: 2221 case Builtin::BI__sync_xor_and_fetch_8: 2222 case Builtin::BI__sync_xor_and_fetch_16: 2223 case Builtin::BI__sync_nand_and_fetch: 2224 case Builtin::BI__sync_nand_and_fetch_1: 2225 case Builtin::BI__sync_nand_and_fetch_2: 2226 case Builtin::BI__sync_nand_and_fetch_4: 2227 case Builtin::BI__sync_nand_and_fetch_8: 2228 case Builtin::BI__sync_nand_and_fetch_16: 2229 case Builtin::BI__sync_val_compare_and_swap: 2230 case Builtin::BI__sync_val_compare_and_swap_1: 2231 case Builtin::BI__sync_val_compare_and_swap_2: 2232 case Builtin::BI__sync_val_compare_and_swap_4: 2233 case Builtin::BI__sync_val_compare_and_swap_8: 2234 case Builtin::BI__sync_val_compare_and_swap_16: 2235 case Builtin::BI__sync_bool_compare_and_swap: 2236 case Builtin::BI__sync_bool_compare_and_swap_1: 2237 case Builtin::BI__sync_bool_compare_and_swap_2: 2238 case Builtin::BI__sync_bool_compare_and_swap_4: 2239 case Builtin::BI__sync_bool_compare_and_swap_8: 2240 case Builtin::BI__sync_bool_compare_and_swap_16: 2241 case Builtin::BI__sync_lock_test_and_set: 2242 case Builtin::BI__sync_lock_test_and_set_1: 2243 case Builtin::BI__sync_lock_test_and_set_2: 2244 case Builtin::BI__sync_lock_test_and_set_4: 2245 case Builtin::BI__sync_lock_test_and_set_8: 2246 case Builtin::BI__sync_lock_test_and_set_16: 2247 case Builtin::BI__sync_lock_release: 2248 case Builtin::BI__sync_lock_release_1: 2249 case Builtin::BI__sync_lock_release_2: 2250 case Builtin::BI__sync_lock_release_4: 2251 case Builtin::BI__sync_lock_release_8: 2252 case Builtin::BI__sync_lock_release_16: 2253 case Builtin::BI__sync_swap: 2254 case Builtin::BI__sync_swap_1: 2255 case Builtin::BI__sync_swap_2: 2256 case Builtin::BI__sync_swap_4: 2257 case Builtin::BI__sync_swap_8: 2258 case Builtin::BI__sync_swap_16: 2259 return SemaBuiltinAtomicOverloaded(TheCallResult); 2260 case Builtin::BI__sync_synchronize: 2261 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 2262 << TheCall->getCallee()->getSourceRange(); 2263 break; 2264 case Builtin::BI__builtin_nontemporal_load: 2265 case Builtin::BI__builtin_nontemporal_store: 2266 return SemaBuiltinNontemporalOverloaded(TheCallResult); 2267 case Builtin::BI__builtin_memcpy_inline: { 2268 if (checkArgCount(*this, TheCall, 3)) 2269 return ExprError(); 2270 auto ArgArrayConversionFailed = [&](unsigned Arg) { 2271 ExprResult ArgExpr = 2272 DefaultFunctionArrayLvalueConversion(TheCall->getArg(Arg)); 2273 if (ArgExpr.isInvalid()) 2274 return true; 2275 TheCall->setArg(Arg, ArgExpr.get()); 2276 return false; 2277 }; 2278 2279 if (ArgArrayConversionFailed(0) || ArgArrayConversionFailed(1)) 2280 return true; 2281 clang::Expr *SizeOp = TheCall->getArg(2); 2282 // We warn about copying to or from `nullptr` pointers when `size` is 2283 // greater than 0. When `size` is value dependent we cannot evaluate its 2284 // value so we bail out. 2285 if (SizeOp->isValueDependent()) 2286 break; 2287 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 2288 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 2289 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 2290 } 2291 break; 2292 } 2293 #define BUILTIN(ID, TYPE, ATTRS) 2294 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 2295 case Builtin::BI##ID: \ 2296 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 2297 #include "clang/Basic/Builtins.def" 2298 case Builtin::BI__annotation: 2299 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 2300 return ExprError(); 2301 break; 2302 case Builtin::BI__builtin_annotation: 2303 if (SemaBuiltinAnnotation(*this, TheCall)) 2304 return ExprError(); 2305 break; 2306 case Builtin::BI__builtin_addressof: 2307 if (SemaBuiltinAddressof(*this, TheCall)) 2308 return ExprError(); 2309 break; 2310 case Builtin::BI__builtin_function_start: 2311 if (SemaBuiltinFunctionStart(*this, TheCall)) 2312 return ExprError(); 2313 break; 2314 case Builtin::BI__builtin_is_aligned: 2315 case Builtin::BI__builtin_align_up: 2316 case Builtin::BI__builtin_align_down: 2317 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 2318 return ExprError(); 2319 break; 2320 case Builtin::BI__builtin_add_overflow: 2321 case Builtin::BI__builtin_sub_overflow: 2322 case Builtin::BI__builtin_mul_overflow: 2323 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 2324 return ExprError(); 2325 break; 2326 case Builtin::BI__builtin_operator_new: 2327 case Builtin::BI__builtin_operator_delete: { 2328 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 2329 ExprResult Res = 2330 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 2331 if (Res.isInvalid()) 2332 CorrectDelayedTyposInExpr(TheCallResult.get()); 2333 return Res; 2334 } 2335 case Builtin::BI__builtin_dump_struct: 2336 return SemaBuiltinDumpStruct(*this, TheCall); 2337 case Builtin::BI__builtin_expect_with_probability: { 2338 // We first want to ensure we are called with 3 arguments 2339 if (checkArgCount(*this, TheCall, 3)) 2340 return ExprError(); 2341 // then check probability is constant float in range [0.0, 1.0] 2342 const Expr *ProbArg = TheCall->getArg(2); 2343 SmallVector<PartialDiagnosticAt, 8> Notes; 2344 Expr::EvalResult Eval; 2345 Eval.Diag = &Notes; 2346 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 2347 !Eval.Val.isFloat()) { 2348 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 2349 << ProbArg->getSourceRange(); 2350 for (const PartialDiagnosticAt &PDiag : Notes) 2351 Diag(PDiag.first, PDiag.second); 2352 return ExprError(); 2353 } 2354 llvm::APFloat Probability = Eval.Val.getFloat(); 2355 bool LoseInfo = false; 2356 Probability.convert(llvm::APFloat::IEEEdouble(), 2357 llvm::RoundingMode::Dynamic, &LoseInfo); 2358 if (!(Probability >= llvm::APFloat(0.0) && 2359 Probability <= llvm::APFloat(1.0))) { 2360 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 2361 << ProbArg->getSourceRange(); 2362 return ExprError(); 2363 } 2364 break; 2365 } 2366 case Builtin::BI__builtin_preserve_access_index: 2367 if (SemaBuiltinPreserveAI(*this, TheCall)) 2368 return ExprError(); 2369 break; 2370 case Builtin::BI__builtin_call_with_static_chain: 2371 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 2372 return ExprError(); 2373 break; 2374 case Builtin::BI__exception_code: 2375 case Builtin::BI_exception_code: 2376 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 2377 diag::err_seh___except_block)) 2378 return ExprError(); 2379 break; 2380 case Builtin::BI__exception_info: 2381 case Builtin::BI_exception_info: 2382 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 2383 diag::err_seh___except_filter)) 2384 return ExprError(); 2385 break; 2386 case Builtin::BI__GetExceptionInfo: 2387 if (checkArgCount(*this, TheCall, 1)) 2388 return ExprError(); 2389 2390 if (CheckCXXThrowOperand( 2391 TheCall->getBeginLoc(), 2392 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 2393 TheCall)) 2394 return ExprError(); 2395 2396 TheCall->setType(Context.VoidPtrTy); 2397 break; 2398 case Builtin::BIaddressof: 2399 case Builtin::BI__addressof: 2400 case Builtin::BIforward: 2401 case Builtin::BImove: 2402 case Builtin::BImove_if_noexcept: 2403 case Builtin::BIas_const: { 2404 // These are all expected to be of the form 2405 // T &/&&/* f(U &/&&) 2406 // where T and U only differ in qualification. 2407 if (checkArgCount(*this, TheCall, 1)) 2408 return ExprError(); 2409 QualType Param = FDecl->getParamDecl(0)->getType(); 2410 QualType Result = FDecl->getReturnType(); 2411 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof || 2412 BuiltinID == Builtin::BI__addressof; 2413 if (!(Param->isReferenceType() && 2414 (ReturnsPointer ? Result->isPointerType() 2415 : Result->isReferenceType()) && 2416 Context.hasSameUnqualifiedType(Param->getPointeeType(), 2417 Result->getPointeeType()))) { 2418 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported) 2419 << FDecl; 2420 return ExprError(); 2421 } 2422 break; 2423 } 2424 // OpenCL v2.0, s6.13.16 - Pipe functions 2425 case Builtin::BIread_pipe: 2426 case Builtin::BIwrite_pipe: 2427 // Since those two functions are declared with var args, we need a semantic 2428 // check for the argument. 2429 if (SemaBuiltinRWPipe(*this, TheCall)) 2430 return ExprError(); 2431 break; 2432 case Builtin::BIreserve_read_pipe: 2433 case Builtin::BIreserve_write_pipe: 2434 case Builtin::BIwork_group_reserve_read_pipe: 2435 case Builtin::BIwork_group_reserve_write_pipe: 2436 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 2437 return ExprError(); 2438 break; 2439 case Builtin::BIsub_group_reserve_read_pipe: 2440 case Builtin::BIsub_group_reserve_write_pipe: 2441 if (checkOpenCLSubgroupExt(*this, TheCall) || 2442 SemaBuiltinReserveRWPipe(*this, TheCall)) 2443 return ExprError(); 2444 break; 2445 case Builtin::BIcommit_read_pipe: 2446 case Builtin::BIcommit_write_pipe: 2447 case Builtin::BIwork_group_commit_read_pipe: 2448 case Builtin::BIwork_group_commit_write_pipe: 2449 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 2450 return ExprError(); 2451 break; 2452 case Builtin::BIsub_group_commit_read_pipe: 2453 case Builtin::BIsub_group_commit_write_pipe: 2454 if (checkOpenCLSubgroupExt(*this, TheCall) || 2455 SemaBuiltinCommitRWPipe(*this, TheCall)) 2456 return ExprError(); 2457 break; 2458 case Builtin::BIget_pipe_num_packets: 2459 case Builtin::BIget_pipe_max_packets: 2460 if (SemaBuiltinPipePackets(*this, TheCall)) 2461 return ExprError(); 2462 break; 2463 case Builtin::BIto_global: 2464 case Builtin::BIto_local: 2465 case Builtin::BIto_private: 2466 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 2467 return ExprError(); 2468 break; 2469 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 2470 case Builtin::BIenqueue_kernel: 2471 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 2472 return ExprError(); 2473 break; 2474 case Builtin::BIget_kernel_work_group_size: 2475 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 2476 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 2477 return ExprError(); 2478 break; 2479 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 2480 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 2481 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 2482 return ExprError(); 2483 break; 2484 case Builtin::BI__builtin_os_log_format: 2485 Cleanup.setExprNeedsCleanups(true); 2486 LLVM_FALLTHROUGH; 2487 case Builtin::BI__builtin_os_log_format_buffer_size: 2488 if (SemaBuiltinOSLogFormat(TheCall)) 2489 return ExprError(); 2490 break; 2491 case Builtin::BI__builtin_frame_address: 2492 case Builtin::BI__builtin_return_address: { 2493 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 2494 return ExprError(); 2495 2496 // -Wframe-address warning if non-zero passed to builtin 2497 // return/frame address. 2498 Expr::EvalResult Result; 2499 if (!TheCall->getArg(0)->isValueDependent() && 2500 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 2501 Result.Val.getInt() != 0) 2502 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 2503 << ((BuiltinID == Builtin::BI__builtin_return_address) 2504 ? "__builtin_return_address" 2505 : "__builtin_frame_address") 2506 << TheCall->getSourceRange(); 2507 break; 2508 } 2509 2510 // __builtin_elementwise_abs restricts the element type to signed integers or 2511 // floating point types only. 2512 case Builtin::BI__builtin_elementwise_abs: { 2513 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2514 return ExprError(); 2515 2516 QualType ArgTy = TheCall->getArg(0)->getType(); 2517 QualType EltTy = ArgTy; 2518 2519 if (auto *VecTy = EltTy->getAs<VectorType>()) 2520 EltTy = VecTy->getElementType(); 2521 if (EltTy->isUnsignedIntegerType()) { 2522 Diag(TheCall->getArg(0)->getBeginLoc(), 2523 diag::err_builtin_invalid_arg_type) 2524 << 1 << /* signed integer or float ty*/ 3 << ArgTy; 2525 return ExprError(); 2526 } 2527 break; 2528 } 2529 2530 // These builtins restrict the element type to floating point 2531 // types only. 2532 case Builtin::BI__builtin_elementwise_ceil: 2533 case Builtin::BI__builtin_elementwise_floor: 2534 case Builtin::BI__builtin_elementwise_roundeven: 2535 case Builtin::BI__builtin_elementwise_trunc: { 2536 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2537 return ExprError(); 2538 2539 QualType ArgTy = TheCall->getArg(0)->getType(); 2540 QualType EltTy = ArgTy; 2541 2542 if (auto *VecTy = EltTy->getAs<VectorType>()) 2543 EltTy = VecTy->getElementType(); 2544 if (!EltTy->isFloatingType()) { 2545 Diag(TheCall->getArg(0)->getBeginLoc(), 2546 diag::err_builtin_invalid_arg_type) 2547 << 1 << /* float ty*/ 5 << ArgTy; 2548 2549 return ExprError(); 2550 } 2551 break; 2552 } 2553 2554 // These builtins restrict the element type to integer 2555 // types only. 2556 case Builtin::BI__builtin_elementwise_add_sat: 2557 case Builtin::BI__builtin_elementwise_sub_sat: { 2558 if (SemaBuiltinElementwiseMath(TheCall)) 2559 return ExprError(); 2560 2561 const Expr *Arg = TheCall->getArg(0); 2562 QualType ArgTy = Arg->getType(); 2563 QualType EltTy = ArgTy; 2564 2565 if (auto *VecTy = EltTy->getAs<VectorType>()) 2566 EltTy = VecTy->getElementType(); 2567 2568 if (!EltTy->isIntegerType()) { 2569 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2570 << 1 << /* integer ty */ 6 << ArgTy; 2571 return ExprError(); 2572 } 2573 break; 2574 } 2575 2576 case Builtin::BI__builtin_elementwise_min: 2577 case Builtin::BI__builtin_elementwise_max: 2578 if (SemaBuiltinElementwiseMath(TheCall)) 2579 return ExprError(); 2580 break; 2581 case Builtin::BI__builtin_reduce_max: 2582 case Builtin::BI__builtin_reduce_min: { 2583 if (PrepareBuiltinReduceMathOneArgCall(TheCall)) 2584 return ExprError(); 2585 2586 const Expr *Arg = TheCall->getArg(0); 2587 const auto *TyA = Arg->getType()->getAs<VectorType>(); 2588 if (!TyA) { 2589 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2590 << 1 << /* vector ty*/ 4 << Arg->getType(); 2591 return ExprError(); 2592 } 2593 2594 TheCall->setType(TyA->getElementType()); 2595 break; 2596 } 2597 2598 // These builtins support vectors of integers only. 2599 // TODO: ADD should support floating-point types. 2600 case Builtin::BI__builtin_reduce_add: 2601 case Builtin::BI__builtin_reduce_xor: 2602 case Builtin::BI__builtin_reduce_or: 2603 case Builtin::BI__builtin_reduce_and: { 2604 if (PrepareBuiltinReduceMathOneArgCall(TheCall)) 2605 return ExprError(); 2606 2607 const Expr *Arg = TheCall->getArg(0); 2608 const auto *TyA = Arg->getType()->getAs<VectorType>(); 2609 if (!TyA || !TyA->getElementType()->isIntegerType()) { 2610 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2611 << 1 << /* vector of integers */ 6 << Arg->getType(); 2612 return ExprError(); 2613 } 2614 TheCall->setType(TyA->getElementType()); 2615 break; 2616 } 2617 2618 case Builtin::BI__builtin_matrix_transpose: 2619 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 2620 2621 case Builtin::BI__builtin_matrix_column_major_load: 2622 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 2623 2624 case Builtin::BI__builtin_matrix_column_major_store: 2625 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 2626 2627 case Builtin::BI__builtin_get_device_side_mangled_name: { 2628 auto Check = [](CallExpr *TheCall) { 2629 if (TheCall->getNumArgs() != 1) 2630 return false; 2631 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 2632 if (!DRE) 2633 return false; 2634 auto *D = DRE->getDecl(); 2635 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 2636 return false; 2637 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 2638 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2639 }; 2640 if (!Check(TheCall)) { 2641 Diag(TheCall->getBeginLoc(), 2642 diag::err_hip_invalid_args_builtin_mangled_name); 2643 return ExprError(); 2644 } 2645 } 2646 } 2647 2648 // Since the target specific builtins for each arch overlap, only check those 2649 // of the arch we are compiling for. 2650 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2651 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2652 assert(Context.getAuxTargetInfo() && 2653 "Aux Target Builtin, but not an aux target?"); 2654 2655 if (CheckTSBuiltinFunctionCall( 2656 *Context.getAuxTargetInfo(), 2657 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2658 return ExprError(); 2659 } else { 2660 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2661 TheCall)) 2662 return ExprError(); 2663 } 2664 } 2665 2666 return TheCallResult; 2667 } 2668 2669 // Get the valid immediate range for the specified NEON type code. 2670 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2671 NeonTypeFlags Type(t); 2672 int IsQuad = ForceQuad ? true : Type.isQuad(); 2673 switch (Type.getEltType()) { 2674 case NeonTypeFlags::Int8: 2675 case NeonTypeFlags::Poly8: 2676 return shift ? 7 : (8 << IsQuad) - 1; 2677 case NeonTypeFlags::Int16: 2678 case NeonTypeFlags::Poly16: 2679 return shift ? 15 : (4 << IsQuad) - 1; 2680 case NeonTypeFlags::Int32: 2681 return shift ? 31 : (2 << IsQuad) - 1; 2682 case NeonTypeFlags::Int64: 2683 case NeonTypeFlags::Poly64: 2684 return shift ? 63 : (1 << IsQuad) - 1; 2685 case NeonTypeFlags::Poly128: 2686 return shift ? 127 : (1 << IsQuad) - 1; 2687 case NeonTypeFlags::Float16: 2688 assert(!shift && "cannot shift float types!"); 2689 return (4 << IsQuad) - 1; 2690 case NeonTypeFlags::Float32: 2691 assert(!shift && "cannot shift float types!"); 2692 return (2 << IsQuad) - 1; 2693 case NeonTypeFlags::Float64: 2694 assert(!shift && "cannot shift float types!"); 2695 return (1 << IsQuad) - 1; 2696 case NeonTypeFlags::BFloat16: 2697 assert(!shift && "cannot shift float types!"); 2698 return (4 << IsQuad) - 1; 2699 } 2700 llvm_unreachable("Invalid NeonTypeFlag!"); 2701 } 2702 2703 /// getNeonEltType - Return the QualType corresponding to the elements of 2704 /// the vector type specified by the NeonTypeFlags. This is used to check 2705 /// the pointer arguments for Neon load/store intrinsics. 2706 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2707 bool IsPolyUnsigned, bool IsInt64Long) { 2708 switch (Flags.getEltType()) { 2709 case NeonTypeFlags::Int8: 2710 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2711 case NeonTypeFlags::Int16: 2712 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2713 case NeonTypeFlags::Int32: 2714 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2715 case NeonTypeFlags::Int64: 2716 if (IsInt64Long) 2717 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2718 else 2719 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2720 : Context.LongLongTy; 2721 case NeonTypeFlags::Poly8: 2722 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2723 case NeonTypeFlags::Poly16: 2724 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2725 case NeonTypeFlags::Poly64: 2726 if (IsInt64Long) 2727 return Context.UnsignedLongTy; 2728 else 2729 return Context.UnsignedLongLongTy; 2730 case NeonTypeFlags::Poly128: 2731 break; 2732 case NeonTypeFlags::Float16: 2733 return Context.HalfTy; 2734 case NeonTypeFlags::Float32: 2735 return Context.FloatTy; 2736 case NeonTypeFlags::Float64: 2737 return Context.DoubleTy; 2738 case NeonTypeFlags::BFloat16: 2739 return Context.BFloat16Ty; 2740 } 2741 llvm_unreachable("Invalid NeonTypeFlag!"); 2742 } 2743 2744 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2745 // Range check SVE intrinsics that take immediate values. 2746 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2747 2748 switch (BuiltinID) { 2749 default: 2750 return false; 2751 #define GET_SVE_IMMEDIATE_CHECK 2752 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2753 #undef GET_SVE_IMMEDIATE_CHECK 2754 } 2755 2756 // Perform all the immediate checks for this builtin call. 2757 bool HasError = false; 2758 for (auto &I : ImmChecks) { 2759 int ArgNum, CheckTy, ElementSizeInBits; 2760 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2761 2762 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2763 2764 // Function that checks whether the operand (ArgNum) is an immediate 2765 // that is one of the predefined values. 2766 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2767 int ErrDiag) -> bool { 2768 // We can't check the value of a dependent argument. 2769 Expr *Arg = TheCall->getArg(ArgNum); 2770 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2771 return false; 2772 2773 // Check constant-ness first. 2774 llvm::APSInt Imm; 2775 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2776 return true; 2777 2778 if (!CheckImm(Imm.getSExtValue())) 2779 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2780 return false; 2781 }; 2782 2783 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2784 case SVETypeFlags::ImmCheck0_31: 2785 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2786 HasError = true; 2787 break; 2788 case SVETypeFlags::ImmCheck0_13: 2789 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2790 HasError = true; 2791 break; 2792 case SVETypeFlags::ImmCheck1_16: 2793 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2794 HasError = true; 2795 break; 2796 case SVETypeFlags::ImmCheck0_7: 2797 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2798 HasError = true; 2799 break; 2800 case SVETypeFlags::ImmCheckExtract: 2801 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2802 (2048 / ElementSizeInBits) - 1)) 2803 HasError = true; 2804 break; 2805 case SVETypeFlags::ImmCheckShiftRight: 2806 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2807 HasError = true; 2808 break; 2809 case SVETypeFlags::ImmCheckShiftRightNarrow: 2810 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2811 ElementSizeInBits / 2)) 2812 HasError = true; 2813 break; 2814 case SVETypeFlags::ImmCheckShiftLeft: 2815 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2816 ElementSizeInBits - 1)) 2817 HasError = true; 2818 break; 2819 case SVETypeFlags::ImmCheckLaneIndex: 2820 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2821 (128 / (1 * ElementSizeInBits)) - 1)) 2822 HasError = true; 2823 break; 2824 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2825 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2826 (128 / (2 * ElementSizeInBits)) - 1)) 2827 HasError = true; 2828 break; 2829 case SVETypeFlags::ImmCheckLaneIndexDot: 2830 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2831 (128 / (4 * ElementSizeInBits)) - 1)) 2832 HasError = true; 2833 break; 2834 case SVETypeFlags::ImmCheckComplexRot90_270: 2835 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2836 diag::err_rotation_argument_to_cadd)) 2837 HasError = true; 2838 break; 2839 case SVETypeFlags::ImmCheckComplexRotAll90: 2840 if (CheckImmediateInSet( 2841 [](int64_t V) { 2842 return V == 0 || V == 90 || V == 180 || V == 270; 2843 }, 2844 diag::err_rotation_argument_to_cmla)) 2845 HasError = true; 2846 break; 2847 case SVETypeFlags::ImmCheck0_1: 2848 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2849 HasError = true; 2850 break; 2851 case SVETypeFlags::ImmCheck0_2: 2852 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2853 HasError = true; 2854 break; 2855 case SVETypeFlags::ImmCheck0_3: 2856 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2857 HasError = true; 2858 break; 2859 } 2860 } 2861 2862 return HasError; 2863 } 2864 2865 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2866 unsigned BuiltinID, CallExpr *TheCall) { 2867 llvm::APSInt Result; 2868 uint64_t mask = 0; 2869 unsigned TV = 0; 2870 int PtrArgNum = -1; 2871 bool HasConstPtr = false; 2872 switch (BuiltinID) { 2873 #define GET_NEON_OVERLOAD_CHECK 2874 #include "clang/Basic/arm_neon.inc" 2875 #include "clang/Basic/arm_fp16.inc" 2876 #undef GET_NEON_OVERLOAD_CHECK 2877 } 2878 2879 // For NEON intrinsics which are overloaded on vector element type, validate 2880 // the immediate which specifies which variant to emit. 2881 unsigned ImmArg = TheCall->getNumArgs()-1; 2882 if (mask) { 2883 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2884 return true; 2885 2886 TV = Result.getLimitedValue(64); 2887 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2888 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2889 << TheCall->getArg(ImmArg)->getSourceRange(); 2890 } 2891 2892 if (PtrArgNum >= 0) { 2893 // Check that pointer arguments have the specified type. 2894 Expr *Arg = TheCall->getArg(PtrArgNum); 2895 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2896 Arg = ICE->getSubExpr(); 2897 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2898 QualType RHSTy = RHS.get()->getType(); 2899 2900 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2901 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2902 Arch == llvm::Triple::aarch64_32 || 2903 Arch == llvm::Triple::aarch64_be; 2904 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2905 QualType EltTy = 2906 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2907 if (HasConstPtr) 2908 EltTy = EltTy.withConst(); 2909 QualType LHSTy = Context.getPointerType(EltTy); 2910 AssignConvertType ConvTy; 2911 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2912 if (RHS.isInvalid()) 2913 return true; 2914 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2915 RHS.get(), AA_Assigning)) 2916 return true; 2917 } 2918 2919 // For NEON intrinsics which take an immediate value as part of the 2920 // instruction, range check them here. 2921 unsigned i = 0, l = 0, u = 0; 2922 switch (BuiltinID) { 2923 default: 2924 return false; 2925 #define GET_NEON_IMMEDIATE_CHECK 2926 #include "clang/Basic/arm_neon.inc" 2927 #include "clang/Basic/arm_fp16.inc" 2928 #undef GET_NEON_IMMEDIATE_CHECK 2929 } 2930 2931 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2932 } 2933 2934 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2935 switch (BuiltinID) { 2936 default: 2937 return false; 2938 #include "clang/Basic/arm_mve_builtin_sema.inc" 2939 } 2940 } 2941 2942 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2943 CallExpr *TheCall) { 2944 bool Err = false; 2945 switch (BuiltinID) { 2946 default: 2947 return false; 2948 #include "clang/Basic/arm_cde_builtin_sema.inc" 2949 } 2950 2951 if (Err) 2952 return true; 2953 2954 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2955 } 2956 2957 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2958 const Expr *CoprocArg, bool WantCDE) { 2959 if (isConstantEvaluated()) 2960 return false; 2961 2962 // We can't check the value of a dependent argument. 2963 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2964 return false; 2965 2966 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2967 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2968 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2969 2970 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2971 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2972 2973 if (IsCDECoproc != WantCDE) 2974 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2975 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2976 2977 return false; 2978 } 2979 2980 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2981 unsigned MaxWidth) { 2982 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2983 BuiltinID == ARM::BI__builtin_arm_ldaex || 2984 BuiltinID == ARM::BI__builtin_arm_strex || 2985 BuiltinID == ARM::BI__builtin_arm_stlex || 2986 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2987 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2988 BuiltinID == AArch64::BI__builtin_arm_strex || 2989 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2990 "unexpected ARM builtin"); 2991 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2992 BuiltinID == ARM::BI__builtin_arm_ldaex || 2993 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2994 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2995 2996 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2997 2998 // Ensure that we have the proper number of arguments. 2999 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 3000 return true; 3001 3002 // Inspect the pointer argument of the atomic builtin. This should always be 3003 // a pointer type, whose element is an integral scalar or pointer type. 3004 // Because it is a pointer type, we don't have to worry about any implicit 3005 // casts here. 3006 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 3007 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 3008 if (PointerArgRes.isInvalid()) 3009 return true; 3010 PointerArg = PointerArgRes.get(); 3011 3012 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3013 if (!pointerType) { 3014 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 3015 << PointerArg->getType() << PointerArg->getSourceRange(); 3016 return true; 3017 } 3018 3019 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 3020 // task is to insert the appropriate casts into the AST. First work out just 3021 // what the appropriate type is. 3022 QualType ValType = pointerType->getPointeeType(); 3023 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 3024 if (IsLdrex) 3025 AddrType.addConst(); 3026 3027 // Issue a warning if the cast is dodgy. 3028 CastKind CastNeeded = CK_NoOp; 3029 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 3030 CastNeeded = CK_BitCast; 3031 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 3032 << PointerArg->getType() << Context.getPointerType(AddrType) 3033 << AA_Passing << PointerArg->getSourceRange(); 3034 } 3035 3036 // Finally, do the cast and replace the argument with the corrected version. 3037 AddrType = Context.getPointerType(AddrType); 3038 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 3039 if (PointerArgRes.isInvalid()) 3040 return true; 3041 PointerArg = PointerArgRes.get(); 3042 3043 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 3044 3045 // In general, we allow ints, floats and pointers to be loaded and stored. 3046 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3047 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 3048 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 3049 << PointerArg->getType() << PointerArg->getSourceRange(); 3050 return true; 3051 } 3052 3053 // But ARM doesn't have instructions to deal with 128-bit versions. 3054 if (Context.getTypeSize(ValType) > MaxWidth) { 3055 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 3056 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 3057 << PointerArg->getType() << PointerArg->getSourceRange(); 3058 return true; 3059 } 3060 3061 switch (ValType.getObjCLifetime()) { 3062 case Qualifiers::OCL_None: 3063 case Qualifiers::OCL_ExplicitNone: 3064 // okay 3065 break; 3066 3067 case Qualifiers::OCL_Weak: 3068 case Qualifiers::OCL_Strong: 3069 case Qualifiers::OCL_Autoreleasing: 3070 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 3071 << ValType << PointerArg->getSourceRange(); 3072 return true; 3073 } 3074 3075 if (IsLdrex) { 3076 TheCall->setType(ValType); 3077 return false; 3078 } 3079 3080 // Initialize the argument to be stored. 3081 ExprResult ValArg = TheCall->getArg(0); 3082 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3083 Context, ValType, /*consume*/ false); 3084 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3085 if (ValArg.isInvalid()) 3086 return true; 3087 TheCall->setArg(0, ValArg.get()); 3088 3089 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 3090 // but the custom checker bypasses all default analysis. 3091 TheCall->setType(Context.IntTy); 3092 return false; 3093 } 3094 3095 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3096 CallExpr *TheCall) { 3097 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 3098 BuiltinID == ARM::BI__builtin_arm_ldaex || 3099 BuiltinID == ARM::BI__builtin_arm_strex || 3100 BuiltinID == ARM::BI__builtin_arm_stlex) { 3101 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 3102 } 3103 3104 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 3105 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3106 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 3107 } 3108 3109 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 3110 BuiltinID == ARM::BI__builtin_arm_wsr64) 3111 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 3112 3113 if (BuiltinID == ARM::BI__builtin_arm_rsr || 3114 BuiltinID == ARM::BI__builtin_arm_rsrp || 3115 BuiltinID == ARM::BI__builtin_arm_wsr || 3116 BuiltinID == ARM::BI__builtin_arm_wsrp) 3117 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 3118 3119 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 3120 return true; 3121 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 3122 return true; 3123 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 3124 return true; 3125 3126 // For intrinsics which take an immediate value as part of the instruction, 3127 // range check them here. 3128 // FIXME: VFP Intrinsics should error if VFP not present. 3129 switch (BuiltinID) { 3130 default: return false; 3131 case ARM::BI__builtin_arm_ssat: 3132 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 3133 case ARM::BI__builtin_arm_usat: 3134 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 3135 case ARM::BI__builtin_arm_ssat16: 3136 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3137 case ARM::BI__builtin_arm_usat16: 3138 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3139 case ARM::BI__builtin_arm_vcvtr_f: 3140 case ARM::BI__builtin_arm_vcvtr_d: 3141 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3142 case ARM::BI__builtin_arm_dmb: 3143 case ARM::BI__builtin_arm_dsb: 3144 case ARM::BI__builtin_arm_isb: 3145 case ARM::BI__builtin_arm_dbg: 3146 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 3147 case ARM::BI__builtin_arm_cdp: 3148 case ARM::BI__builtin_arm_cdp2: 3149 case ARM::BI__builtin_arm_mcr: 3150 case ARM::BI__builtin_arm_mcr2: 3151 case ARM::BI__builtin_arm_mrc: 3152 case ARM::BI__builtin_arm_mrc2: 3153 case ARM::BI__builtin_arm_mcrr: 3154 case ARM::BI__builtin_arm_mcrr2: 3155 case ARM::BI__builtin_arm_mrrc: 3156 case ARM::BI__builtin_arm_mrrc2: 3157 case ARM::BI__builtin_arm_ldc: 3158 case ARM::BI__builtin_arm_ldcl: 3159 case ARM::BI__builtin_arm_ldc2: 3160 case ARM::BI__builtin_arm_ldc2l: 3161 case ARM::BI__builtin_arm_stc: 3162 case ARM::BI__builtin_arm_stcl: 3163 case ARM::BI__builtin_arm_stc2: 3164 case ARM::BI__builtin_arm_stc2l: 3165 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 3166 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 3167 /*WantCDE*/ false); 3168 } 3169 } 3170 3171 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 3172 unsigned BuiltinID, 3173 CallExpr *TheCall) { 3174 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 3175 BuiltinID == AArch64::BI__builtin_arm_ldaex || 3176 BuiltinID == AArch64::BI__builtin_arm_strex || 3177 BuiltinID == AArch64::BI__builtin_arm_stlex) { 3178 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 3179 } 3180 3181 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 3182 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3183 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 3184 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 3185 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 3186 } 3187 3188 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 3189 BuiltinID == AArch64::BI__builtin_arm_wsr64) 3190 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 3191 3192 // Memory Tagging Extensions (MTE) Intrinsics 3193 if (BuiltinID == AArch64::BI__builtin_arm_irg || 3194 BuiltinID == AArch64::BI__builtin_arm_addg || 3195 BuiltinID == AArch64::BI__builtin_arm_gmi || 3196 BuiltinID == AArch64::BI__builtin_arm_ldg || 3197 BuiltinID == AArch64::BI__builtin_arm_stg || 3198 BuiltinID == AArch64::BI__builtin_arm_subp) { 3199 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 3200 } 3201 3202 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 3203 BuiltinID == AArch64::BI__builtin_arm_rsrp || 3204 BuiltinID == AArch64::BI__builtin_arm_wsr || 3205 BuiltinID == AArch64::BI__builtin_arm_wsrp) 3206 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 3207 3208 // Only check the valid encoding range. Any constant in this range would be 3209 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 3210 // an exception for incorrect registers. This matches MSVC behavior. 3211 if (BuiltinID == AArch64::BI_ReadStatusReg || 3212 BuiltinID == AArch64::BI_WriteStatusReg) 3213 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 3214 3215 if (BuiltinID == AArch64::BI__getReg) 3216 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3217 3218 if (BuiltinID == AArch64::BI__break) 3219 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xffff); 3220 3221 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 3222 return true; 3223 3224 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 3225 return true; 3226 3227 // For intrinsics which take an immediate value as part of the instruction, 3228 // range check them here. 3229 unsigned i = 0, l = 0, u = 0; 3230 switch (BuiltinID) { 3231 default: return false; 3232 case AArch64::BI__builtin_arm_dmb: 3233 case AArch64::BI__builtin_arm_dsb: 3234 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 3235 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 3236 } 3237 3238 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 3239 } 3240 3241 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 3242 if (Arg->getType()->getAsPlaceholderType()) 3243 return false; 3244 3245 // The first argument needs to be a record field access. 3246 // If it is an array element access, we delay decision 3247 // to BPF backend to check whether the access is a 3248 // field access or not. 3249 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 3250 isa<MemberExpr>(Arg->IgnoreParens()) || 3251 isa<ArraySubscriptExpr>(Arg->IgnoreParens())); 3252 } 3253 3254 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 3255 QualType VectorTy, QualType EltTy) { 3256 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 3257 if (!Context.hasSameType(VectorEltTy, EltTy)) { 3258 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 3259 << Call->getSourceRange() << VectorEltTy << EltTy; 3260 return false; 3261 } 3262 return true; 3263 } 3264 3265 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 3266 QualType ArgType = Arg->getType(); 3267 if (ArgType->getAsPlaceholderType()) 3268 return false; 3269 3270 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 3271 // format: 3272 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 3273 // 2. <type> var; 3274 // __builtin_preserve_type_info(var, flag); 3275 if (!isa<DeclRefExpr>(Arg->IgnoreParens()) && 3276 !isa<UnaryOperator>(Arg->IgnoreParens())) 3277 return false; 3278 3279 // Typedef type. 3280 if (ArgType->getAs<TypedefType>()) 3281 return true; 3282 3283 // Record type or Enum type. 3284 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 3285 if (const auto *RT = Ty->getAs<RecordType>()) { 3286 if (!RT->getDecl()->getDeclName().isEmpty()) 3287 return true; 3288 } else if (const auto *ET = Ty->getAs<EnumType>()) { 3289 if (!ET->getDecl()->getDeclName().isEmpty()) 3290 return true; 3291 } 3292 3293 return false; 3294 } 3295 3296 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 3297 QualType ArgType = Arg->getType(); 3298 if (ArgType->getAsPlaceholderType()) 3299 return false; 3300 3301 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 3302 // format: 3303 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 3304 // flag); 3305 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 3306 if (!UO) 3307 return false; 3308 3309 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 3310 if (!CE) 3311 return false; 3312 if (CE->getCastKind() != CK_IntegralToPointer && 3313 CE->getCastKind() != CK_NullToPointer) 3314 return false; 3315 3316 // The integer must be from an EnumConstantDecl. 3317 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 3318 if (!DR) 3319 return false; 3320 3321 const EnumConstantDecl *Enumerator = 3322 dyn_cast<EnumConstantDecl>(DR->getDecl()); 3323 if (!Enumerator) 3324 return false; 3325 3326 // The type must be EnumType. 3327 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 3328 const auto *ET = Ty->getAs<EnumType>(); 3329 if (!ET) 3330 return false; 3331 3332 // The enum value must be supported. 3333 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator); 3334 } 3335 3336 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 3337 CallExpr *TheCall) { 3338 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 3339 BuiltinID == BPF::BI__builtin_btf_type_id || 3340 BuiltinID == BPF::BI__builtin_preserve_type_info || 3341 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 3342 "unexpected BPF builtin"); 3343 3344 if (checkArgCount(*this, TheCall, 2)) 3345 return true; 3346 3347 // The second argument needs to be a constant int 3348 Expr *Arg = TheCall->getArg(1); 3349 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 3350 diag::kind kind; 3351 if (!Value) { 3352 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 3353 kind = diag::err_preserve_field_info_not_const; 3354 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 3355 kind = diag::err_btf_type_id_not_const; 3356 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 3357 kind = diag::err_preserve_type_info_not_const; 3358 else 3359 kind = diag::err_preserve_enum_value_not_const; 3360 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 3361 return true; 3362 } 3363 3364 // The first argument 3365 Arg = TheCall->getArg(0); 3366 bool InvalidArg = false; 3367 bool ReturnUnsignedInt = true; 3368 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 3369 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 3370 InvalidArg = true; 3371 kind = diag::err_preserve_field_info_not_field; 3372 } 3373 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 3374 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 3375 InvalidArg = true; 3376 kind = diag::err_preserve_type_info_invalid; 3377 } 3378 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 3379 if (!isValidBPFPreserveEnumValueArg(Arg)) { 3380 InvalidArg = true; 3381 kind = diag::err_preserve_enum_value_invalid; 3382 } 3383 ReturnUnsignedInt = false; 3384 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 3385 ReturnUnsignedInt = false; 3386 } 3387 3388 if (InvalidArg) { 3389 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 3390 return true; 3391 } 3392 3393 if (ReturnUnsignedInt) 3394 TheCall->setType(Context.UnsignedIntTy); 3395 else 3396 TheCall->setType(Context.UnsignedLongTy); 3397 return false; 3398 } 3399 3400 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3401 struct ArgInfo { 3402 uint8_t OpNum; 3403 bool IsSigned; 3404 uint8_t BitWidth; 3405 uint8_t Align; 3406 }; 3407 struct BuiltinInfo { 3408 unsigned BuiltinID; 3409 ArgInfo Infos[2]; 3410 }; 3411 3412 static BuiltinInfo Infos[] = { 3413 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 3414 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 3415 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 3416 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 3417 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 3418 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 3419 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 3420 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 3421 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 3422 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 3423 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 3424 3425 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 3426 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 3427 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 3428 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 3429 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 3430 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 3431 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 3432 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 3433 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 3434 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 3435 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 3436 3437 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 3438 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 3439 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 3440 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 3441 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 3442 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 3443 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 3444 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 3445 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 3446 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 3447 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 3448 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 3449 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 3450 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 3451 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 3452 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 3453 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 3454 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 3455 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 3456 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 3457 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 3458 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 3459 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 3460 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 3461 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 3462 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 3463 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 3464 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 3465 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 3466 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 3467 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 3468 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 3469 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 3470 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 3471 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 3472 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 3473 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 3474 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 3475 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 3476 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 3477 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 3478 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 3479 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 3480 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 3481 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 3482 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 3483 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 3484 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 3485 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 3486 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 3487 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 3488 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 3489 {{ 1, false, 6, 0 }} }, 3490 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 3491 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 3492 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 3493 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 3494 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 3495 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 3496 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 3497 {{ 1, false, 5, 0 }} }, 3498 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 3499 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 3500 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 3501 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 3502 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 3503 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 3504 { 2, false, 5, 0 }} }, 3505 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 3506 { 2, false, 6, 0 }} }, 3507 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 3508 { 3, false, 5, 0 }} }, 3509 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 3510 { 3, false, 6, 0 }} }, 3511 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 3512 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 3513 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 3514 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 3515 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 3516 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 3517 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 3518 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 3519 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 3520 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 3521 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 3522 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 3523 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 3524 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 3525 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 3526 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 3527 {{ 2, false, 4, 0 }, 3528 { 3, false, 5, 0 }} }, 3529 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 3530 {{ 2, false, 4, 0 }, 3531 { 3, false, 5, 0 }} }, 3532 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 3533 {{ 2, false, 4, 0 }, 3534 { 3, false, 5, 0 }} }, 3535 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 3536 {{ 2, false, 4, 0 }, 3537 { 3, false, 5, 0 }} }, 3538 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 3539 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 3540 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 3541 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 3542 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 3543 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 3544 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 3545 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 3546 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 3547 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 3548 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 3549 { 2, false, 5, 0 }} }, 3550 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 3551 { 2, false, 6, 0 }} }, 3552 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 3553 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 3554 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 3555 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 3556 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 3557 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 3558 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 3559 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 3560 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 3561 {{ 1, false, 4, 0 }} }, 3562 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 3563 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 3564 {{ 1, false, 4, 0 }} }, 3565 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 3566 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 3567 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 3568 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 3569 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 3570 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 3571 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 3572 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 3573 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 3574 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 3575 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 3576 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 3577 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 3578 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 3579 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 3580 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 3581 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 3582 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 3583 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 3584 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 3585 {{ 3, false, 1, 0 }} }, 3586 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 3587 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 3588 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 3589 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 3590 {{ 3, false, 1, 0 }} }, 3591 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 3592 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 3593 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 3594 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 3595 {{ 3, false, 1, 0 }} }, 3596 }; 3597 3598 // Use a dynamically initialized static to sort the table exactly once on 3599 // first run. 3600 static const bool SortOnce = 3601 (llvm::sort(Infos, 3602 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 3603 return LHS.BuiltinID < RHS.BuiltinID; 3604 }), 3605 true); 3606 (void)SortOnce; 3607 3608 const BuiltinInfo *F = llvm::partition_point( 3609 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 3610 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 3611 return false; 3612 3613 bool Error = false; 3614 3615 for (const ArgInfo &A : F->Infos) { 3616 // Ignore empty ArgInfo elements. 3617 if (A.BitWidth == 0) 3618 continue; 3619 3620 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 3621 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 3622 if (!A.Align) { 3623 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3624 } else { 3625 unsigned M = 1 << A.Align; 3626 Min *= M; 3627 Max *= M; 3628 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3629 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 3630 } 3631 } 3632 return Error; 3633 } 3634 3635 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 3636 CallExpr *TheCall) { 3637 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3638 } 3639 3640 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3641 unsigned BuiltinID, CallExpr *TheCall) { 3642 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3643 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3644 } 3645 3646 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3647 CallExpr *TheCall) { 3648 3649 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3650 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3651 if (!TI.hasFeature("dsp")) 3652 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3653 } 3654 3655 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3656 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3657 if (!TI.hasFeature("dspr2")) 3658 return Diag(TheCall->getBeginLoc(), 3659 diag::err_mips_builtin_requires_dspr2); 3660 } 3661 3662 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3663 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3664 if (!TI.hasFeature("msa")) 3665 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3666 } 3667 3668 return false; 3669 } 3670 3671 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3672 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3673 // ordering for DSP is unspecified. MSA is ordered by the data format used 3674 // by the underlying instruction i.e., df/m, df/n and then by size. 3675 // 3676 // FIXME: The size tests here should instead be tablegen'd along with the 3677 // definitions from include/clang/Basic/BuiltinsMips.def. 3678 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3679 // be too. 3680 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3681 unsigned i = 0, l = 0, u = 0, m = 0; 3682 switch (BuiltinID) { 3683 default: return false; 3684 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3685 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3686 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3687 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3688 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3689 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3690 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3691 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3692 // df/m field. 3693 // These intrinsics take an unsigned 3 bit immediate. 3694 case Mips::BI__builtin_msa_bclri_b: 3695 case Mips::BI__builtin_msa_bnegi_b: 3696 case Mips::BI__builtin_msa_bseti_b: 3697 case Mips::BI__builtin_msa_sat_s_b: 3698 case Mips::BI__builtin_msa_sat_u_b: 3699 case Mips::BI__builtin_msa_slli_b: 3700 case Mips::BI__builtin_msa_srai_b: 3701 case Mips::BI__builtin_msa_srari_b: 3702 case Mips::BI__builtin_msa_srli_b: 3703 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3704 case Mips::BI__builtin_msa_binsli_b: 3705 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3706 // These intrinsics take an unsigned 4 bit immediate. 3707 case Mips::BI__builtin_msa_bclri_h: 3708 case Mips::BI__builtin_msa_bnegi_h: 3709 case Mips::BI__builtin_msa_bseti_h: 3710 case Mips::BI__builtin_msa_sat_s_h: 3711 case Mips::BI__builtin_msa_sat_u_h: 3712 case Mips::BI__builtin_msa_slli_h: 3713 case Mips::BI__builtin_msa_srai_h: 3714 case Mips::BI__builtin_msa_srari_h: 3715 case Mips::BI__builtin_msa_srli_h: 3716 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3717 case Mips::BI__builtin_msa_binsli_h: 3718 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3719 // These intrinsics take an unsigned 5 bit immediate. 3720 // The first block of intrinsics actually have an unsigned 5 bit field, 3721 // not a df/n field. 3722 case Mips::BI__builtin_msa_cfcmsa: 3723 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3724 case Mips::BI__builtin_msa_clei_u_b: 3725 case Mips::BI__builtin_msa_clei_u_h: 3726 case Mips::BI__builtin_msa_clei_u_w: 3727 case Mips::BI__builtin_msa_clei_u_d: 3728 case Mips::BI__builtin_msa_clti_u_b: 3729 case Mips::BI__builtin_msa_clti_u_h: 3730 case Mips::BI__builtin_msa_clti_u_w: 3731 case Mips::BI__builtin_msa_clti_u_d: 3732 case Mips::BI__builtin_msa_maxi_u_b: 3733 case Mips::BI__builtin_msa_maxi_u_h: 3734 case Mips::BI__builtin_msa_maxi_u_w: 3735 case Mips::BI__builtin_msa_maxi_u_d: 3736 case Mips::BI__builtin_msa_mini_u_b: 3737 case Mips::BI__builtin_msa_mini_u_h: 3738 case Mips::BI__builtin_msa_mini_u_w: 3739 case Mips::BI__builtin_msa_mini_u_d: 3740 case Mips::BI__builtin_msa_addvi_b: 3741 case Mips::BI__builtin_msa_addvi_h: 3742 case Mips::BI__builtin_msa_addvi_w: 3743 case Mips::BI__builtin_msa_addvi_d: 3744 case Mips::BI__builtin_msa_bclri_w: 3745 case Mips::BI__builtin_msa_bnegi_w: 3746 case Mips::BI__builtin_msa_bseti_w: 3747 case Mips::BI__builtin_msa_sat_s_w: 3748 case Mips::BI__builtin_msa_sat_u_w: 3749 case Mips::BI__builtin_msa_slli_w: 3750 case Mips::BI__builtin_msa_srai_w: 3751 case Mips::BI__builtin_msa_srari_w: 3752 case Mips::BI__builtin_msa_srli_w: 3753 case Mips::BI__builtin_msa_srlri_w: 3754 case Mips::BI__builtin_msa_subvi_b: 3755 case Mips::BI__builtin_msa_subvi_h: 3756 case Mips::BI__builtin_msa_subvi_w: 3757 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3758 case Mips::BI__builtin_msa_binsli_w: 3759 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3760 // These intrinsics take an unsigned 6 bit immediate. 3761 case Mips::BI__builtin_msa_bclri_d: 3762 case Mips::BI__builtin_msa_bnegi_d: 3763 case Mips::BI__builtin_msa_bseti_d: 3764 case Mips::BI__builtin_msa_sat_s_d: 3765 case Mips::BI__builtin_msa_sat_u_d: 3766 case Mips::BI__builtin_msa_slli_d: 3767 case Mips::BI__builtin_msa_srai_d: 3768 case Mips::BI__builtin_msa_srari_d: 3769 case Mips::BI__builtin_msa_srli_d: 3770 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3771 case Mips::BI__builtin_msa_binsli_d: 3772 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3773 // These intrinsics take a signed 5 bit immediate. 3774 case Mips::BI__builtin_msa_ceqi_b: 3775 case Mips::BI__builtin_msa_ceqi_h: 3776 case Mips::BI__builtin_msa_ceqi_w: 3777 case Mips::BI__builtin_msa_ceqi_d: 3778 case Mips::BI__builtin_msa_clti_s_b: 3779 case Mips::BI__builtin_msa_clti_s_h: 3780 case Mips::BI__builtin_msa_clti_s_w: 3781 case Mips::BI__builtin_msa_clti_s_d: 3782 case Mips::BI__builtin_msa_clei_s_b: 3783 case Mips::BI__builtin_msa_clei_s_h: 3784 case Mips::BI__builtin_msa_clei_s_w: 3785 case Mips::BI__builtin_msa_clei_s_d: 3786 case Mips::BI__builtin_msa_maxi_s_b: 3787 case Mips::BI__builtin_msa_maxi_s_h: 3788 case Mips::BI__builtin_msa_maxi_s_w: 3789 case Mips::BI__builtin_msa_maxi_s_d: 3790 case Mips::BI__builtin_msa_mini_s_b: 3791 case Mips::BI__builtin_msa_mini_s_h: 3792 case Mips::BI__builtin_msa_mini_s_w: 3793 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3794 // These intrinsics take an unsigned 8 bit immediate. 3795 case Mips::BI__builtin_msa_andi_b: 3796 case Mips::BI__builtin_msa_nori_b: 3797 case Mips::BI__builtin_msa_ori_b: 3798 case Mips::BI__builtin_msa_shf_b: 3799 case Mips::BI__builtin_msa_shf_h: 3800 case Mips::BI__builtin_msa_shf_w: 3801 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3802 case Mips::BI__builtin_msa_bseli_b: 3803 case Mips::BI__builtin_msa_bmnzi_b: 3804 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3805 // df/n format 3806 // These intrinsics take an unsigned 4 bit immediate. 3807 case Mips::BI__builtin_msa_copy_s_b: 3808 case Mips::BI__builtin_msa_copy_u_b: 3809 case Mips::BI__builtin_msa_insve_b: 3810 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3811 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3812 // These intrinsics take an unsigned 3 bit immediate. 3813 case Mips::BI__builtin_msa_copy_s_h: 3814 case Mips::BI__builtin_msa_copy_u_h: 3815 case Mips::BI__builtin_msa_insve_h: 3816 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3817 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3818 // These intrinsics take an unsigned 2 bit immediate. 3819 case Mips::BI__builtin_msa_copy_s_w: 3820 case Mips::BI__builtin_msa_copy_u_w: 3821 case Mips::BI__builtin_msa_insve_w: 3822 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3823 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3824 // These intrinsics take an unsigned 1 bit immediate. 3825 case Mips::BI__builtin_msa_copy_s_d: 3826 case Mips::BI__builtin_msa_copy_u_d: 3827 case Mips::BI__builtin_msa_insve_d: 3828 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3829 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3830 // Memory offsets and immediate loads. 3831 // These intrinsics take a signed 10 bit immediate. 3832 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3833 case Mips::BI__builtin_msa_ldi_h: 3834 case Mips::BI__builtin_msa_ldi_w: 3835 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3836 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3837 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3838 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3839 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3840 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3841 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3842 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3843 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3844 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3845 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3846 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3847 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3848 } 3849 3850 if (!m) 3851 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3852 3853 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3854 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3855 } 3856 3857 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3858 /// advancing the pointer over the consumed characters. The decoded type is 3859 /// returned. If the decoded type represents a constant integer with a 3860 /// constraint on its value then Mask is set to that value. The type descriptors 3861 /// used in Str are specific to PPC MMA builtins and are documented in the file 3862 /// defining the PPC builtins. 3863 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3864 unsigned &Mask) { 3865 bool RequireICE = false; 3866 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3867 switch (*Str++) { 3868 case 'V': 3869 return Context.getVectorType(Context.UnsignedCharTy, 16, 3870 VectorType::VectorKind::AltiVecVector); 3871 case 'i': { 3872 char *End; 3873 unsigned size = strtoul(Str, &End, 10); 3874 assert(End != Str && "Missing constant parameter constraint"); 3875 Str = End; 3876 Mask = size; 3877 return Context.IntTy; 3878 } 3879 case 'W': { 3880 char *End; 3881 unsigned size = strtoul(Str, &End, 10); 3882 assert(End != Str && "Missing PowerPC MMA type size"); 3883 Str = End; 3884 QualType Type; 3885 switch (size) { 3886 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3887 case size: Type = Context.Id##Ty; break; 3888 #include "clang/Basic/PPCTypes.def" 3889 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3890 } 3891 bool CheckVectorArgs = false; 3892 while (!CheckVectorArgs) { 3893 switch (*Str++) { 3894 case '*': 3895 Type = Context.getPointerType(Type); 3896 break; 3897 case 'C': 3898 Type = Type.withConst(); 3899 break; 3900 default: 3901 CheckVectorArgs = true; 3902 --Str; 3903 break; 3904 } 3905 } 3906 return Type; 3907 } 3908 default: 3909 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3910 } 3911 } 3912 3913 static bool isPPC_64Builtin(unsigned BuiltinID) { 3914 // These builtins only work on PPC 64bit targets. 3915 switch (BuiltinID) { 3916 case PPC::BI__builtin_divde: 3917 case PPC::BI__builtin_divdeu: 3918 case PPC::BI__builtin_bpermd: 3919 case PPC::BI__builtin_pdepd: 3920 case PPC::BI__builtin_pextd: 3921 case PPC::BI__builtin_ppc_ldarx: 3922 case PPC::BI__builtin_ppc_stdcx: 3923 case PPC::BI__builtin_ppc_tdw: 3924 case PPC::BI__builtin_ppc_trapd: 3925 case PPC::BI__builtin_ppc_cmpeqb: 3926 case PPC::BI__builtin_ppc_setb: 3927 case PPC::BI__builtin_ppc_mulhd: 3928 case PPC::BI__builtin_ppc_mulhdu: 3929 case PPC::BI__builtin_ppc_maddhd: 3930 case PPC::BI__builtin_ppc_maddhdu: 3931 case PPC::BI__builtin_ppc_maddld: 3932 case PPC::BI__builtin_ppc_load8r: 3933 case PPC::BI__builtin_ppc_store8r: 3934 case PPC::BI__builtin_ppc_insert_exp: 3935 case PPC::BI__builtin_ppc_extract_sig: 3936 case PPC::BI__builtin_ppc_addex: 3937 case PPC::BI__builtin_darn: 3938 case PPC::BI__builtin_darn_raw: 3939 case PPC::BI__builtin_ppc_compare_and_swaplp: 3940 case PPC::BI__builtin_ppc_fetch_and_addlp: 3941 case PPC::BI__builtin_ppc_fetch_and_andlp: 3942 case PPC::BI__builtin_ppc_fetch_and_orlp: 3943 case PPC::BI__builtin_ppc_fetch_and_swaplp: 3944 return true; 3945 } 3946 return false; 3947 } 3948 3949 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3950 StringRef FeatureToCheck, unsigned DiagID, 3951 StringRef DiagArg = "") { 3952 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3953 return false; 3954 3955 if (DiagArg.empty()) 3956 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3957 else 3958 S.Diag(TheCall->getBeginLoc(), DiagID) 3959 << DiagArg << TheCall->getSourceRange(); 3960 3961 return true; 3962 } 3963 3964 /// Returns true if the argument consists of one contiguous run of 1s with any 3965 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3966 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3967 /// since all 1s are not contiguous. 3968 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3969 llvm::APSInt Result; 3970 // We can't check the value of a dependent argument. 3971 Expr *Arg = TheCall->getArg(ArgNum); 3972 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3973 return false; 3974 3975 // Check constant-ness first. 3976 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3977 return true; 3978 3979 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3980 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3981 return false; 3982 3983 return Diag(TheCall->getBeginLoc(), 3984 diag::err_argument_not_contiguous_bit_field) 3985 << ArgNum << Arg->getSourceRange(); 3986 } 3987 3988 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3989 CallExpr *TheCall) { 3990 unsigned i = 0, l = 0, u = 0; 3991 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3992 llvm::APSInt Result; 3993 3994 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3995 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3996 << TheCall->getSourceRange(); 3997 3998 switch (BuiltinID) { 3999 default: return false; 4000 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 4001 case PPC::BI__builtin_altivec_crypto_vshasigmad: 4002 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 4003 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 4004 case PPC::BI__builtin_altivec_dss: 4005 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 4006 case PPC::BI__builtin_tbegin: 4007 case PPC::BI__builtin_tend: 4008 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) || 4009 SemaFeatureCheck(*this, TheCall, "htm", 4010 diag::err_ppc_builtin_requires_htm); 4011 case PPC::BI__builtin_tsr: 4012 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 4013 SemaFeatureCheck(*this, TheCall, "htm", 4014 diag::err_ppc_builtin_requires_htm); 4015 case PPC::BI__builtin_tabortwc: 4016 case PPC::BI__builtin_tabortdc: 4017 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 4018 SemaFeatureCheck(*this, TheCall, "htm", 4019 diag::err_ppc_builtin_requires_htm); 4020 case PPC::BI__builtin_tabortwci: 4021 case PPC::BI__builtin_tabortdci: 4022 return SemaFeatureCheck(*this, TheCall, "htm", 4023 diag::err_ppc_builtin_requires_htm) || 4024 (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 4025 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31)); 4026 case PPC::BI__builtin_tabort: 4027 case PPC::BI__builtin_tcheck: 4028 case PPC::BI__builtin_treclaim: 4029 case PPC::BI__builtin_trechkpt: 4030 case PPC::BI__builtin_tendall: 4031 case PPC::BI__builtin_tresume: 4032 case PPC::BI__builtin_tsuspend: 4033 case PPC::BI__builtin_get_texasr: 4034 case PPC::BI__builtin_get_texasru: 4035 case PPC::BI__builtin_get_tfhar: 4036 case PPC::BI__builtin_get_tfiar: 4037 case PPC::BI__builtin_set_texasr: 4038 case PPC::BI__builtin_set_texasru: 4039 case PPC::BI__builtin_set_tfhar: 4040 case PPC::BI__builtin_set_tfiar: 4041 case PPC::BI__builtin_ttest: 4042 return SemaFeatureCheck(*this, TheCall, "htm", 4043 diag::err_ppc_builtin_requires_htm); 4044 // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05', 4045 // __builtin_(un)pack_longdouble are available only if long double uses IBM 4046 // extended double representation. 4047 case PPC::BI__builtin_unpack_longdouble: 4048 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1)) 4049 return true; 4050 LLVM_FALLTHROUGH; 4051 case PPC::BI__builtin_pack_longdouble: 4052 if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble()) 4053 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi) 4054 << "ibmlongdouble"; 4055 return false; 4056 case PPC::BI__builtin_altivec_dst: 4057 case PPC::BI__builtin_altivec_dstt: 4058 case PPC::BI__builtin_altivec_dstst: 4059 case PPC::BI__builtin_altivec_dststt: 4060 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 4061 case PPC::BI__builtin_vsx_xxpermdi: 4062 case PPC::BI__builtin_vsx_xxsldwi: 4063 return SemaBuiltinVSX(TheCall); 4064 case PPC::BI__builtin_divwe: 4065 case PPC::BI__builtin_divweu: 4066 case PPC::BI__builtin_divde: 4067 case PPC::BI__builtin_divdeu: 4068 return SemaFeatureCheck(*this, TheCall, "extdiv", 4069 diag::err_ppc_builtin_only_on_arch, "7"); 4070 case PPC::BI__builtin_bpermd: 4071 return SemaFeatureCheck(*this, TheCall, "bpermd", 4072 diag::err_ppc_builtin_only_on_arch, "7"); 4073 case PPC::BI__builtin_unpack_vector_int128: 4074 return SemaFeatureCheck(*this, TheCall, "vsx", 4075 diag::err_ppc_builtin_only_on_arch, "7") || 4076 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 4077 case PPC::BI__builtin_pack_vector_int128: 4078 return SemaFeatureCheck(*this, TheCall, "vsx", 4079 diag::err_ppc_builtin_only_on_arch, "7"); 4080 case PPC::BI__builtin_pdepd: 4081 case PPC::BI__builtin_pextd: 4082 return SemaFeatureCheck(*this, TheCall, "isa-v31-instructions", 4083 diag::err_ppc_builtin_only_on_arch, "10"); 4084 case PPC::BI__builtin_altivec_vgnb: 4085 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 4086 case PPC::BI__builtin_altivec_vec_replace_elt: 4087 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 4088 QualType VecTy = TheCall->getArg(0)->getType(); 4089 QualType EltTy = TheCall->getArg(1)->getType(); 4090 unsigned Width = Context.getIntWidth(EltTy); 4091 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 4092 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 4093 } 4094 case PPC::BI__builtin_vsx_xxeval: 4095 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 4096 case PPC::BI__builtin_altivec_vsldbi: 4097 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 4098 case PPC::BI__builtin_altivec_vsrdbi: 4099 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 4100 case PPC::BI__builtin_vsx_xxpermx: 4101 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 4102 case PPC::BI__builtin_ppc_tw: 4103 case PPC::BI__builtin_ppc_tdw: 4104 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 4105 case PPC::BI__builtin_ppc_cmpeqb: 4106 case PPC::BI__builtin_ppc_setb: 4107 case PPC::BI__builtin_ppc_maddhd: 4108 case PPC::BI__builtin_ppc_maddhdu: 4109 case PPC::BI__builtin_ppc_maddld: 4110 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 4111 diag::err_ppc_builtin_only_on_arch, "9"); 4112 case PPC::BI__builtin_ppc_cmprb: 4113 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 4114 diag::err_ppc_builtin_only_on_arch, "9") || 4115 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 4116 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 4117 // be a constant that represents a contiguous bit field. 4118 case PPC::BI__builtin_ppc_rlwnm: 4119 return SemaValueIsRunOfOnes(TheCall, 2); 4120 case PPC::BI__builtin_ppc_rlwimi: 4121 case PPC::BI__builtin_ppc_rldimi: 4122 return SemaBuiltinConstantArg(TheCall, 2, Result) || 4123 SemaValueIsRunOfOnes(TheCall, 3); 4124 case PPC::BI__builtin_ppc_extract_exp: 4125 case PPC::BI__builtin_ppc_extract_sig: 4126 case PPC::BI__builtin_ppc_insert_exp: 4127 return SemaFeatureCheck(*this, TheCall, "power9-vector", 4128 diag::err_ppc_builtin_only_on_arch, "9"); 4129 case PPC::BI__builtin_ppc_addex: { 4130 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 4131 diag::err_ppc_builtin_only_on_arch, "9") || 4132 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 4133 return true; 4134 // Output warning for reserved values 1 to 3. 4135 int ArgValue = 4136 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 4137 if (ArgValue != 0) 4138 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 4139 << ArgValue; 4140 return false; 4141 } 4142 case PPC::BI__builtin_ppc_mtfsb0: 4143 case PPC::BI__builtin_ppc_mtfsb1: 4144 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 4145 case PPC::BI__builtin_ppc_mtfsf: 4146 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 4147 case PPC::BI__builtin_ppc_mtfsfi: 4148 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 4149 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4150 case PPC::BI__builtin_ppc_alignx: 4151 return SemaBuiltinConstantArgPower2(TheCall, 0); 4152 case PPC::BI__builtin_ppc_rdlam: 4153 return SemaValueIsRunOfOnes(TheCall, 2); 4154 case PPC::BI__builtin_ppc_icbt: 4155 case PPC::BI__builtin_ppc_sthcx: 4156 case PPC::BI__builtin_ppc_stbcx: 4157 case PPC::BI__builtin_ppc_lharx: 4158 case PPC::BI__builtin_ppc_lbarx: 4159 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 4160 diag::err_ppc_builtin_only_on_arch, "8"); 4161 case PPC::BI__builtin_vsx_ldrmb: 4162 case PPC::BI__builtin_vsx_strmb: 4163 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 4164 diag::err_ppc_builtin_only_on_arch, "8") || 4165 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 4166 case PPC::BI__builtin_altivec_vcntmbb: 4167 case PPC::BI__builtin_altivec_vcntmbh: 4168 case PPC::BI__builtin_altivec_vcntmbw: 4169 case PPC::BI__builtin_altivec_vcntmbd: 4170 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 4171 case PPC::BI__builtin_darn: 4172 case PPC::BI__builtin_darn_raw: 4173 case PPC::BI__builtin_darn_32: 4174 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 4175 diag::err_ppc_builtin_only_on_arch, "9"); 4176 case PPC::BI__builtin_vsx_xxgenpcvbm: 4177 case PPC::BI__builtin_vsx_xxgenpcvhm: 4178 case PPC::BI__builtin_vsx_xxgenpcvwm: 4179 case PPC::BI__builtin_vsx_xxgenpcvdm: 4180 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 4181 case PPC::BI__builtin_ppc_compare_exp_uo: 4182 case PPC::BI__builtin_ppc_compare_exp_lt: 4183 case PPC::BI__builtin_ppc_compare_exp_gt: 4184 case PPC::BI__builtin_ppc_compare_exp_eq: 4185 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 4186 diag::err_ppc_builtin_only_on_arch, "9") || 4187 SemaFeatureCheck(*this, TheCall, "vsx", 4188 diag::err_ppc_builtin_requires_vsx); 4189 case PPC::BI__builtin_ppc_test_data_class: { 4190 // Check if the first argument of the __builtin_ppc_test_data_class call is 4191 // valid. The argument must be either a 'float' or a 'double'. 4192 QualType ArgType = TheCall->getArg(0)->getType(); 4193 if (ArgType != QualType(Context.FloatTy) && 4194 ArgType != QualType(Context.DoubleTy)) 4195 return Diag(TheCall->getBeginLoc(), 4196 diag::err_ppc_invalid_test_data_class_type); 4197 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 4198 diag::err_ppc_builtin_only_on_arch, "9") || 4199 SemaFeatureCheck(*this, TheCall, "vsx", 4200 diag::err_ppc_builtin_requires_vsx) || 4201 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 4202 } 4203 case PPC::BI__builtin_ppc_maxfe: 4204 case PPC::BI__builtin_ppc_minfe: 4205 case PPC::BI__builtin_ppc_maxfl: 4206 case PPC::BI__builtin_ppc_minfl: 4207 case PPC::BI__builtin_ppc_maxfs: 4208 case PPC::BI__builtin_ppc_minfs: { 4209 if (Context.getTargetInfo().getTriple().isOSAIX() && 4210 (BuiltinID == PPC::BI__builtin_ppc_maxfe || 4211 BuiltinID == PPC::BI__builtin_ppc_minfe)) 4212 return Diag(TheCall->getBeginLoc(), diag::err_target_unsupported_type) 4213 << "builtin" << true << 128 << QualType(Context.LongDoubleTy) 4214 << false << Context.getTargetInfo().getTriple().str(); 4215 // Argument type should be exact. 4216 QualType ArgType = QualType(Context.LongDoubleTy); 4217 if (BuiltinID == PPC::BI__builtin_ppc_maxfl || 4218 BuiltinID == PPC::BI__builtin_ppc_minfl) 4219 ArgType = QualType(Context.DoubleTy); 4220 else if (BuiltinID == PPC::BI__builtin_ppc_maxfs || 4221 BuiltinID == PPC::BI__builtin_ppc_minfs) 4222 ArgType = QualType(Context.FloatTy); 4223 for (unsigned I = 0, E = TheCall->getNumArgs(); I < E; ++I) 4224 if (TheCall->getArg(I)->getType() != ArgType) 4225 return Diag(TheCall->getBeginLoc(), 4226 diag::err_typecheck_convert_incompatible) 4227 << TheCall->getArg(I)->getType() << ArgType << 1 << 0 << 0; 4228 return false; 4229 } 4230 case PPC::BI__builtin_ppc_load8r: 4231 case PPC::BI__builtin_ppc_store8r: 4232 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions", 4233 diag::err_ppc_builtin_only_on_arch, "7"); 4234 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 4235 case PPC::BI__builtin_##Name: \ 4236 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types); 4237 #include "clang/Basic/BuiltinsPPC.def" 4238 } 4239 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 4240 } 4241 4242 // Check if the given type is a non-pointer PPC MMA type. This function is used 4243 // in Sema to prevent invalid uses of restricted PPC MMA types. 4244 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 4245 if (Type->isPointerType() || Type->isArrayType()) 4246 return false; 4247 4248 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 4249 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 4250 if (false 4251 #include "clang/Basic/PPCTypes.def" 4252 ) { 4253 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 4254 return true; 4255 } 4256 return false; 4257 } 4258 4259 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 4260 CallExpr *TheCall) { 4261 // position of memory order and scope arguments in the builtin 4262 unsigned OrderIndex, ScopeIndex; 4263 switch (BuiltinID) { 4264 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 4265 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 4266 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 4267 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 4268 OrderIndex = 2; 4269 ScopeIndex = 3; 4270 break; 4271 case AMDGPU::BI__builtin_amdgcn_fence: 4272 OrderIndex = 0; 4273 ScopeIndex = 1; 4274 break; 4275 default: 4276 return false; 4277 } 4278 4279 ExprResult Arg = TheCall->getArg(OrderIndex); 4280 auto ArgExpr = Arg.get(); 4281 Expr::EvalResult ArgResult; 4282 4283 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 4284 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 4285 << ArgExpr->getType(); 4286 auto Ord = ArgResult.Val.getInt().getZExtValue(); 4287 4288 // Check validity of memory ordering as per C11 / C++11's memody model. 4289 // Only fence needs check. Atomic dec/inc allow all memory orders. 4290 if (!llvm::isValidAtomicOrderingCABI(Ord)) 4291 return Diag(ArgExpr->getBeginLoc(), 4292 diag::warn_atomic_op_has_invalid_memory_order) 4293 << ArgExpr->getSourceRange(); 4294 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 4295 case llvm::AtomicOrderingCABI::relaxed: 4296 case llvm::AtomicOrderingCABI::consume: 4297 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 4298 return Diag(ArgExpr->getBeginLoc(), 4299 diag::warn_atomic_op_has_invalid_memory_order) 4300 << ArgExpr->getSourceRange(); 4301 break; 4302 case llvm::AtomicOrderingCABI::acquire: 4303 case llvm::AtomicOrderingCABI::release: 4304 case llvm::AtomicOrderingCABI::acq_rel: 4305 case llvm::AtomicOrderingCABI::seq_cst: 4306 break; 4307 } 4308 4309 Arg = TheCall->getArg(ScopeIndex); 4310 ArgExpr = Arg.get(); 4311 Expr::EvalResult ArgResult1; 4312 // Check that sync scope is a constant literal 4313 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 4314 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 4315 << ArgExpr->getType(); 4316 4317 return false; 4318 } 4319 4320 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 4321 llvm::APSInt Result; 4322 4323 // We can't check the value of a dependent argument. 4324 Expr *Arg = TheCall->getArg(ArgNum); 4325 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4326 return false; 4327 4328 // Check constant-ness first. 4329 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4330 return true; 4331 4332 int64_t Val = Result.getSExtValue(); 4333 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 4334 return false; 4335 4336 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 4337 << Arg->getSourceRange(); 4338 } 4339 4340 static bool isRISCV32Builtin(unsigned BuiltinID) { 4341 // These builtins only work on riscv32 targets. 4342 switch (BuiltinID) { 4343 case RISCV::BI__builtin_riscv_zip_32: 4344 case RISCV::BI__builtin_riscv_unzip_32: 4345 case RISCV::BI__builtin_riscv_aes32dsi_32: 4346 case RISCV::BI__builtin_riscv_aes32dsmi_32: 4347 case RISCV::BI__builtin_riscv_aes32esi_32: 4348 case RISCV::BI__builtin_riscv_aes32esmi_32: 4349 case RISCV::BI__builtin_riscv_sha512sig0h_32: 4350 case RISCV::BI__builtin_riscv_sha512sig0l_32: 4351 case RISCV::BI__builtin_riscv_sha512sig1h_32: 4352 case RISCV::BI__builtin_riscv_sha512sig1l_32: 4353 case RISCV::BI__builtin_riscv_sha512sum0r_32: 4354 case RISCV::BI__builtin_riscv_sha512sum1r_32: 4355 return true; 4356 } 4357 4358 return false; 4359 } 4360 4361 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 4362 unsigned BuiltinID, 4363 CallExpr *TheCall) { 4364 // CodeGenFunction can also detect this, but this gives a better error 4365 // message. 4366 bool FeatureMissing = false; 4367 SmallVector<StringRef> ReqFeatures; 4368 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 4369 Features.split(ReqFeatures, ','); 4370 4371 // Check for 32-bit only builtins on a 64-bit target. 4372 const llvm::Triple &TT = TI.getTriple(); 4373 if (TT.getArch() != llvm::Triple::riscv32 && isRISCV32Builtin(BuiltinID)) 4374 return Diag(TheCall->getCallee()->getBeginLoc(), 4375 diag::err_32_bit_builtin_64_bit_tgt); 4376 4377 // Check if each required feature is included 4378 for (StringRef F : ReqFeatures) { 4379 SmallVector<StringRef> ReqOpFeatures; 4380 F.split(ReqOpFeatures, '|'); 4381 bool HasFeature = false; 4382 for (StringRef OF : ReqOpFeatures) { 4383 if (TI.hasFeature(OF)) { 4384 HasFeature = true; 4385 continue; 4386 } 4387 } 4388 4389 if (!HasFeature) { 4390 std::string FeatureStrs; 4391 for (StringRef OF : ReqOpFeatures) { 4392 // If the feature is 64bit, alter the string so it will print better in 4393 // the diagnostic. 4394 if (OF == "64bit") 4395 OF = "RV64"; 4396 4397 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 4398 OF.consume_front("experimental-"); 4399 std::string FeatureStr = OF.str(); 4400 FeatureStr[0] = std::toupper(FeatureStr[0]); 4401 // Combine strings. 4402 FeatureStrs += FeatureStrs == "" ? "" : ", "; 4403 FeatureStrs += "'"; 4404 FeatureStrs += FeatureStr; 4405 FeatureStrs += "'"; 4406 } 4407 // Error message 4408 FeatureMissing = true; 4409 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 4410 << TheCall->getSourceRange() << StringRef(FeatureStrs); 4411 } 4412 } 4413 4414 if (FeatureMissing) 4415 return true; 4416 4417 switch (BuiltinID) { 4418 case RISCVVector::BI__builtin_rvv_vsetvli: 4419 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 4420 CheckRISCVLMUL(TheCall, 2); 4421 case RISCVVector::BI__builtin_rvv_vsetvlimax: 4422 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 4423 CheckRISCVLMUL(TheCall, 1); 4424 case RISCVVector::BI__builtin_rvv_vget_v: { 4425 ASTContext::BuiltinVectorTypeInfo ResVecInfo = 4426 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>( 4427 TheCall->getType().getCanonicalType().getTypePtr())); 4428 ASTContext::BuiltinVectorTypeInfo VecInfo = 4429 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>( 4430 TheCall->getArg(0)->getType().getCanonicalType().getTypePtr())); 4431 unsigned MaxIndex = 4432 (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors) / 4433 (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors); 4434 return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1); 4435 } 4436 case RISCVVector::BI__builtin_rvv_vset_v: { 4437 ASTContext::BuiltinVectorTypeInfo ResVecInfo = 4438 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>( 4439 TheCall->getType().getCanonicalType().getTypePtr())); 4440 ASTContext::BuiltinVectorTypeInfo VecInfo = 4441 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>( 4442 TheCall->getArg(2)->getType().getCanonicalType().getTypePtr())); 4443 unsigned MaxIndex = 4444 (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors) / 4445 (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors); 4446 return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1); 4447 } 4448 // Check if byteselect is in [0, 3] 4449 case RISCV::BI__builtin_riscv_aes32dsi_32: 4450 case RISCV::BI__builtin_riscv_aes32dsmi_32: 4451 case RISCV::BI__builtin_riscv_aes32esi_32: 4452 case RISCV::BI__builtin_riscv_aes32esmi_32: 4453 case RISCV::BI__builtin_riscv_sm4ks: 4454 case RISCV::BI__builtin_riscv_sm4ed: 4455 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 4456 // Check if rnum is in [0, 10] 4457 case RISCV::BI__builtin_riscv_aes64ks1i_64: 4458 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 10); 4459 } 4460 4461 return false; 4462 } 4463 4464 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 4465 CallExpr *TheCall) { 4466 if (BuiltinID == SystemZ::BI__builtin_tabort) { 4467 Expr *Arg = TheCall->getArg(0); 4468 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 4469 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 4470 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 4471 << Arg->getSourceRange(); 4472 } 4473 4474 // For intrinsics which take an immediate value as part of the instruction, 4475 // range check them here. 4476 unsigned i = 0, l = 0, u = 0; 4477 switch (BuiltinID) { 4478 default: return false; 4479 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 4480 case SystemZ::BI__builtin_s390_verimb: 4481 case SystemZ::BI__builtin_s390_verimh: 4482 case SystemZ::BI__builtin_s390_verimf: 4483 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 4484 case SystemZ::BI__builtin_s390_vfaeb: 4485 case SystemZ::BI__builtin_s390_vfaeh: 4486 case SystemZ::BI__builtin_s390_vfaef: 4487 case SystemZ::BI__builtin_s390_vfaebs: 4488 case SystemZ::BI__builtin_s390_vfaehs: 4489 case SystemZ::BI__builtin_s390_vfaefs: 4490 case SystemZ::BI__builtin_s390_vfaezb: 4491 case SystemZ::BI__builtin_s390_vfaezh: 4492 case SystemZ::BI__builtin_s390_vfaezf: 4493 case SystemZ::BI__builtin_s390_vfaezbs: 4494 case SystemZ::BI__builtin_s390_vfaezhs: 4495 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 4496 case SystemZ::BI__builtin_s390_vfisb: 4497 case SystemZ::BI__builtin_s390_vfidb: 4498 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 4499 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 4500 case SystemZ::BI__builtin_s390_vftcisb: 4501 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 4502 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 4503 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 4504 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 4505 case SystemZ::BI__builtin_s390_vstrcb: 4506 case SystemZ::BI__builtin_s390_vstrch: 4507 case SystemZ::BI__builtin_s390_vstrcf: 4508 case SystemZ::BI__builtin_s390_vstrczb: 4509 case SystemZ::BI__builtin_s390_vstrczh: 4510 case SystemZ::BI__builtin_s390_vstrczf: 4511 case SystemZ::BI__builtin_s390_vstrcbs: 4512 case SystemZ::BI__builtin_s390_vstrchs: 4513 case SystemZ::BI__builtin_s390_vstrcfs: 4514 case SystemZ::BI__builtin_s390_vstrczbs: 4515 case SystemZ::BI__builtin_s390_vstrczhs: 4516 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 4517 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 4518 case SystemZ::BI__builtin_s390_vfminsb: 4519 case SystemZ::BI__builtin_s390_vfmaxsb: 4520 case SystemZ::BI__builtin_s390_vfmindb: 4521 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 4522 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 4523 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 4524 case SystemZ::BI__builtin_s390_vclfnhs: 4525 case SystemZ::BI__builtin_s390_vclfnls: 4526 case SystemZ::BI__builtin_s390_vcfn: 4527 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 4528 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 4529 } 4530 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 4531 } 4532 4533 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 4534 /// This checks that the target supports __builtin_cpu_supports and 4535 /// that the string argument is constant and valid. 4536 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 4537 CallExpr *TheCall) { 4538 Expr *Arg = TheCall->getArg(0); 4539 4540 // Check if the argument is a string literal. 4541 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4542 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 4543 << Arg->getSourceRange(); 4544 4545 // Check the contents of the string. 4546 StringRef Feature = 4547 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4548 if (!TI.validateCpuSupports(Feature)) 4549 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 4550 << Arg->getSourceRange(); 4551 return false; 4552 } 4553 4554 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 4555 /// This checks that the target supports __builtin_cpu_is and 4556 /// that the string argument is constant and valid. 4557 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 4558 Expr *Arg = TheCall->getArg(0); 4559 4560 // Check if the argument is a string literal. 4561 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4562 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 4563 << Arg->getSourceRange(); 4564 4565 // Check the contents of the string. 4566 StringRef Feature = 4567 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4568 if (!TI.validateCpuIs(Feature)) 4569 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 4570 << Arg->getSourceRange(); 4571 return false; 4572 } 4573 4574 // Check if the rounding mode is legal. 4575 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 4576 // Indicates if this instruction has rounding control or just SAE. 4577 bool HasRC = false; 4578 4579 unsigned ArgNum = 0; 4580 switch (BuiltinID) { 4581 default: 4582 return false; 4583 case X86::BI__builtin_ia32_vcvttsd2si32: 4584 case X86::BI__builtin_ia32_vcvttsd2si64: 4585 case X86::BI__builtin_ia32_vcvttsd2usi32: 4586 case X86::BI__builtin_ia32_vcvttsd2usi64: 4587 case X86::BI__builtin_ia32_vcvttss2si32: 4588 case X86::BI__builtin_ia32_vcvttss2si64: 4589 case X86::BI__builtin_ia32_vcvttss2usi32: 4590 case X86::BI__builtin_ia32_vcvttss2usi64: 4591 case X86::BI__builtin_ia32_vcvttsh2si32: 4592 case X86::BI__builtin_ia32_vcvttsh2si64: 4593 case X86::BI__builtin_ia32_vcvttsh2usi32: 4594 case X86::BI__builtin_ia32_vcvttsh2usi64: 4595 ArgNum = 1; 4596 break; 4597 case X86::BI__builtin_ia32_maxpd512: 4598 case X86::BI__builtin_ia32_maxps512: 4599 case X86::BI__builtin_ia32_minpd512: 4600 case X86::BI__builtin_ia32_minps512: 4601 case X86::BI__builtin_ia32_maxph512: 4602 case X86::BI__builtin_ia32_minph512: 4603 ArgNum = 2; 4604 break; 4605 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 4606 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 4607 case X86::BI__builtin_ia32_cvtps2pd512_mask: 4608 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 4609 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 4610 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 4611 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 4612 case X86::BI__builtin_ia32_cvttps2dq512_mask: 4613 case X86::BI__builtin_ia32_cvttps2qq512_mask: 4614 case X86::BI__builtin_ia32_cvttps2udq512_mask: 4615 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 4616 case X86::BI__builtin_ia32_vcvttph2w512_mask: 4617 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 4618 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 4619 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 4620 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 4621 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 4622 case X86::BI__builtin_ia32_exp2pd_mask: 4623 case X86::BI__builtin_ia32_exp2ps_mask: 4624 case X86::BI__builtin_ia32_getexppd512_mask: 4625 case X86::BI__builtin_ia32_getexpps512_mask: 4626 case X86::BI__builtin_ia32_getexpph512_mask: 4627 case X86::BI__builtin_ia32_rcp28pd_mask: 4628 case X86::BI__builtin_ia32_rcp28ps_mask: 4629 case X86::BI__builtin_ia32_rsqrt28pd_mask: 4630 case X86::BI__builtin_ia32_rsqrt28ps_mask: 4631 case X86::BI__builtin_ia32_vcomisd: 4632 case X86::BI__builtin_ia32_vcomiss: 4633 case X86::BI__builtin_ia32_vcomish: 4634 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 4635 ArgNum = 3; 4636 break; 4637 case X86::BI__builtin_ia32_cmppd512_mask: 4638 case X86::BI__builtin_ia32_cmpps512_mask: 4639 case X86::BI__builtin_ia32_cmpsd_mask: 4640 case X86::BI__builtin_ia32_cmpss_mask: 4641 case X86::BI__builtin_ia32_cmpsh_mask: 4642 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 4643 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 4644 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 4645 case X86::BI__builtin_ia32_getexpsd128_round_mask: 4646 case X86::BI__builtin_ia32_getexpss128_round_mask: 4647 case X86::BI__builtin_ia32_getexpsh128_round_mask: 4648 case X86::BI__builtin_ia32_getmantpd512_mask: 4649 case X86::BI__builtin_ia32_getmantps512_mask: 4650 case X86::BI__builtin_ia32_getmantph512_mask: 4651 case X86::BI__builtin_ia32_maxsd_round_mask: 4652 case X86::BI__builtin_ia32_maxss_round_mask: 4653 case X86::BI__builtin_ia32_maxsh_round_mask: 4654 case X86::BI__builtin_ia32_minsd_round_mask: 4655 case X86::BI__builtin_ia32_minss_round_mask: 4656 case X86::BI__builtin_ia32_minsh_round_mask: 4657 case X86::BI__builtin_ia32_rcp28sd_round_mask: 4658 case X86::BI__builtin_ia32_rcp28ss_round_mask: 4659 case X86::BI__builtin_ia32_reducepd512_mask: 4660 case X86::BI__builtin_ia32_reduceps512_mask: 4661 case X86::BI__builtin_ia32_reduceph512_mask: 4662 case X86::BI__builtin_ia32_rndscalepd_mask: 4663 case X86::BI__builtin_ia32_rndscaleps_mask: 4664 case X86::BI__builtin_ia32_rndscaleph_mask: 4665 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 4666 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 4667 ArgNum = 4; 4668 break; 4669 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4670 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4671 case X86::BI__builtin_ia32_fixupimmps512_mask: 4672 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4673 case X86::BI__builtin_ia32_fixupimmsd_mask: 4674 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4675 case X86::BI__builtin_ia32_fixupimmss_mask: 4676 case X86::BI__builtin_ia32_fixupimmss_maskz: 4677 case X86::BI__builtin_ia32_getmantsd_round_mask: 4678 case X86::BI__builtin_ia32_getmantss_round_mask: 4679 case X86::BI__builtin_ia32_getmantsh_round_mask: 4680 case X86::BI__builtin_ia32_rangepd512_mask: 4681 case X86::BI__builtin_ia32_rangeps512_mask: 4682 case X86::BI__builtin_ia32_rangesd128_round_mask: 4683 case X86::BI__builtin_ia32_rangess128_round_mask: 4684 case X86::BI__builtin_ia32_reducesd_mask: 4685 case X86::BI__builtin_ia32_reducess_mask: 4686 case X86::BI__builtin_ia32_reducesh_mask: 4687 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4688 case X86::BI__builtin_ia32_rndscaless_round_mask: 4689 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4690 ArgNum = 5; 4691 break; 4692 case X86::BI__builtin_ia32_vcvtsd2si64: 4693 case X86::BI__builtin_ia32_vcvtsd2si32: 4694 case X86::BI__builtin_ia32_vcvtsd2usi32: 4695 case X86::BI__builtin_ia32_vcvtsd2usi64: 4696 case X86::BI__builtin_ia32_vcvtss2si32: 4697 case X86::BI__builtin_ia32_vcvtss2si64: 4698 case X86::BI__builtin_ia32_vcvtss2usi32: 4699 case X86::BI__builtin_ia32_vcvtss2usi64: 4700 case X86::BI__builtin_ia32_vcvtsh2si32: 4701 case X86::BI__builtin_ia32_vcvtsh2si64: 4702 case X86::BI__builtin_ia32_vcvtsh2usi32: 4703 case X86::BI__builtin_ia32_vcvtsh2usi64: 4704 case X86::BI__builtin_ia32_sqrtpd512: 4705 case X86::BI__builtin_ia32_sqrtps512: 4706 case X86::BI__builtin_ia32_sqrtph512: 4707 ArgNum = 1; 4708 HasRC = true; 4709 break; 4710 case X86::BI__builtin_ia32_addph512: 4711 case X86::BI__builtin_ia32_divph512: 4712 case X86::BI__builtin_ia32_mulph512: 4713 case X86::BI__builtin_ia32_subph512: 4714 case X86::BI__builtin_ia32_addpd512: 4715 case X86::BI__builtin_ia32_addps512: 4716 case X86::BI__builtin_ia32_divpd512: 4717 case X86::BI__builtin_ia32_divps512: 4718 case X86::BI__builtin_ia32_mulpd512: 4719 case X86::BI__builtin_ia32_mulps512: 4720 case X86::BI__builtin_ia32_subpd512: 4721 case X86::BI__builtin_ia32_subps512: 4722 case X86::BI__builtin_ia32_cvtsi2sd64: 4723 case X86::BI__builtin_ia32_cvtsi2ss32: 4724 case X86::BI__builtin_ia32_cvtsi2ss64: 4725 case X86::BI__builtin_ia32_cvtusi2sd64: 4726 case X86::BI__builtin_ia32_cvtusi2ss32: 4727 case X86::BI__builtin_ia32_cvtusi2ss64: 4728 case X86::BI__builtin_ia32_vcvtusi2sh: 4729 case X86::BI__builtin_ia32_vcvtusi642sh: 4730 case X86::BI__builtin_ia32_vcvtsi2sh: 4731 case X86::BI__builtin_ia32_vcvtsi642sh: 4732 ArgNum = 2; 4733 HasRC = true; 4734 break; 4735 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4736 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4737 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4738 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4739 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4740 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4741 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4742 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4743 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4744 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4745 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4746 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4747 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4748 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4749 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4750 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4751 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4752 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4753 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4754 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4755 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4756 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4757 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4758 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4759 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4760 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4761 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4762 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4763 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4764 ArgNum = 3; 4765 HasRC = true; 4766 break; 4767 case X86::BI__builtin_ia32_addsh_round_mask: 4768 case X86::BI__builtin_ia32_addss_round_mask: 4769 case X86::BI__builtin_ia32_addsd_round_mask: 4770 case X86::BI__builtin_ia32_divsh_round_mask: 4771 case X86::BI__builtin_ia32_divss_round_mask: 4772 case X86::BI__builtin_ia32_divsd_round_mask: 4773 case X86::BI__builtin_ia32_mulsh_round_mask: 4774 case X86::BI__builtin_ia32_mulss_round_mask: 4775 case X86::BI__builtin_ia32_mulsd_round_mask: 4776 case X86::BI__builtin_ia32_subsh_round_mask: 4777 case X86::BI__builtin_ia32_subss_round_mask: 4778 case X86::BI__builtin_ia32_subsd_round_mask: 4779 case X86::BI__builtin_ia32_scalefph512_mask: 4780 case X86::BI__builtin_ia32_scalefpd512_mask: 4781 case X86::BI__builtin_ia32_scalefps512_mask: 4782 case X86::BI__builtin_ia32_scalefsd_round_mask: 4783 case X86::BI__builtin_ia32_scalefss_round_mask: 4784 case X86::BI__builtin_ia32_scalefsh_round_mask: 4785 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4786 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4787 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4788 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4789 case X86::BI__builtin_ia32_sqrtss_round_mask: 4790 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4791 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4792 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4793 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4794 case X86::BI__builtin_ia32_vfmaddss3_mask: 4795 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4796 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4797 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4798 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4799 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4800 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4801 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4802 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4803 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4804 case X86::BI__builtin_ia32_vfmaddps512_mask: 4805 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4806 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4807 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4808 case X86::BI__builtin_ia32_vfmaddph512_mask: 4809 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4810 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4811 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4812 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4813 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4814 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4815 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4816 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4817 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4818 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4819 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4820 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4821 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4822 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4823 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4824 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4825 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4826 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4827 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4828 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4829 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4830 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4831 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4832 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4833 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4834 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4835 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4836 case X86::BI__builtin_ia32_vfmulcsh_mask: 4837 case X86::BI__builtin_ia32_vfmulcph512_mask: 4838 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4839 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4840 ArgNum = 4; 4841 HasRC = true; 4842 break; 4843 } 4844 4845 llvm::APSInt Result; 4846 4847 // We can't check the value of a dependent argument. 4848 Expr *Arg = TheCall->getArg(ArgNum); 4849 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4850 return false; 4851 4852 // Check constant-ness first. 4853 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4854 return true; 4855 4856 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4857 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4858 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4859 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4860 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4861 Result == 8/*ROUND_NO_EXC*/ || 4862 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4863 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4864 return false; 4865 4866 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4867 << Arg->getSourceRange(); 4868 } 4869 4870 // Check if the gather/scatter scale is legal. 4871 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4872 CallExpr *TheCall) { 4873 unsigned ArgNum = 0; 4874 switch (BuiltinID) { 4875 default: 4876 return false; 4877 case X86::BI__builtin_ia32_gatherpfdpd: 4878 case X86::BI__builtin_ia32_gatherpfdps: 4879 case X86::BI__builtin_ia32_gatherpfqpd: 4880 case X86::BI__builtin_ia32_gatherpfqps: 4881 case X86::BI__builtin_ia32_scatterpfdpd: 4882 case X86::BI__builtin_ia32_scatterpfdps: 4883 case X86::BI__builtin_ia32_scatterpfqpd: 4884 case X86::BI__builtin_ia32_scatterpfqps: 4885 ArgNum = 3; 4886 break; 4887 case X86::BI__builtin_ia32_gatherd_pd: 4888 case X86::BI__builtin_ia32_gatherd_pd256: 4889 case X86::BI__builtin_ia32_gatherq_pd: 4890 case X86::BI__builtin_ia32_gatherq_pd256: 4891 case X86::BI__builtin_ia32_gatherd_ps: 4892 case X86::BI__builtin_ia32_gatherd_ps256: 4893 case X86::BI__builtin_ia32_gatherq_ps: 4894 case X86::BI__builtin_ia32_gatherq_ps256: 4895 case X86::BI__builtin_ia32_gatherd_q: 4896 case X86::BI__builtin_ia32_gatherd_q256: 4897 case X86::BI__builtin_ia32_gatherq_q: 4898 case X86::BI__builtin_ia32_gatherq_q256: 4899 case X86::BI__builtin_ia32_gatherd_d: 4900 case X86::BI__builtin_ia32_gatherd_d256: 4901 case X86::BI__builtin_ia32_gatherq_d: 4902 case X86::BI__builtin_ia32_gatherq_d256: 4903 case X86::BI__builtin_ia32_gather3div2df: 4904 case X86::BI__builtin_ia32_gather3div2di: 4905 case X86::BI__builtin_ia32_gather3div4df: 4906 case X86::BI__builtin_ia32_gather3div4di: 4907 case X86::BI__builtin_ia32_gather3div4sf: 4908 case X86::BI__builtin_ia32_gather3div4si: 4909 case X86::BI__builtin_ia32_gather3div8sf: 4910 case X86::BI__builtin_ia32_gather3div8si: 4911 case X86::BI__builtin_ia32_gather3siv2df: 4912 case X86::BI__builtin_ia32_gather3siv2di: 4913 case X86::BI__builtin_ia32_gather3siv4df: 4914 case X86::BI__builtin_ia32_gather3siv4di: 4915 case X86::BI__builtin_ia32_gather3siv4sf: 4916 case X86::BI__builtin_ia32_gather3siv4si: 4917 case X86::BI__builtin_ia32_gather3siv8sf: 4918 case X86::BI__builtin_ia32_gather3siv8si: 4919 case X86::BI__builtin_ia32_gathersiv8df: 4920 case X86::BI__builtin_ia32_gathersiv16sf: 4921 case X86::BI__builtin_ia32_gatherdiv8df: 4922 case X86::BI__builtin_ia32_gatherdiv16sf: 4923 case X86::BI__builtin_ia32_gathersiv8di: 4924 case X86::BI__builtin_ia32_gathersiv16si: 4925 case X86::BI__builtin_ia32_gatherdiv8di: 4926 case X86::BI__builtin_ia32_gatherdiv16si: 4927 case X86::BI__builtin_ia32_scatterdiv2df: 4928 case X86::BI__builtin_ia32_scatterdiv2di: 4929 case X86::BI__builtin_ia32_scatterdiv4df: 4930 case X86::BI__builtin_ia32_scatterdiv4di: 4931 case X86::BI__builtin_ia32_scatterdiv4sf: 4932 case X86::BI__builtin_ia32_scatterdiv4si: 4933 case X86::BI__builtin_ia32_scatterdiv8sf: 4934 case X86::BI__builtin_ia32_scatterdiv8si: 4935 case X86::BI__builtin_ia32_scattersiv2df: 4936 case X86::BI__builtin_ia32_scattersiv2di: 4937 case X86::BI__builtin_ia32_scattersiv4df: 4938 case X86::BI__builtin_ia32_scattersiv4di: 4939 case X86::BI__builtin_ia32_scattersiv4sf: 4940 case X86::BI__builtin_ia32_scattersiv4si: 4941 case X86::BI__builtin_ia32_scattersiv8sf: 4942 case X86::BI__builtin_ia32_scattersiv8si: 4943 case X86::BI__builtin_ia32_scattersiv8df: 4944 case X86::BI__builtin_ia32_scattersiv16sf: 4945 case X86::BI__builtin_ia32_scatterdiv8df: 4946 case X86::BI__builtin_ia32_scatterdiv16sf: 4947 case X86::BI__builtin_ia32_scattersiv8di: 4948 case X86::BI__builtin_ia32_scattersiv16si: 4949 case X86::BI__builtin_ia32_scatterdiv8di: 4950 case X86::BI__builtin_ia32_scatterdiv16si: 4951 ArgNum = 4; 4952 break; 4953 } 4954 4955 llvm::APSInt Result; 4956 4957 // We can't check the value of a dependent argument. 4958 Expr *Arg = TheCall->getArg(ArgNum); 4959 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4960 return false; 4961 4962 // Check constant-ness first. 4963 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4964 return true; 4965 4966 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4967 return false; 4968 4969 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4970 << Arg->getSourceRange(); 4971 } 4972 4973 enum { TileRegLow = 0, TileRegHigh = 7 }; 4974 4975 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4976 ArrayRef<int> ArgNums) { 4977 for (int ArgNum : ArgNums) { 4978 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4979 return true; 4980 } 4981 return false; 4982 } 4983 4984 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4985 ArrayRef<int> ArgNums) { 4986 // Because the max number of tile register is TileRegHigh + 1, so here we use 4987 // each bit to represent the usage of them in bitset. 4988 std::bitset<TileRegHigh + 1> ArgValues; 4989 for (int ArgNum : ArgNums) { 4990 Expr *Arg = TheCall->getArg(ArgNum); 4991 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4992 continue; 4993 4994 llvm::APSInt Result; 4995 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4996 return true; 4997 int ArgExtValue = Result.getExtValue(); 4998 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4999 "Incorrect tile register num."); 5000 if (ArgValues.test(ArgExtValue)) 5001 return Diag(TheCall->getBeginLoc(), 5002 diag::err_x86_builtin_tile_arg_duplicate) 5003 << TheCall->getArg(ArgNum)->getSourceRange(); 5004 ArgValues.set(ArgExtValue); 5005 } 5006 return false; 5007 } 5008 5009 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 5010 ArrayRef<int> ArgNums) { 5011 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 5012 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 5013 } 5014 5015 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 5016 switch (BuiltinID) { 5017 default: 5018 return false; 5019 case X86::BI__builtin_ia32_tileloadd64: 5020 case X86::BI__builtin_ia32_tileloaddt164: 5021 case X86::BI__builtin_ia32_tilestored64: 5022 case X86::BI__builtin_ia32_tilezero: 5023 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 5024 case X86::BI__builtin_ia32_tdpbssd: 5025 case X86::BI__builtin_ia32_tdpbsud: 5026 case X86::BI__builtin_ia32_tdpbusd: 5027 case X86::BI__builtin_ia32_tdpbuud: 5028 case X86::BI__builtin_ia32_tdpbf16ps: 5029 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 5030 } 5031 } 5032 static bool isX86_32Builtin(unsigned BuiltinID) { 5033 // These builtins only work on x86-32 targets. 5034 switch (BuiltinID) { 5035 case X86::BI__builtin_ia32_readeflags_u32: 5036 case X86::BI__builtin_ia32_writeeflags_u32: 5037 return true; 5038 } 5039 5040 return false; 5041 } 5042 5043 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 5044 CallExpr *TheCall) { 5045 if (BuiltinID == X86::BI__builtin_cpu_supports) 5046 return SemaBuiltinCpuSupports(*this, TI, TheCall); 5047 5048 if (BuiltinID == X86::BI__builtin_cpu_is) 5049 return SemaBuiltinCpuIs(*this, TI, TheCall); 5050 5051 // Check for 32-bit only builtins on a 64-bit target. 5052 const llvm::Triple &TT = TI.getTriple(); 5053 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 5054 return Diag(TheCall->getCallee()->getBeginLoc(), 5055 diag::err_32_bit_builtin_64_bit_tgt); 5056 5057 // If the intrinsic has rounding or SAE make sure its valid. 5058 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 5059 return true; 5060 5061 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 5062 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 5063 return true; 5064 5065 // If the intrinsic has a tile arguments, make sure they are valid. 5066 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 5067 return true; 5068 5069 // For intrinsics which take an immediate value as part of the instruction, 5070 // range check them here. 5071 int i = 0, l = 0, u = 0; 5072 switch (BuiltinID) { 5073 default: 5074 return false; 5075 case X86::BI__builtin_ia32_vec_ext_v2si: 5076 case X86::BI__builtin_ia32_vec_ext_v2di: 5077 case X86::BI__builtin_ia32_vextractf128_pd256: 5078 case X86::BI__builtin_ia32_vextractf128_ps256: 5079 case X86::BI__builtin_ia32_vextractf128_si256: 5080 case X86::BI__builtin_ia32_extract128i256: 5081 case X86::BI__builtin_ia32_extractf64x4_mask: 5082 case X86::BI__builtin_ia32_extracti64x4_mask: 5083 case X86::BI__builtin_ia32_extractf32x8_mask: 5084 case X86::BI__builtin_ia32_extracti32x8_mask: 5085 case X86::BI__builtin_ia32_extractf64x2_256_mask: 5086 case X86::BI__builtin_ia32_extracti64x2_256_mask: 5087 case X86::BI__builtin_ia32_extractf32x4_256_mask: 5088 case X86::BI__builtin_ia32_extracti32x4_256_mask: 5089 i = 1; l = 0; u = 1; 5090 break; 5091 case X86::BI__builtin_ia32_vec_set_v2di: 5092 case X86::BI__builtin_ia32_vinsertf128_pd256: 5093 case X86::BI__builtin_ia32_vinsertf128_ps256: 5094 case X86::BI__builtin_ia32_vinsertf128_si256: 5095 case X86::BI__builtin_ia32_insert128i256: 5096 case X86::BI__builtin_ia32_insertf32x8: 5097 case X86::BI__builtin_ia32_inserti32x8: 5098 case X86::BI__builtin_ia32_insertf64x4: 5099 case X86::BI__builtin_ia32_inserti64x4: 5100 case X86::BI__builtin_ia32_insertf64x2_256: 5101 case X86::BI__builtin_ia32_inserti64x2_256: 5102 case X86::BI__builtin_ia32_insertf32x4_256: 5103 case X86::BI__builtin_ia32_inserti32x4_256: 5104 i = 2; l = 0; u = 1; 5105 break; 5106 case X86::BI__builtin_ia32_vpermilpd: 5107 case X86::BI__builtin_ia32_vec_ext_v4hi: 5108 case X86::BI__builtin_ia32_vec_ext_v4si: 5109 case X86::BI__builtin_ia32_vec_ext_v4sf: 5110 case X86::BI__builtin_ia32_vec_ext_v4di: 5111 case X86::BI__builtin_ia32_extractf32x4_mask: 5112 case X86::BI__builtin_ia32_extracti32x4_mask: 5113 case X86::BI__builtin_ia32_extractf64x2_512_mask: 5114 case X86::BI__builtin_ia32_extracti64x2_512_mask: 5115 i = 1; l = 0; u = 3; 5116 break; 5117 case X86::BI_mm_prefetch: 5118 case X86::BI__builtin_ia32_vec_ext_v8hi: 5119 case X86::BI__builtin_ia32_vec_ext_v8si: 5120 i = 1; l = 0; u = 7; 5121 break; 5122 case X86::BI__builtin_ia32_sha1rnds4: 5123 case X86::BI__builtin_ia32_blendpd: 5124 case X86::BI__builtin_ia32_shufpd: 5125 case X86::BI__builtin_ia32_vec_set_v4hi: 5126 case X86::BI__builtin_ia32_vec_set_v4si: 5127 case X86::BI__builtin_ia32_vec_set_v4di: 5128 case X86::BI__builtin_ia32_shuf_f32x4_256: 5129 case X86::BI__builtin_ia32_shuf_f64x2_256: 5130 case X86::BI__builtin_ia32_shuf_i32x4_256: 5131 case X86::BI__builtin_ia32_shuf_i64x2_256: 5132 case X86::BI__builtin_ia32_insertf64x2_512: 5133 case X86::BI__builtin_ia32_inserti64x2_512: 5134 case X86::BI__builtin_ia32_insertf32x4: 5135 case X86::BI__builtin_ia32_inserti32x4: 5136 i = 2; l = 0; u = 3; 5137 break; 5138 case X86::BI__builtin_ia32_vpermil2pd: 5139 case X86::BI__builtin_ia32_vpermil2pd256: 5140 case X86::BI__builtin_ia32_vpermil2ps: 5141 case X86::BI__builtin_ia32_vpermil2ps256: 5142 i = 3; l = 0; u = 3; 5143 break; 5144 case X86::BI__builtin_ia32_cmpb128_mask: 5145 case X86::BI__builtin_ia32_cmpw128_mask: 5146 case X86::BI__builtin_ia32_cmpd128_mask: 5147 case X86::BI__builtin_ia32_cmpq128_mask: 5148 case X86::BI__builtin_ia32_cmpb256_mask: 5149 case X86::BI__builtin_ia32_cmpw256_mask: 5150 case X86::BI__builtin_ia32_cmpd256_mask: 5151 case X86::BI__builtin_ia32_cmpq256_mask: 5152 case X86::BI__builtin_ia32_cmpb512_mask: 5153 case X86::BI__builtin_ia32_cmpw512_mask: 5154 case X86::BI__builtin_ia32_cmpd512_mask: 5155 case X86::BI__builtin_ia32_cmpq512_mask: 5156 case X86::BI__builtin_ia32_ucmpb128_mask: 5157 case X86::BI__builtin_ia32_ucmpw128_mask: 5158 case X86::BI__builtin_ia32_ucmpd128_mask: 5159 case X86::BI__builtin_ia32_ucmpq128_mask: 5160 case X86::BI__builtin_ia32_ucmpb256_mask: 5161 case X86::BI__builtin_ia32_ucmpw256_mask: 5162 case X86::BI__builtin_ia32_ucmpd256_mask: 5163 case X86::BI__builtin_ia32_ucmpq256_mask: 5164 case X86::BI__builtin_ia32_ucmpb512_mask: 5165 case X86::BI__builtin_ia32_ucmpw512_mask: 5166 case X86::BI__builtin_ia32_ucmpd512_mask: 5167 case X86::BI__builtin_ia32_ucmpq512_mask: 5168 case X86::BI__builtin_ia32_vpcomub: 5169 case X86::BI__builtin_ia32_vpcomuw: 5170 case X86::BI__builtin_ia32_vpcomud: 5171 case X86::BI__builtin_ia32_vpcomuq: 5172 case X86::BI__builtin_ia32_vpcomb: 5173 case X86::BI__builtin_ia32_vpcomw: 5174 case X86::BI__builtin_ia32_vpcomd: 5175 case X86::BI__builtin_ia32_vpcomq: 5176 case X86::BI__builtin_ia32_vec_set_v8hi: 5177 case X86::BI__builtin_ia32_vec_set_v8si: 5178 i = 2; l = 0; u = 7; 5179 break; 5180 case X86::BI__builtin_ia32_vpermilpd256: 5181 case X86::BI__builtin_ia32_roundps: 5182 case X86::BI__builtin_ia32_roundpd: 5183 case X86::BI__builtin_ia32_roundps256: 5184 case X86::BI__builtin_ia32_roundpd256: 5185 case X86::BI__builtin_ia32_getmantpd128_mask: 5186 case X86::BI__builtin_ia32_getmantpd256_mask: 5187 case X86::BI__builtin_ia32_getmantps128_mask: 5188 case X86::BI__builtin_ia32_getmantps256_mask: 5189 case X86::BI__builtin_ia32_getmantpd512_mask: 5190 case X86::BI__builtin_ia32_getmantps512_mask: 5191 case X86::BI__builtin_ia32_getmantph128_mask: 5192 case X86::BI__builtin_ia32_getmantph256_mask: 5193 case X86::BI__builtin_ia32_getmantph512_mask: 5194 case X86::BI__builtin_ia32_vec_ext_v16qi: 5195 case X86::BI__builtin_ia32_vec_ext_v16hi: 5196 i = 1; l = 0; u = 15; 5197 break; 5198 case X86::BI__builtin_ia32_pblendd128: 5199 case X86::BI__builtin_ia32_blendps: 5200 case X86::BI__builtin_ia32_blendpd256: 5201 case X86::BI__builtin_ia32_shufpd256: 5202 case X86::BI__builtin_ia32_roundss: 5203 case X86::BI__builtin_ia32_roundsd: 5204 case X86::BI__builtin_ia32_rangepd128_mask: 5205 case X86::BI__builtin_ia32_rangepd256_mask: 5206 case X86::BI__builtin_ia32_rangepd512_mask: 5207 case X86::BI__builtin_ia32_rangeps128_mask: 5208 case X86::BI__builtin_ia32_rangeps256_mask: 5209 case X86::BI__builtin_ia32_rangeps512_mask: 5210 case X86::BI__builtin_ia32_getmantsd_round_mask: 5211 case X86::BI__builtin_ia32_getmantss_round_mask: 5212 case X86::BI__builtin_ia32_getmantsh_round_mask: 5213 case X86::BI__builtin_ia32_vec_set_v16qi: 5214 case X86::BI__builtin_ia32_vec_set_v16hi: 5215 i = 2; l = 0; u = 15; 5216 break; 5217 case X86::BI__builtin_ia32_vec_ext_v32qi: 5218 i = 1; l = 0; u = 31; 5219 break; 5220 case X86::BI__builtin_ia32_cmpps: 5221 case X86::BI__builtin_ia32_cmpss: 5222 case X86::BI__builtin_ia32_cmppd: 5223 case X86::BI__builtin_ia32_cmpsd: 5224 case X86::BI__builtin_ia32_cmpps256: 5225 case X86::BI__builtin_ia32_cmppd256: 5226 case X86::BI__builtin_ia32_cmpps128_mask: 5227 case X86::BI__builtin_ia32_cmppd128_mask: 5228 case X86::BI__builtin_ia32_cmpps256_mask: 5229 case X86::BI__builtin_ia32_cmppd256_mask: 5230 case X86::BI__builtin_ia32_cmpps512_mask: 5231 case X86::BI__builtin_ia32_cmppd512_mask: 5232 case X86::BI__builtin_ia32_cmpsd_mask: 5233 case X86::BI__builtin_ia32_cmpss_mask: 5234 case X86::BI__builtin_ia32_vec_set_v32qi: 5235 i = 2; l = 0; u = 31; 5236 break; 5237 case X86::BI__builtin_ia32_permdf256: 5238 case X86::BI__builtin_ia32_permdi256: 5239 case X86::BI__builtin_ia32_permdf512: 5240 case X86::BI__builtin_ia32_permdi512: 5241 case X86::BI__builtin_ia32_vpermilps: 5242 case X86::BI__builtin_ia32_vpermilps256: 5243 case X86::BI__builtin_ia32_vpermilpd512: 5244 case X86::BI__builtin_ia32_vpermilps512: 5245 case X86::BI__builtin_ia32_pshufd: 5246 case X86::BI__builtin_ia32_pshufd256: 5247 case X86::BI__builtin_ia32_pshufd512: 5248 case X86::BI__builtin_ia32_pshufhw: 5249 case X86::BI__builtin_ia32_pshufhw256: 5250 case X86::BI__builtin_ia32_pshufhw512: 5251 case X86::BI__builtin_ia32_pshuflw: 5252 case X86::BI__builtin_ia32_pshuflw256: 5253 case X86::BI__builtin_ia32_pshuflw512: 5254 case X86::BI__builtin_ia32_vcvtps2ph: 5255 case X86::BI__builtin_ia32_vcvtps2ph_mask: 5256 case X86::BI__builtin_ia32_vcvtps2ph256: 5257 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 5258 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 5259 case X86::BI__builtin_ia32_rndscaleps_128_mask: 5260 case X86::BI__builtin_ia32_rndscalepd_128_mask: 5261 case X86::BI__builtin_ia32_rndscaleps_256_mask: 5262 case X86::BI__builtin_ia32_rndscalepd_256_mask: 5263 case X86::BI__builtin_ia32_rndscaleps_mask: 5264 case X86::BI__builtin_ia32_rndscalepd_mask: 5265 case X86::BI__builtin_ia32_rndscaleph_mask: 5266 case X86::BI__builtin_ia32_reducepd128_mask: 5267 case X86::BI__builtin_ia32_reducepd256_mask: 5268 case X86::BI__builtin_ia32_reducepd512_mask: 5269 case X86::BI__builtin_ia32_reduceps128_mask: 5270 case X86::BI__builtin_ia32_reduceps256_mask: 5271 case X86::BI__builtin_ia32_reduceps512_mask: 5272 case X86::BI__builtin_ia32_reduceph128_mask: 5273 case X86::BI__builtin_ia32_reduceph256_mask: 5274 case X86::BI__builtin_ia32_reduceph512_mask: 5275 case X86::BI__builtin_ia32_prold512: 5276 case X86::BI__builtin_ia32_prolq512: 5277 case X86::BI__builtin_ia32_prold128: 5278 case X86::BI__builtin_ia32_prold256: 5279 case X86::BI__builtin_ia32_prolq128: 5280 case X86::BI__builtin_ia32_prolq256: 5281 case X86::BI__builtin_ia32_prord512: 5282 case X86::BI__builtin_ia32_prorq512: 5283 case X86::BI__builtin_ia32_prord128: 5284 case X86::BI__builtin_ia32_prord256: 5285 case X86::BI__builtin_ia32_prorq128: 5286 case X86::BI__builtin_ia32_prorq256: 5287 case X86::BI__builtin_ia32_fpclasspd128_mask: 5288 case X86::BI__builtin_ia32_fpclasspd256_mask: 5289 case X86::BI__builtin_ia32_fpclassps128_mask: 5290 case X86::BI__builtin_ia32_fpclassps256_mask: 5291 case X86::BI__builtin_ia32_fpclassps512_mask: 5292 case X86::BI__builtin_ia32_fpclasspd512_mask: 5293 case X86::BI__builtin_ia32_fpclassph128_mask: 5294 case X86::BI__builtin_ia32_fpclassph256_mask: 5295 case X86::BI__builtin_ia32_fpclassph512_mask: 5296 case X86::BI__builtin_ia32_fpclasssd_mask: 5297 case X86::BI__builtin_ia32_fpclassss_mask: 5298 case X86::BI__builtin_ia32_fpclasssh_mask: 5299 case X86::BI__builtin_ia32_pslldqi128_byteshift: 5300 case X86::BI__builtin_ia32_pslldqi256_byteshift: 5301 case X86::BI__builtin_ia32_pslldqi512_byteshift: 5302 case X86::BI__builtin_ia32_psrldqi128_byteshift: 5303 case X86::BI__builtin_ia32_psrldqi256_byteshift: 5304 case X86::BI__builtin_ia32_psrldqi512_byteshift: 5305 case X86::BI__builtin_ia32_kshiftliqi: 5306 case X86::BI__builtin_ia32_kshiftlihi: 5307 case X86::BI__builtin_ia32_kshiftlisi: 5308 case X86::BI__builtin_ia32_kshiftlidi: 5309 case X86::BI__builtin_ia32_kshiftriqi: 5310 case X86::BI__builtin_ia32_kshiftrihi: 5311 case X86::BI__builtin_ia32_kshiftrisi: 5312 case X86::BI__builtin_ia32_kshiftridi: 5313 i = 1; l = 0; u = 255; 5314 break; 5315 case X86::BI__builtin_ia32_vperm2f128_pd256: 5316 case X86::BI__builtin_ia32_vperm2f128_ps256: 5317 case X86::BI__builtin_ia32_vperm2f128_si256: 5318 case X86::BI__builtin_ia32_permti256: 5319 case X86::BI__builtin_ia32_pblendw128: 5320 case X86::BI__builtin_ia32_pblendw256: 5321 case X86::BI__builtin_ia32_blendps256: 5322 case X86::BI__builtin_ia32_pblendd256: 5323 case X86::BI__builtin_ia32_palignr128: 5324 case X86::BI__builtin_ia32_palignr256: 5325 case X86::BI__builtin_ia32_palignr512: 5326 case X86::BI__builtin_ia32_alignq512: 5327 case X86::BI__builtin_ia32_alignd512: 5328 case X86::BI__builtin_ia32_alignd128: 5329 case X86::BI__builtin_ia32_alignd256: 5330 case X86::BI__builtin_ia32_alignq128: 5331 case X86::BI__builtin_ia32_alignq256: 5332 case X86::BI__builtin_ia32_vcomisd: 5333 case X86::BI__builtin_ia32_vcomiss: 5334 case X86::BI__builtin_ia32_shuf_f32x4: 5335 case X86::BI__builtin_ia32_shuf_f64x2: 5336 case X86::BI__builtin_ia32_shuf_i32x4: 5337 case X86::BI__builtin_ia32_shuf_i64x2: 5338 case X86::BI__builtin_ia32_shufpd512: 5339 case X86::BI__builtin_ia32_shufps: 5340 case X86::BI__builtin_ia32_shufps256: 5341 case X86::BI__builtin_ia32_shufps512: 5342 case X86::BI__builtin_ia32_dbpsadbw128: 5343 case X86::BI__builtin_ia32_dbpsadbw256: 5344 case X86::BI__builtin_ia32_dbpsadbw512: 5345 case X86::BI__builtin_ia32_vpshldd128: 5346 case X86::BI__builtin_ia32_vpshldd256: 5347 case X86::BI__builtin_ia32_vpshldd512: 5348 case X86::BI__builtin_ia32_vpshldq128: 5349 case X86::BI__builtin_ia32_vpshldq256: 5350 case X86::BI__builtin_ia32_vpshldq512: 5351 case X86::BI__builtin_ia32_vpshldw128: 5352 case X86::BI__builtin_ia32_vpshldw256: 5353 case X86::BI__builtin_ia32_vpshldw512: 5354 case X86::BI__builtin_ia32_vpshrdd128: 5355 case X86::BI__builtin_ia32_vpshrdd256: 5356 case X86::BI__builtin_ia32_vpshrdd512: 5357 case X86::BI__builtin_ia32_vpshrdq128: 5358 case X86::BI__builtin_ia32_vpshrdq256: 5359 case X86::BI__builtin_ia32_vpshrdq512: 5360 case X86::BI__builtin_ia32_vpshrdw128: 5361 case X86::BI__builtin_ia32_vpshrdw256: 5362 case X86::BI__builtin_ia32_vpshrdw512: 5363 i = 2; l = 0; u = 255; 5364 break; 5365 case X86::BI__builtin_ia32_fixupimmpd512_mask: 5366 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 5367 case X86::BI__builtin_ia32_fixupimmps512_mask: 5368 case X86::BI__builtin_ia32_fixupimmps512_maskz: 5369 case X86::BI__builtin_ia32_fixupimmsd_mask: 5370 case X86::BI__builtin_ia32_fixupimmsd_maskz: 5371 case X86::BI__builtin_ia32_fixupimmss_mask: 5372 case X86::BI__builtin_ia32_fixupimmss_maskz: 5373 case X86::BI__builtin_ia32_fixupimmpd128_mask: 5374 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 5375 case X86::BI__builtin_ia32_fixupimmpd256_mask: 5376 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 5377 case X86::BI__builtin_ia32_fixupimmps128_mask: 5378 case X86::BI__builtin_ia32_fixupimmps128_maskz: 5379 case X86::BI__builtin_ia32_fixupimmps256_mask: 5380 case X86::BI__builtin_ia32_fixupimmps256_maskz: 5381 case X86::BI__builtin_ia32_pternlogd512_mask: 5382 case X86::BI__builtin_ia32_pternlogd512_maskz: 5383 case X86::BI__builtin_ia32_pternlogq512_mask: 5384 case X86::BI__builtin_ia32_pternlogq512_maskz: 5385 case X86::BI__builtin_ia32_pternlogd128_mask: 5386 case X86::BI__builtin_ia32_pternlogd128_maskz: 5387 case X86::BI__builtin_ia32_pternlogd256_mask: 5388 case X86::BI__builtin_ia32_pternlogd256_maskz: 5389 case X86::BI__builtin_ia32_pternlogq128_mask: 5390 case X86::BI__builtin_ia32_pternlogq128_maskz: 5391 case X86::BI__builtin_ia32_pternlogq256_mask: 5392 case X86::BI__builtin_ia32_pternlogq256_maskz: 5393 i = 3; l = 0; u = 255; 5394 break; 5395 case X86::BI__builtin_ia32_gatherpfdpd: 5396 case X86::BI__builtin_ia32_gatherpfdps: 5397 case X86::BI__builtin_ia32_gatherpfqpd: 5398 case X86::BI__builtin_ia32_gatherpfqps: 5399 case X86::BI__builtin_ia32_scatterpfdpd: 5400 case X86::BI__builtin_ia32_scatterpfdps: 5401 case X86::BI__builtin_ia32_scatterpfqpd: 5402 case X86::BI__builtin_ia32_scatterpfqps: 5403 i = 4; l = 2; u = 3; 5404 break; 5405 case X86::BI__builtin_ia32_reducesd_mask: 5406 case X86::BI__builtin_ia32_reducess_mask: 5407 case X86::BI__builtin_ia32_rndscalesd_round_mask: 5408 case X86::BI__builtin_ia32_rndscaless_round_mask: 5409 case X86::BI__builtin_ia32_rndscalesh_round_mask: 5410 case X86::BI__builtin_ia32_reducesh_mask: 5411 i = 4; l = 0; u = 255; 5412 break; 5413 } 5414 5415 // Note that we don't force a hard error on the range check here, allowing 5416 // template-generated or macro-generated dead code to potentially have out-of- 5417 // range values. These need to code generate, but don't need to necessarily 5418 // make any sense. We use a warning that defaults to an error. 5419 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 5420 } 5421 5422 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 5423 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 5424 /// Returns true when the format fits the function and the FormatStringInfo has 5425 /// been populated. 5426 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 5427 FormatStringInfo *FSI) { 5428 FSI->HasVAListArg = Format->getFirstArg() == 0; 5429 FSI->FormatIdx = Format->getFormatIdx() - 1; 5430 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 5431 5432 // The way the format attribute works in GCC, the implicit this argument 5433 // of member functions is counted. However, it doesn't appear in our own 5434 // lists, so decrement format_idx in that case. 5435 if (IsCXXMember) { 5436 if(FSI->FormatIdx == 0) 5437 return false; 5438 --FSI->FormatIdx; 5439 if (FSI->FirstDataArg != 0) 5440 --FSI->FirstDataArg; 5441 } 5442 return true; 5443 } 5444 5445 /// Checks if a the given expression evaluates to null. 5446 /// 5447 /// Returns true if the value evaluates to null. 5448 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 5449 // If the expression has non-null type, it doesn't evaluate to null. 5450 if (auto nullability 5451 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 5452 if (*nullability == NullabilityKind::NonNull) 5453 return false; 5454 } 5455 5456 // As a special case, transparent unions initialized with zero are 5457 // considered null for the purposes of the nonnull attribute. 5458 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 5459 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 5460 if (const CompoundLiteralExpr *CLE = 5461 dyn_cast<CompoundLiteralExpr>(Expr)) 5462 if (const InitListExpr *ILE = 5463 dyn_cast<InitListExpr>(CLE->getInitializer())) 5464 Expr = ILE->getInit(0); 5465 } 5466 5467 bool Result; 5468 return (!Expr->isValueDependent() && 5469 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 5470 !Result); 5471 } 5472 5473 static void CheckNonNullArgument(Sema &S, 5474 const Expr *ArgExpr, 5475 SourceLocation CallSiteLoc) { 5476 if (CheckNonNullExpr(S, ArgExpr)) 5477 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 5478 S.PDiag(diag::warn_null_arg) 5479 << ArgExpr->getSourceRange()); 5480 } 5481 5482 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 5483 FormatStringInfo FSI; 5484 if ((GetFormatStringType(Format) == FST_NSString) && 5485 getFormatStringInfo(Format, false, &FSI)) { 5486 Idx = FSI.FormatIdx; 5487 return true; 5488 } 5489 return false; 5490 } 5491 5492 /// Diagnose use of %s directive in an NSString which is being passed 5493 /// as formatting string to formatting method. 5494 static void 5495 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 5496 const NamedDecl *FDecl, 5497 Expr **Args, 5498 unsigned NumArgs) { 5499 unsigned Idx = 0; 5500 bool Format = false; 5501 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 5502 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 5503 Idx = 2; 5504 Format = true; 5505 } 5506 else 5507 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5508 if (S.GetFormatNSStringIdx(I, Idx)) { 5509 Format = true; 5510 break; 5511 } 5512 } 5513 if (!Format || NumArgs <= Idx) 5514 return; 5515 const Expr *FormatExpr = Args[Idx]; 5516 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 5517 FormatExpr = CSCE->getSubExpr(); 5518 const StringLiteral *FormatString; 5519 if (const ObjCStringLiteral *OSL = 5520 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 5521 FormatString = OSL->getString(); 5522 else 5523 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 5524 if (!FormatString) 5525 return; 5526 if (S.FormatStringHasSArg(FormatString)) { 5527 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 5528 << "%s" << 1 << 1; 5529 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 5530 << FDecl->getDeclName(); 5531 } 5532 } 5533 5534 /// Determine whether the given type has a non-null nullability annotation. 5535 static bool isNonNullType(ASTContext &ctx, QualType type) { 5536 if (auto nullability = type->getNullability(ctx)) 5537 return *nullability == NullabilityKind::NonNull; 5538 5539 return false; 5540 } 5541 5542 static void CheckNonNullArguments(Sema &S, 5543 const NamedDecl *FDecl, 5544 const FunctionProtoType *Proto, 5545 ArrayRef<const Expr *> Args, 5546 SourceLocation CallSiteLoc) { 5547 assert((FDecl || Proto) && "Need a function declaration or prototype"); 5548 5549 // Already checked by by constant evaluator. 5550 if (S.isConstantEvaluated()) 5551 return; 5552 // Check the attributes attached to the method/function itself. 5553 llvm::SmallBitVector NonNullArgs; 5554 if (FDecl) { 5555 // Handle the nonnull attribute on the function/method declaration itself. 5556 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 5557 if (!NonNull->args_size()) { 5558 // Easy case: all pointer arguments are nonnull. 5559 for (const auto *Arg : Args) 5560 if (S.isValidPointerAttrType(Arg->getType())) 5561 CheckNonNullArgument(S, Arg, CallSiteLoc); 5562 return; 5563 } 5564 5565 for (const ParamIdx &Idx : NonNull->args()) { 5566 unsigned IdxAST = Idx.getASTIndex(); 5567 if (IdxAST >= Args.size()) 5568 continue; 5569 if (NonNullArgs.empty()) 5570 NonNullArgs.resize(Args.size()); 5571 NonNullArgs.set(IdxAST); 5572 } 5573 } 5574 } 5575 5576 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 5577 // Handle the nonnull attribute on the parameters of the 5578 // function/method. 5579 ArrayRef<ParmVarDecl*> parms; 5580 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 5581 parms = FD->parameters(); 5582 else 5583 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 5584 5585 unsigned ParamIndex = 0; 5586 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 5587 I != E; ++I, ++ParamIndex) { 5588 const ParmVarDecl *PVD = *I; 5589 if (PVD->hasAttr<NonNullAttr>() || 5590 isNonNullType(S.Context, PVD->getType())) { 5591 if (NonNullArgs.empty()) 5592 NonNullArgs.resize(Args.size()); 5593 5594 NonNullArgs.set(ParamIndex); 5595 } 5596 } 5597 } else { 5598 // If we have a non-function, non-method declaration but no 5599 // function prototype, try to dig out the function prototype. 5600 if (!Proto) { 5601 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 5602 QualType type = VD->getType().getNonReferenceType(); 5603 if (auto pointerType = type->getAs<PointerType>()) 5604 type = pointerType->getPointeeType(); 5605 else if (auto blockType = type->getAs<BlockPointerType>()) 5606 type = blockType->getPointeeType(); 5607 // FIXME: data member pointers? 5608 5609 // Dig out the function prototype, if there is one. 5610 Proto = type->getAs<FunctionProtoType>(); 5611 } 5612 } 5613 5614 // Fill in non-null argument information from the nullability 5615 // information on the parameter types (if we have them). 5616 if (Proto) { 5617 unsigned Index = 0; 5618 for (auto paramType : Proto->getParamTypes()) { 5619 if (isNonNullType(S.Context, paramType)) { 5620 if (NonNullArgs.empty()) 5621 NonNullArgs.resize(Args.size()); 5622 5623 NonNullArgs.set(Index); 5624 } 5625 5626 ++Index; 5627 } 5628 } 5629 } 5630 5631 // Check for non-null arguments. 5632 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 5633 ArgIndex != ArgIndexEnd; ++ArgIndex) { 5634 if (NonNullArgs[ArgIndex]) 5635 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 5636 } 5637 } 5638 5639 /// Warn if a pointer or reference argument passed to a function points to an 5640 /// object that is less aligned than the parameter. This can happen when 5641 /// creating a typedef with a lower alignment than the original type and then 5642 /// calling functions defined in terms of the original type. 5643 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 5644 StringRef ParamName, QualType ArgTy, 5645 QualType ParamTy) { 5646 5647 // If a function accepts a pointer or reference type 5648 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 5649 return; 5650 5651 // If the parameter is a pointer type, get the pointee type for the 5652 // argument too. If the parameter is a reference type, don't try to get 5653 // the pointee type for the argument. 5654 if (ParamTy->isPointerType()) 5655 ArgTy = ArgTy->getPointeeType(); 5656 5657 // Remove reference or pointer 5658 ParamTy = ParamTy->getPointeeType(); 5659 5660 // Find expected alignment, and the actual alignment of the passed object. 5661 // getTypeAlignInChars requires complete types 5662 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 5663 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 5664 ArgTy->isUndeducedType()) 5665 return; 5666 5667 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 5668 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 5669 5670 // If the argument is less aligned than the parameter, there is a 5671 // potential alignment issue. 5672 if (ArgAlign < ParamAlign) 5673 Diag(Loc, diag::warn_param_mismatched_alignment) 5674 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 5675 << ParamName << (FDecl != nullptr) << FDecl; 5676 } 5677 5678 /// Handles the checks for format strings, non-POD arguments to vararg 5679 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5680 /// attributes. 5681 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5682 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5683 bool IsMemberFunction, SourceLocation Loc, 5684 SourceRange Range, VariadicCallType CallType) { 5685 // FIXME: We should check as much as we can in the template definition. 5686 if (CurContext->isDependentContext()) 5687 return; 5688 5689 // Printf and scanf checking. 5690 llvm::SmallBitVector CheckedVarArgs; 5691 if (FDecl) { 5692 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5693 // Only create vector if there are format attributes. 5694 CheckedVarArgs.resize(Args.size()); 5695 5696 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5697 CheckedVarArgs); 5698 } 5699 } 5700 5701 // Refuse POD arguments that weren't caught by the format string 5702 // checks above. 5703 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5704 if (CallType != VariadicDoesNotApply && 5705 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5706 unsigned NumParams = Proto ? Proto->getNumParams() 5707 : FDecl && isa<FunctionDecl>(FDecl) 5708 ? cast<FunctionDecl>(FDecl)->getNumParams() 5709 : FDecl && isa<ObjCMethodDecl>(FDecl) 5710 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5711 : 0; 5712 5713 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5714 // Args[ArgIdx] can be null in malformed code. 5715 if (const Expr *Arg = Args[ArgIdx]) { 5716 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5717 checkVariadicArgument(Arg, CallType); 5718 } 5719 } 5720 } 5721 5722 if (FDecl || Proto) { 5723 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5724 5725 // Type safety checking. 5726 if (FDecl) { 5727 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5728 CheckArgumentWithTypeTag(I, Args, Loc); 5729 } 5730 } 5731 5732 // Check that passed arguments match the alignment of original arguments. 5733 // Try to get the missing prototype from the declaration. 5734 if (!Proto && FDecl) { 5735 const auto *FT = FDecl->getFunctionType(); 5736 if (isa_and_nonnull<FunctionProtoType>(FT)) 5737 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5738 } 5739 if (Proto) { 5740 // For variadic functions, we may have more args than parameters. 5741 // For some K&R functions, we may have less args than parameters. 5742 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5743 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5744 // Args[ArgIdx] can be null in malformed code. 5745 if (const Expr *Arg = Args[ArgIdx]) { 5746 if (Arg->containsErrors()) 5747 continue; 5748 5749 QualType ParamTy = Proto->getParamType(ArgIdx); 5750 QualType ArgTy = Arg->getType(); 5751 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5752 ArgTy, ParamTy); 5753 } 5754 } 5755 } 5756 5757 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5758 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5759 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5760 if (!Arg->isValueDependent()) { 5761 Expr::EvalResult Align; 5762 if (Arg->EvaluateAsInt(Align, Context)) { 5763 const llvm::APSInt &I = Align.Val.getInt(); 5764 if (!I.isPowerOf2()) 5765 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5766 << Arg->getSourceRange(); 5767 5768 if (I > Sema::MaximumAlignment) 5769 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5770 << Arg->getSourceRange() << Sema::MaximumAlignment; 5771 } 5772 } 5773 } 5774 5775 if (FD) 5776 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5777 } 5778 5779 /// CheckConstructorCall - Check a constructor call for correctness and safety 5780 /// properties not enforced by the C type system. 5781 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5782 ArrayRef<const Expr *> Args, 5783 const FunctionProtoType *Proto, 5784 SourceLocation Loc) { 5785 VariadicCallType CallType = 5786 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5787 5788 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5789 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5790 Context.getPointerType(Ctor->getThisObjectType())); 5791 5792 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5793 Loc, SourceRange(), CallType); 5794 } 5795 5796 /// CheckFunctionCall - Check a direct function call for various correctness 5797 /// and safety properties not strictly enforced by the C type system. 5798 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5799 const FunctionProtoType *Proto) { 5800 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5801 isa<CXXMethodDecl>(FDecl); 5802 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5803 IsMemberOperatorCall; 5804 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5805 TheCall->getCallee()); 5806 Expr** Args = TheCall->getArgs(); 5807 unsigned NumArgs = TheCall->getNumArgs(); 5808 5809 Expr *ImplicitThis = nullptr; 5810 if (IsMemberOperatorCall) { 5811 // If this is a call to a member operator, hide the first argument 5812 // from checkCall. 5813 // FIXME: Our choice of AST representation here is less than ideal. 5814 ImplicitThis = Args[0]; 5815 ++Args; 5816 --NumArgs; 5817 } else if (IsMemberFunction) 5818 ImplicitThis = 5819 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5820 5821 if (ImplicitThis) { 5822 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5823 // used. 5824 QualType ThisType = ImplicitThis->getType(); 5825 if (!ThisType->isPointerType()) { 5826 assert(!ThisType->isReferenceType()); 5827 ThisType = Context.getPointerType(ThisType); 5828 } 5829 5830 QualType ThisTypeFromDecl = 5831 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5832 5833 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5834 ThisTypeFromDecl); 5835 } 5836 5837 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5838 IsMemberFunction, TheCall->getRParenLoc(), 5839 TheCall->getCallee()->getSourceRange(), CallType); 5840 5841 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5842 // None of the checks below are needed for functions that don't have 5843 // simple names (e.g., C++ conversion functions). 5844 if (!FnInfo) 5845 return false; 5846 5847 // Enforce TCB except for builtin calls, which are always allowed. 5848 if (FDecl->getBuiltinID() == 0) 5849 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl); 5850 5851 CheckAbsoluteValueFunction(TheCall, FDecl); 5852 CheckMaxUnsignedZero(TheCall, FDecl); 5853 5854 if (getLangOpts().ObjC) 5855 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5856 5857 unsigned CMId = FDecl->getMemoryFunctionKind(); 5858 5859 // Handle memory setting and copying functions. 5860 switch (CMId) { 5861 case 0: 5862 return false; 5863 case Builtin::BIstrlcpy: // fallthrough 5864 case Builtin::BIstrlcat: 5865 CheckStrlcpycatArguments(TheCall, FnInfo); 5866 break; 5867 case Builtin::BIstrncat: 5868 CheckStrncatArguments(TheCall, FnInfo); 5869 break; 5870 case Builtin::BIfree: 5871 CheckFreeArguments(TheCall); 5872 break; 5873 default: 5874 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5875 } 5876 5877 return false; 5878 } 5879 5880 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5881 ArrayRef<const Expr *> Args) { 5882 VariadicCallType CallType = 5883 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5884 5885 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5886 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5887 CallType); 5888 5889 CheckTCBEnforcement(lbrac, Method); 5890 5891 return false; 5892 } 5893 5894 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5895 const FunctionProtoType *Proto) { 5896 QualType Ty; 5897 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5898 Ty = V->getType().getNonReferenceType(); 5899 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5900 Ty = F->getType().getNonReferenceType(); 5901 else 5902 return false; 5903 5904 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5905 !Ty->isFunctionProtoType()) 5906 return false; 5907 5908 VariadicCallType CallType; 5909 if (!Proto || !Proto->isVariadic()) { 5910 CallType = VariadicDoesNotApply; 5911 } else if (Ty->isBlockPointerType()) { 5912 CallType = VariadicBlock; 5913 } else { // Ty->isFunctionPointerType() 5914 CallType = VariadicFunction; 5915 } 5916 5917 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5918 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5919 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5920 TheCall->getCallee()->getSourceRange(), CallType); 5921 5922 return false; 5923 } 5924 5925 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5926 /// such as function pointers returned from functions. 5927 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5928 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5929 TheCall->getCallee()); 5930 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5931 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5932 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5933 TheCall->getCallee()->getSourceRange(), CallType); 5934 5935 return false; 5936 } 5937 5938 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5939 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5940 return false; 5941 5942 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5943 switch (Op) { 5944 case AtomicExpr::AO__c11_atomic_init: 5945 case AtomicExpr::AO__opencl_atomic_init: 5946 llvm_unreachable("There is no ordering argument for an init"); 5947 5948 case AtomicExpr::AO__c11_atomic_load: 5949 case AtomicExpr::AO__opencl_atomic_load: 5950 case AtomicExpr::AO__hip_atomic_load: 5951 case AtomicExpr::AO__atomic_load_n: 5952 case AtomicExpr::AO__atomic_load: 5953 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5954 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5955 5956 case AtomicExpr::AO__c11_atomic_store: 5957 case AtomicExpr::AO__opencl_atomic_store: 5958 case AtomicExpr::AO__hip_atomic_store: 5959 case AtomicExpr::AO__atomic_store: 5960 case AtomicExpr::AO__atomic_store_n: 5961 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5962 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5963 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5964 5965 default: 5966 return true; 5967 } 5968 } 5969 5970 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5971 AtomicExpr::AtomicOp Op) { 5972 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5973 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5974 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5975 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5976 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5977 Op); 5978 } 5979 5980 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5981 SourceLocation RParenLoc, MultiExprArg Args, 5982 AtomicExpr::AtomicOp Op, 5983 AtomicArgumentOrder ArgOrder) { 5984 // All the non-OpenCL operations take one of the following forms. 5985 // The OpenCL operations take the __c11 forms with one extra argument for 5986 // synchronization scope. 5987 enum { 5988 // C __c11_atomic_init(A *, C) 5989 Init, 5990 5991 // C __c11_atomic_load(A *, int) 5992 Load, 5993 5994 // void __atomic_load(A *, CP, int) 5995 LoadCopy, 5996 5997 // void __atomic_store(A *, CP, int) 5998 Copy, 5999 6000 // C __c11_atomic_add(A *, M, int) 6001 Arithmetic, 6002 6003 // C __atomic_exchange_n(A *, CP, int) 6004 Xchg, 6005 6006 // void __atomic_exchange(A *, C *, CP, int) 6007 GNUXchg, 6008 6009 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 6010 C11CmpXchg, 6011 6012 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 6013 GNUCmpXchg 6014 } Form = Init; 6015 6016 const unsigned NumForm = GNUCmpXchg + 1; 6017 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 6018 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 6019 // where: 6020 // C is an appropriate type, 6021 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 6022 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 6023 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 6024 // the int parameters are for orderings. 6025 6026 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 6027 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 6028 "need to update code for modified forms"); 6029 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 6030 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 6031 AtomicExpr::AO__atomic_load, 6032 "need to update code for modified C11 atomics"); 6033 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 6034 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 6035 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load && 6036 Op <= AtomicExpr::AO__hip_atomic_fetch_max; 6037 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 6038 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 6039 IsOpenCL; 6040 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 6041 Op == AtomicExpr::AO__atomic_store_n || 6042 Op == AtomicExpr::AO__atomic_exchange_n || 6043 Op == AtomicExpr::AO__atomic_compare_exchange_n; 6044 bool IsAddSub = false; 6045 6046 switch (Op) { 6047 case AtomicExpr::AO__c11_atomic_init: 6048 case AtomicExpr::AO__opencl_atomic_init: 6049 Form = Init; 6050 break; 6051 6052 case AtomicExpr::AO__c11_atomic_load: 6053 case AtomicExpr::AO__opencl_atomic_load: 6054 case AtomicExpr::AO__hip_atomic_load: 6055 case AtomicExpr::AO__atomic_load_n: 6056 Form = Load; 6057 break; 6058 6059 case AtomicExpr::AO__atomic_load: 6060 Form = LoadCopy; 6061 break; 6062 6063 case AtomicExpr::AO__c11_atomic_store: 6064 case AtomicExpr::AO__opencl_atomic_store: 6065 case AtomicExpr::AO__hip_atomic_store: 6066 case AtomicExpr::AO__atomic_store: 6067 case AtomicExpr::AO__atomic_store_n: 6068 Form = Copy; 6069 break; 6070 case AtomicExpr::AO__hip_atomic_fetch_add: 6071 case AtomicExpr::AO__hip_atomic_fetch_min: 6072 case AtomicExpr::AO__hip_atomic_fetch_max: 6073 case AtomicExpr::AO__c11_atomic_fetch_add: 6074 case AtomicExpr::AO__c11_atomic_fetch_sub: 6075 case AtomicExpr::AO__opencl_atomic_fetch_add: 6076 case AtomicExpr::AO__opencl_atomic_fetch_sub: 6077 case AtomicExpr::AO__atomic_fetch_add: 6078 case AtomicExpr::AO__atomic_fetch_sub: 6079 case AtomicExpr::AO__atomic_add_fetch: 6080 case AtomicExpr::AO__atomic_sub_fetch: 6081 IsAddSub = true; 6082 Form = Arithmetic; 6083 break; 6084 case AtomicExpr::AO__c11_atomic_fetch_and: 6085 case AtomicExpr::AO__c11_atomic_fetch_or: 6086 case AtomicExpr::AO__c11_atomic_fetch_xor: 6087 case AtomicExpr::AO__hip_atomic_fetch_and: 6088 case AtomicExpr::AO__hip_atomic_fetch_or: 6089 case AtomicExpr::AO__hip_atomic_fetch_xor: 6090 case AtomicExpr::AO__c11_atomic_fetch_nand: 6091 case AtomicExpr::AO__opencl_atomic_fetch_and: 6092 case AtomicExpr::AO__opencl_atomic_fetch_or: 6093 case AtomicExpr::AO__opencl_atomic_fetch_xor: 6094 case AtomicExpr::AO__atomic_fetch_and: 6095 case AtomicExpr::AO__atomic_fetch_or: 6096 case AtomicExpr::AO__atomic_fetch_xor: 6097 case AtomicExpr::AO__atomic_fetch_nand: 6098 case AtomicExpr::AO__atomic_and_fetch: 6099 case AtomicExpr::AO__atomic_or_fetch: 6100 case AtomicExpr::AO__atomic_xor_fetch: 6101 case AtomicExpr::AO__atomic_nand_fetch: 6102 Form = Arithmetic; 6103 break; 6104 case AtomicExpr::AO__c11_atomic_fetch_min: 6105 case AtomicExpr::AO__c11_atomic_fetch_max: 6106 case AtomicExpr::AO__opencl_atomic_fetch_min: 6107 case AtomicExpr::AO__opencl_atomic_fetch_max: 6108 case AtomicExpr::AO__atomic_min_fetch: 6109 case AtomicExpr::AO__atomic_max_fetch: 6110 case AtomicExpr::AO__atomic_fetch_min: 6111 case AtomicExpr::AO__atomic_fetch_max: 6112 Form = Arithmetic; 6113 break; 6114 6115 case AtomicExpr::AO__c11_atomic_exchange: 6116 case AtomicExpr::AO__hip_atomic_exchange: 6117 case AtomicExpr::AO__opencl_atomic_exchange: 6118 case AtomicExpr::AO__atomic_exchange_n: 6119 Form = Xchg; 6120 break; 6121 6122 case AtomicExpr::AO__atomic_exchange: 6123 Form = GNUXchg; 6124 break; 6125 6126 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 6127 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 6128 case AtomicExpr::AO__hip_atomic_compare_exchange_strong: 6129 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 6130 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 6131 case AtomicExpr::AO__hip_atomic_compare_exchange_weak: 6132 Form = C11CmpXchg; 6133 break; 6134 6135 case AtomicExpr::AO__atomic_compare_exchange: 6136 case AtomicExpr::AO__atomic_compare_exchange_n: 6137 Form = GNUCmpXchg; 6138 break; 6139 } 6140 6141 unsigned AdjustedNumArgs = NumArgs[Form]; 6142 if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init) 6143 ++AdjustedNumArgs; 6144 // Check we have the right number of arguments. 6145 if (Args.size() < AdjustedNumArgs) { 6146 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 6147 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 6148 << ExprRange; 6149 return ExprError(); 6150 } else if (Args.size() > AdjustedNumArgs) { 6151 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 6152 diag::err_typecheck_call_too_many_args) 6153 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 6154 << ExprRange; 6155 return ExprError(); 6156 } 6157 6158 // Inspect the first argument of the atomic operation. 6159 Expr *Ptr = Args[0]; 6160 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 6161 if (ConvertedPtr.isInvalid()) 6162 return ExprError(); 6163 6164 Ptr = ConvertedPtr.get(); 6165 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 6166 if (!pointerType) { 6167 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 6168 << Ptr->getType() << Ptr->getSourceRange(); 6169 return ExprError(); 6170 } 6171 6172 // For a __c11 builtin, this should be a pointer to an _Atomic type. 6173 QualType AtomTy = pointerType->getPointeeType(); // 'A' 6174 QualType ValType = AtomTy; // 'C' 6175 if (IsC11) { 6176 if (!AtomTy->isAtomicType()) { 6177 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 6178 << Ptr->getType() << Ptr->getSourceRange(); 6179 return ExprError(); 6180 } 6181 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 6182 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 6183 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 6184 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 6185 << Ptr->getSourceRange(); 6186 return ExprError(); 6187 } 6188 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 6189 } else if (Form != Load && Form != LoadCopy) { 6190 if (ValType.isConstQualified()) { 6191 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 6192 << Ptr->getType() << Ptr->getSourceRange(); 6193 return ExprError(); 6194 } 6195 } 6196 6197 // For an arithmetic operation, the implied arithmetic must be well-formed. 6198 if (Form == Arithmetic) { 6199 // GCC does not enforce these rules for GNU atomics, but we do to help catch 6200 // trivial type errors. 6201 auto IsAllowedValueType = [&](QualType ValType) { 6202 if (ValType->isIntegerType()) 6203 return true; 6204 if (ValType->isPointerType()) 6205 return true; 6206 if (!ValType->isFloatingType()) 6207 return false; 6208 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 6209 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 6210 &Context.getTargetInfo().getLongDoubleFormat() == 6211 &llvm::APFloat::x87DoubleExtended()) 6212 return false; 6213 return true; 6214 }; 6215 if (IsAddSub && !IsAllowedValueType(ValType)) { 6216 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 6217 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 6218 return ExprError(); 6219 } 6220 if (!IsAddSub && !ValType->isIntegerType()) { 6221 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 6222 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 6223 return ExprError(); 6224 } 6225 if (IsC11 && ValType->isPointerType() && 6226 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 6227 diag::err_incomplete_type)) { 6228 return ExprError(); 6229 } 6230 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 6231 // For __atomic_*_n operations, the value type must be a scalar integral or 6232 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 6233 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 6234 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 6235 return ExprError(); 6236 } 6237 6238 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 6239 !AtomTy->isScalarType()) { 6240 // For GNU atomics, require a trivially-copyable type. This is not part of 6241 // the GNU atomics specification but we enforce it for consistency with 6242 // other atomics which generally all require a trivially-copyable type. This 6243 // is because atomics just copy bits. 6244 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 6245 << Ptr->getType() << Ptr->getSourceRange(); 6246 return ExprError(); 6247 } 6248 6249 switch (ValType.getObjCLifetime()) { 6250 case Qualifiers::OCL_None: 6251 case Qualifiers::OCL_ExplicitNone: 6252 // okay 6253 break; 6254 6255 case Qualifiers::OCL_Weak: 6256 case Qualifiers::OCL_Strong: 6257 case Qualifiers::OCL_Autoreleasing: 6258 // FIXME: Can this happen? By this point, ValType should be known 6259 // to be trivially copyable. 6260 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 6261 << ValType << Ptr->getSourceRange(); 6262 return ExprError(); 6263 } 6264 6265 // All atomic operations have an overload which takes a pointer to a volatile 6266 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 6267 // into the result or the other operands. Similarly atomic_load takes a 6268 // pointer to a const 'A'. 6269 ValType.removeLocalVolatile(); 6270 ValType.removeLocalConst(); 6271 QualType ResultType = ValType; 6272 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 6273 Form == Init) 6274 ResultType = Context.VoidTy; 6275 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 6276 ResultType = Context.BoolTy; 6277 6278 // The type of a parameter passed 'by value'. In the GNU atomics, such 6279 // arguments are actually passed as pointers. 6280 QualType ByValType = ValType; // 'CP' 6281 bool IsPassedByAddress = false; 6282 if (!IsC11 && !IsHIP && !IsN) { 6283 ByValType = Ptr->getType(); 6284 IsPassedByAddress = true; 6285 } 6286 6287 SmallVector<Expr *, 5> APIOrderedArgs; 6288 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 6289 APIOrderedArgs.push_back(Args[0]); 6290 switch (Form) { 6291 case Init: 6292 case Load: 6293 APIOrderedArgs.push_back(Args[1]); // Val1/Order 6294 break; 6295 case LoadCopy: 6296 case Copy: 6297 case Arithmetic: 6298 case Xchg: 6299 APIOrderedArgs.push_back(Args[2]); // Val1 6300 APIOrderedArgs.push_back(Args[1]); // Order 6301 break; 6302 case GNUXchg: 6303 APIOrderedArgs.push_back(Args[2]); // Val1 6304 APIOrderedArgs.push_back(Args[3]); // Val2 6305 APIOrderedArgs.push_back(Args[1]); // Order 6306 break; 6307 case C11CmpXchg: 6308 APIOrderedArgs.push_back(Args[2]); // Val1 6309 APIOrderedArgs.push_back(Args[4]); // Val2 6310 APIOrderedArgs.push_back(Args[1]); // Order 6311 APIOrderedArgs.push_back(Args[3]); // OrderFail 6312 break; 6313 case GNUCmpXchg: 6314 APIOrderedArgs.push_back(Args[2]); // Val1 6315 APIOrderedArgs.push_back(Args[4]); // Val2 6316 APIOrderedArgs.push_back(Args[5]); // Weak 6317 APIOrderedArgs.push_back(Args[1]); // Order 6318 APIOrderedArgs.push_back(Args[3]); // OrderFail 6319 break; 6320 } 6321 } else 6322 APIOrderedArgs.append(Args.begin(), Args.end()); 6323 6324 // The first argument's non-CV pointer type is used to deduce the type of 6325 // subsequent arguments, except for: 6326 // - weak flag (always converted to bool) 6327 // - memory order (always converted to int) 6328 // - scope (always converted to int) 6329 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 6330 QualType Ty; 6331 if (i < NumVals[Form] + 1) { 6332 switch (i) { 6333 case 0: 6334 // The first argument is always a pointer. It has a fixed type. 6335 // It is always dereferenced, a nullptr is undefined. 6336 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 6337 // Nothing else to do: we already know all we want about this pointer. 6338 continue; 6339 case 1: 6340 // The second argument is the non-atomic operand. For arithmetic, this 6341 // is always passed by value, and for a compare_exchange it is always 6342 // passed by address. For the rest, GNU uses by-address and C11 uses 6343 // by-value. 6344 assert(Form != Load); 6345 if (Form == Arithmetic && ValType->isPointerType()) 6346 Ty = Context.getPointerDiffType(); 6347 else if (Form == Init || Form == Arithmetic) 6348 Ty = ValType; 6349 else if (Form == Copy || Form == Xchg) { 6350 if (IsPassedByAddress) { 6351 // The value pointer is always dereferenced, a nullptr is undefined. 6352 CheckNonNullArgument(*this, APIOrderedArgs[i], 6353 ExprRange.getBegin()); 6354 } 6355 Ty = ByValType; 6356 } else { 6357 Expr *ValArg = APIOrderedArgs[i]; 6358 // The value pointer is always dereferenced, a nullptr is undefined. 6359 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 6360 LangAS AS = LangAS::Default; 6361 // Keep address space of non-atomic pointer type. 6362 if (const PointerType *PtrTy = 6363 ValArg->getType()->getAs<PointerType>()) { 6364 AS = PtrTy->getPointeeType().getAddressSpace(); 6365 } 6366 Ty = Context.getPointerType( 6367 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 6368 } 6369 break; 6370 case 2: 6371 // The third argument to compare_exchange / GNU exchange is the desired 6372 // value, either by-value (for the C11 and *_n variant) or as a pointer. 6373 if (IsPassedByAddress) 6374 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 6375 Ty = ByValType; 6376 break; 6377 case 3: 6378 // The fourth argument to GNU compare_exchange is a 'weak' flag. 6379 Ty = Context.BoolTy; 6380 break; 6381 } 6382 } else { 6383 // The order(s) and scope are always converted to int. 6384 Ty = Context.IntTy; 6385 } 6386 6387 InitializedEntity Entity = 6388 InitializedEntity::InitializeParameter(Context, Ty, false); 6389 ExprResult Arg = APIOrderedArgs[i]; 6390 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6391 if (Arg.isInvalid()) 6392 return true; 6393 APIOrderedArgs[i] = Arg.get(); 6394 } 6395 6396 // Permute the arguments into a 'consistent' order. 6397 SmallVector<Expr*, 5> SubExprs; 6398 SubExprs.push_back(Ptr); 6399 switch (Form) { 6400 case Init: 6401 // Note, AtomicExpr::getVal1() has a special case for this atomic. 6402 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6403 break; 6404 case Load: 6405 SubExprs.push_back(APIOrderedArgs[1]); // Order 6406 break; 6407 case LoadCopy: 6408 case Copy: 6409 case Arithmetic: 6410 case Xchg: 6411 SubExprs.push_back(APIOrderedArgs[2]); // Order 6412 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6413 break; 6414 case GNUXchg: 6415 // Note, AtomicExpr::getVal2() has a special case for this atomic. 6416 SubExprs.push_back(APIOrderedArgs[3]); // Order 6417 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6418 SubExprs.push_back(APIOrderedArgs[2]); // Val2 6419 break; 6420 case C11CmpXchg: 6421 SubExprs.push_back(APIOrderedArgs[3]); // Order 6422 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6423 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 6424 SubExprs.push_back(APIOrderedArgs[2]); // Val2 6425 break; 6426 case GNUCmpXchg: 6427 SubExprs.push_back(APIOrderedArgs[4]); // Order 6428 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6429 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 6430 SubExprs.push_back(APIOrderedArgs[2]); // Val2 6431 SubExprs.push_back(APIOrderedArgs[3]); // Weak 6432 break; 6433 } 6434 6435 if (SubExprs.size() >= 2 && Form != Init) { 6436 if (Optional<llvm::APSInt> Result = 6437 SubExprs[1]->getIntegerConstantExpr(Context)) 6438 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 6439 Diag(SubExprs[1]->getBeginLoc(), 6440 diag::warn_atomic_op_has_invalid_memory_order) 6441 << SubExprs[1]->getSourceRange(); 6442 } 6443 6444 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 6445 auto *Scope = Args[Args.size() - 1]; 6446 if (Optional<llvm::APSInt> Result = 6447 Scope->getIntegerConstantExpr(Context)) { 6448 if (!ScopeModel->isValid(Result->getZExtValue())) 6449 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 6450 << Scope->getSourceRange(); 6451 } 6452 SubExprs.push_back(Scope); 6453 } 6454 6455 AtomicExpr *AE = new (Context) 6456 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 6457 6458 if ((Op == AtomicExpr::AO__c11_atomic_load || 6459 Op == AtomicExpr::AO__c11_atomic_store || 6460 Op == AtomicExpr::AO__opencl_atomic_load || 6461 Op == AtomicExpr::AO__hip_atomic_load || 6462 Op == AtomicExpr::AO__opencl_atomic_store || 6463 Op == AtomicExpr::AO__hip_atomic_store) && 6464 Context.AtomicUsesUnsupportedLibcall(AE)) 6465 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 6466 << ((Op == AtomicExpr::AO__c11_atomic_load || 6467 Op == AtomicExpr::AO__opencl_atomic_load || 6468 Op == AtomicExpr::AO__hip_atomic_load) 6469 ? 0 6470 : 1); 6471 6472 if (ValType->isBitIntType()) { 6473 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit); 6474 return ExprError(); 6475 } 6476 6477 return AE; 6478 } 6479 6480 /// checkBuiltinArgument - Given a call to a builtin function, perform 6481 /// normal type-checking on the given argument, updating the call in 6482 /// place. This is useful when a builtin function requires custom 6483 /// type-checking for some of its arguments but not necessarily all of 6484 /// them. 6485 /// 6486 /// Returns true on error. 6487 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 6488 FunctionDecl *Fn = E->getDirectCallee(); 6489 assert(Fn && "builtin call without direct callee!"); 6490 6491 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 6492 InitializedEntity Entity = 6493 InitializedEntity::InitializeParameter(S.Context, Param); 6494 6495 ExprResult Arg = E->getArg(ArgIndex); 6496 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 6497 if (Arg.isInvalid()) 6498 return true; 6499 6500 E->setArg(ArgIndex, Arg.get()); 6501 return false; 6502 } 6503 6504 /// We have a call to a function like __sync_fetch_and_add, which is an 6505 /// overloaded function based on the pointer type of its first argument. 6506 /// The main BuildCallExpr routines have already promoted the types of 6507 /// arguments because all of these calls are prototyped as void(...). 6508 /// 6509 /// This function goes through and does final semantic checking for these 6510 /// builtins, as well as generating any warnings. 6511 ExprResult 6512 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 6513 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 6514 Expr *Callee = TheCall->getCallee(); 6515 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 6516 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6517 6518 // Ensure that we have at least one argument to do type inference from. 6519 if (TheCall->getNumArgs() < 1) { 6520 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6521 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 6522 return ExprError(); 6523 } 6524 6525 // Inspect the first argument of the atomic builtin. This should always be 6526 // a pointer type, whose element is an integral scalar or pointer type. 6527 // Because it is a pointer type, we don't have to worry about any implicit 6528 // casts here. 6529 // FIXME: We don't allow floating point scalars as input. 6530 Expr *FirstArg = TheCall->getArg(0); 6531 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 6532 if (FirstArgResult.isInvalid()) 6533 return ExprError(); 6534 FirstArg = FirstArgResult.get(); 6535 TheCall->setArg(0, FirstArg); 6536 6537 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 6538 if (!pointerType) { 6539 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 6540 << FirstArg->getType() << FirstArg->getSourceRange(); 6541 return ExprError(); 6542 } 6543 6544 QualType ValType = pointerType->getPointeeType(); 6545 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6546 !ValType->isBlockPointerType()) { 6547 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 6548 << FirstArg->getType() << FirstArg->getSourceRange(); 6549 return ExprError(); 6550 } 6551 6552 if (ValType.isConstQualified()) { 6553 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 6554 << FirstArg->getType() << FirstArg->getSourceRange(); 6555 return ExprError(); 6556 } 6557 6558 switch (ValType.getObjCLifetime()) { 6559 case Qualifiers::OCL_None: 6560 case Qualifiers::OCL_ExplicitNone: 6561 // okay 6562 break; 6563 6564 case Qualifiers::OCL_Weak: 6565 case Qualifiers::OCL_Strong: 6566 case Qualifiers::OCL_Autoreleasing: 6567 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 6568 << ValType << FirstArg->getSourceRange(); 6569 return ExprError(); 6570 } 6571 6572 // Strip any qualifiers off ValType. 6573 ValType = ValType.getUnqualifiedType(); 6574 6575 // The majority of builtins return a value, but a few have special return 6576 // types, so allow them to override appropriately below. 6577 QualType ResultType = ValType; 6578 6579 // We need to figure out which concrete builtin this maps onto. For example, 6580 // __sync_fetch_and_add with a 2 byte object turns into 6581 // __sync_fetch_and_add_2. 6582 #define BUILTIN_ROW(x) \ 6583 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 6584 Builtin::BI##x##_8, Builtin::BI##x##_16 } 6585 6586 static const unsigned BuiltinIndices[][5] = { 6587 BUILTIN_ROW(__sync_fetch_and_add), 6588 BUILTIN_ROW(__sync_fetch_and_sub), 6589 BUILTIN_ROW(__sync_fetch_and_or), 6590 BUILTIN_ROW(__sync_fetch_and_and), 6591 BUILTIN_ROW(__sync_fetch_and_xor), 6592 BUILTIN_ROW(__sync_fetch_and_nand), 6593 6594 BUILTIN_ROW(__sync_add_and_fetch), 6595 BUILTIN_ROW(__sync_sub_and_fetch), 6596 BUILTIN_ROW(__sync_and_and_fetch), 6597 BUILTIN_ROW(__sync_or_and_fetch), 6598 BUILTIN_ROW(__sync_xor_and_fetch), 6599 BUILTIN_ROW(__sync_nand_and_fetch), 6600 6601 BUILTIN_ROW(__sync_val_compare_and_swap), 6602 BUILTIN_ROW(__sync_bool_compare_and_swap), 6603 BUILTIN_ROW(__sync_lock_test_and_set), 6604 BUILTIN_ROW(__sync_lock_release), 6605 BUILTIN_ROW(__sync_swap) 6606 }; 6607 #undef BUILTIN_ROW 6608 6609 // Determine the index of the size. 6610 unsigned SizeIndex; 6611 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 6612 case 1: SizeIndex = 0; break; 6613 case 2: SizeIndex = 1; break; 6614 case 4: SizeIndex = 2; break; 6615 case 8: SizeIndex = 3; break; 6616 case 16: SizeIndex = 4; break; 6617 default: 6618 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 6619 << FirstArg->getType() << FirstArg->getSourceRange(); 6620 return ExprError(); 6621 } 6622 6623 // Each of these builtins has one pointer argument, followed by some number of 6624 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 6625 // that we ignore. Find out which row of BuiltinIndices to read from as well 6626 // as the number of fixed args. 6627 unsigned BuiltinID = FDecl->getBuiltinID(); 6628 unsigned BuiltinIndex, NumFixed = 1; 6629 bool WarnAboutSemanticsChange = false; 6630 switch (BuiltinID) { 6631 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 6632 case Builtin::BI__sync_fetch_and_add: 6633 case Builtin::BI__sync_fetch_and_add_1: 6634 case Builtin::BI__sync_fetch_and_add_2: 6635 case Builtin::BI__sync_fetch_and_add_4: 6636 case Builtin::BI__sync_fetch_and_add_8: 6637 case Builtin::BI__sync_fetch_and_add_16: 6638 BuiltinIndex = 0; 6639 break; 6640 6641 case Builtin::BI__sync_fetch_and_sub: 6642 case Builtin::BI__sync_fetch_and_sub_1: 6643 case Builtin::BI__sync_fetch_and_sub_2: 6644 case Builtin::BI__sync_fetch_and_sub_4: 6645 case Builtin::BI__sync_fetch_and_sub_8: 6646 case Builtin::BI__sync_fetch_and_sub_16: 6647 BuiltinIndex = 1; 6648 break; 6649 6650 case Builtin::BI__sync_fetch_and_or: 6651 case Builtin::BI__sync_fetch_and_or_1: 6652 case Builtin::BI__sync_fetch_and_or_2: 6653 case Builtin::BI__sync_fetch_and_or_4: 6654 case Builtin::BI__sync_fetch_and_or_8: 6655 case Builtin::BI__sync_fetch_and_or_16: 6656 BuiltinIndex = 2; 6657 break; 6658 6659 case Builtin::BI__sync_fetch_and_and: 6660 case Builtin::BI__sync_fetch_and_and_1: 6661 case Builtin::BI__sync_fetch_and_and_2: 6662 case Builtin::BI__sync_fetch_and_and_4: 6663 case Builtin::BI__sync_fetch_and_and_8: 6664 case Builtin::BI__sync_fetch_and_and_16: 6665 BuiltinIndex = 3; 6666 break; 6667 6668 case Builtin::BI__sync_fetch_and_xor: 6669 case Builtin::BI__sync_fetch_and_xor_1: 6670 case Builtin::BI__sync_fetch_and_xor_2: 6671 case Builtin::BI__sync_fetch_and_xor_4: 6672 case Builtin::BI__sync_fetch_and_xor_8: 6673 case Builtin::BI__sync_fetch_and_xor_16: 6674 BuiltinIndex = 4; 6675 break; 6676 6677 case Builtin::BI__sync_fetch_and_nand: 6678 case Builtin::BI__sync_fetch_and_nand_1: 6679 case Builtin::BI__sync_fetch_and_nand_2: 6680 case Builtin::BI__sync_fetch_and_nand_4: 6681 case Builtin::BI__sync_fetch_and_nand_8: 6682 case Builtin::BI__sync_fetch_and_nand_16: 6683 BuiltinIndex = 5; 6684 WarnAboutSemanticsChange = true; 6685 break; 6686 6687 case Builtin::BI__sync_add_and_fetch: 6688 case Builtin::BI__sync_add_and_fetch_1: 6689 case Builtin::BI__sync_add_and_fetch_2: 6690 case Builtin::BI__sync_add_and_fetch_4: 6691 case Builtin::BI__sync_add_and_fetch_8: 6692 case Builtin::BI__sync_add_and_fetch_16: 6693 BuiltinIndex = 6; 6694 break; 6695 6696 case Builtin::BI__sync_sub_and_fetch: 6697 case Builtin::BI__sync_sub_and_fetch_1: 6698 case Builtin::BI__sync_sub_and_fetch_2: 6699 case Builtin::BI__sync_sub_and_fetch_4: 6700 case Builtin::BI__sync_sub_and_fetch_8: 6701 case Builtin::BI__sync_sub_and_fetch_16: 6702 BuiltinIndex = 7; 6703 break; 6704 6705 case Builtin::BI__sync_and_and_fetch: 6706 case Builtin::BI__sync_and_and_fetch_1: 6707 case Builtin::BI__sync_and_and_fetch_2: 6708 case Builtin::BI__sync_and_and_fetch_4: 6709 case Builtin::BI__sync_and_and_fetch_8: 6710 case Builtin::BI__sync_and_and_fetch_16: 6711 BuiltinIndex = 8; 6712 break; 6713 6714 case Builtin::BI__sync_or_and_fetch: 6715 case Builtin::BI__sync_or_and_fetch_1: 6716 case Builtin::BI__sync_or_and_fetch_2: 6717 case Builtin::BI__sync_or_and_fetch_4: 6718 case Builtin::BI__sync_or_and_fetch_8: 6719 case Builtin::BI__sync_or_and_fetch_16: 6720 BuiltinIndex = 9; 6721 break; 6722 6723 case Builtin::BI__sync_xor_and_fetch: 6724 case Builtin::BI__sync_xor_and_fetch_1: 6725 case Builtin::BI__sync_xor_and_fetch_2: 6726 case Builtin::BI__sync_xor_and_fetch_4: 6727 case Builtin::BI__sync_xor_and_fetch_8: 6728 case Builtin::BI__sync_xor_and_fetch_16: 6729 BuiltinIndex = 10; 6730 break; 6731 6732 case Builtin::BI__sync_nand_and_fetch: 6733 case Builtin::BI__sync_nand_and_fetch_1: 6734 case Builtin::BI__sync_nand_and_fetch_2: 6735 case Builtin::BI__sync_nand_and_fetch_4: 6736 case Builtin::BI__sync_nand_and_fetch_8: 6737 case Builtin::BI__sync_nand_and_fetch_16: 6738 BuiltinIndex = 11; 6739 WarnAboutSemanticsChange = true; 6740 break; 6741 6742 case Builtin::BI__sync_val_compare_and_swap: 6743 case Builtin::BI__sync_val_compare_and_swap_1: 6744 case Builtin::BI__sync_val_compare_and_swap_2: 6745 case Builtin::BI__sync_val_compare_and_swap_4: 6746 case Builtin::BI__sync_val_compare_and_swap_8: 6747 case Builtin::BI__sync_val_compare_and_swap_16: 6748 BuiltinIndex = 12; 6749 NumFixed = 2; 6750 break; 6751 6752 case Builtin::BI__sync_bool_compare_and_swap: 6753 case Builtin::BI__sync_bool_compare_and_swap_1: 6754 case Builtin::BI__sync_bool_compare_and_swap_2: 6755 case Builtin::BI__sync_bool_compare_and_swap_4: 6756 case Builtin::BI__sync_bool_compare_and_swap_8: 6757 case Builtin::BI__sync_bool_compare_and_swap_16: 6758 BuiltinIndex = 13; 6759 NumFixed = 2; 6760 ResultType = Context.BoolTy; 6761 break; 6762 6763 case Builtin::BI__sync_lock_test_and_set: 6764 case Builtin::BI__sync_lock_test_and_set_1: 6765 case Builtin::BI__sync_lock_test_and_set_2: 6766 case Builtin::BI__sync_lock_test_and_set_4: 6767 case Builtin::BI__sync_lock_test_and_set_8: 6768 case Builtin::BI__sync_lock_test_and_set_16: 6769 BuiltinIndex = 14; 6770 break; 6771 6772 case Builtin::BI__sync_lock_release: 6773 case Builtin::BI__sync_lock_release_1: 6774 case Builtin::BI__sync_lock_release_2: 6775 case Builtin::BI__sync_lock_release_4: 6776 case Builtin::BI__sync_lock_release_8: 6777 case Builtin::BI__sync_lock_release_16: 6778 BuiltinIndex = 15; 6779 NumFixed = 0; 6780 ResultType = Context.VoidTy; 6781 break; 6782 6783 case Builtin::BI__sync_swap: 6784 case Builtin::BI__sync_swap_1: 6785 case Builtin::BI__sync_swap_2: 6786 case Builtin::BI__sync_swap_4: 6787 case Builtin::BI__sync_swap_8: 6788 case Builtin::BI__sync_swap_16: 6789 BuiltinIndex = 16; 6790 break; 6791 } 6792 6793 // Now that we know how many fixed arguments we expect, first check that we 6794 // have at least that many. 6795 if (TheCall->getNumArgs() < 1+NumFixed) { 6796 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6797 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6798 << Callee->getSourceRange(); 6799 return ExprError(); 6800 } 6801 6802 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6803 << Callee->getSourceRange(); 6804 6805 if (WarnAboutSemanticsChange) { 6806 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6807 << Callee->getSourceRange(); 6808 } 6809 6810 // Get the decl for the concrete builtin from this, we can tell what the 6811 // concrete integer type we should convert to is. 6812 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6813 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6814 FunctionDecl *NewBuiltinDecl; 6815 if (NewBuiltinID == BuiltinID) 6816 NewBuiltinDecl = FDecl; 6817 else { 6818 // Perform builtin lookup to avoid redeclaring it. 6819 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6820 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6821 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6822 assert(Res.getFoundDecl()); 6823 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6824 if (!NewBuiltinDecl) 6825 return ExprError(); 6826 } 6827 6828 // The first argument --- the pointer --- has a fixed type; we 6829 // deduce the types of the rest of the arguments accordingly. Walk 6830 // the remaining arguments, converting them to the deduced value type. 6831 for (unsigned i = 0; i != NumFixed; ++i) { 6832 ExprResult Arg = TheCall->getArg(i+1); 6833 6834 // GCC does an implicit conversion to the pointer or integer ValType. This 6835 // can fail in some cases (1i -> int**), check for this error case now. 6836 // Initialize the argument. 6837 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6838 ValType, /*consume*/ false); 6839 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6840 if (Arg.isInvalid()) 6841 return ExprError(); 6842 6843 // Okay, we have something that *can* be converted to the right type. Check 6844 // to see if there is a potentially weird extension going on here. This can 6845 // happen when you do an atomic operation on something like an char* and 6846 // pass in 42. The 42 gets converted to char. This is even more strange 6847 // for things like 45.123 -> char, etc. 6848 // FIXME: Do this check. 6849 TheCall->setArg(i+1, Arg.get()); 6850 } 6851 6852 // Create a new DeclRefExpr to refer to the new decl. 6853 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6854 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6855 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6856 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6857 6858 // Set the callee in the CallExpr. 6859 // FIXME: This loses syntactic information. 6860 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6861 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6862 CK_BuiltinFnToFnPtr); 6863 TheCall->setCallee(PromotedCall.get()); 6864 6865 // Change the result type of the call to match the original value type. This 6866 // is arbitrary, but the codegen for these builtins ins design to handle it 6867 // gracefully. 6868 TheCall->setType(ResultType); 6869 6870 // Prohibit problematic uses of bit-precise integer types with atomic 6871 // builtins. The arguments would have already been converted to the first 6872 // argument's type, so only need to check the first argument. 6873 const auto *BitIntValType = ValType->getAs<BitIntType>(); 6874 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) { 6875 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6876 return ExprError(); 6877 } 6878 6879 return TheCallResult; 6880 } 6881 6882 /// SemaBuiltinNontemporalOverloaded - We have a call to 6883 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6884 /// overloaded function based on the pointer type of its last argument. 6885 /// 6886 /// This function goes through and does final semantic checking for these 6887 /// builtins. 6888 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6889 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6890 DeclRefExpr *DRE = 6891 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6892 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6893 unsigned BuiltinID = FDecl->getBuiltinID(); 6894 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6895 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6896 "Unexpected nontemporal load/store builtin!"); 6897 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6898 unsigned numArgs = isStore ? 2 : 1; 6899 6900 // Ensure that we have the proper number of arguments. 6901 if (checkArgCount(*this, TheCall, numArgs)) 6902 return ExprError(); 6903 6904 // Inspect the last argument of the nontemporal builtin. This should always 6905 // be a pointer type, from which we imply the type of the memory access. 6906 // Because it is a pointer type, we don't have to worry about any implicit 6907 // casts here. 6908 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6909 ExprResult PointerArgResult = 6910 DefaultFunctionArrayLvalueConversion(PointerArg); 6911 6912 if (PointerArgResult.isInvalid()) 6913 return ExprError(); 6914 PointerArg = PointerArgResult.get(); 6915 TheCall->setArg(numArgs - 1, PointerArg); 6916 6917 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6918 if (!pointerType) { 6919 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6920 << PointerArg->getType() << PointerArg->getSourceRange(); 6921 return ExprError(); 6922 } 6923 6924 QualType ValType = pointerType->getPointeeType(); 6925 6926 // Strip any qualifiers off ValType. 6927 ValType = ValType.getUnqualifiedType(); 6928 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6929 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6930 !ValType->isVectorType()) { 6931 Diag(DRE->getBeginLoc(), 6932 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6933 << PointerArg->getType() << PointerArg->getSourceRange(); 6934 return ExprError(); 6935 } 6936 6937 if (!isStore) { 6938 TheCall->setType(ValType); 6939 return TheCallResult; 6940 } 6941 6942 ExprResult ValArg = TheCall->getArg(0); 6943 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6944 Context, ValType, /*consume*/ false); 6945 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6946 if (ValArg.isInvalid()) 6947 return ExprError(); 6948 6949 TheCall->setArg(0, ValArg.get()); 6950 TheCall->setType(Context.VoidTy); 6951 return TheCallResult; 6952 } 6953 6954 /// CheckObjCString - Checks that the argument to the builtin 6955 /// CFString constructor is correct 6956 /// Note: It might also make sense to do the UTF-16 conversion here (would 6957 /// simplify the backend). 6958 bool Sema::CheckObjCString(Expr *Arg) { 6959 Arg = Arg->IgnoreParenCasts(); 6960 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6961 6962 if (!Literal || !Literal->isAscii()) { 6963 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6964 << Arg->getSourceRange(); 6965 return true; 6966 } 6967 6968 if (Literal->containsNonAsciiOrNull()) { 6969 StringRef String = Literal->getString(); 6970 unsigned NumBytes = String.size(); 6971 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6972 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6973 llvm::UTF16 *ToPtr = &ToBuf[0]; 6974 6975 llvm::ConversionResult Result = 6976 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6977 ToPtr + NumBytes, llvm::strictConversion); 6978 // Check for conversion failure. 6979 if (Result != llvm::conversionOK) 6980 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6981 << Arg->getSourceRange(); 6982 } 6983 return false; 6984 } 6985 6986 /// CheckObjCString - Checks that the format string argument to the os_log() 6987 /// and os_trace() functions is correct, and converts it to const char *. 6988 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6989 Arg = Arg->IgnoreParenCasts(); 6990 auto *Literal = dyn_cast<StringLiteral>(Arg); 6991 if (!Literal) { 6992 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6993 Literal = ObjcLiteral->getString(); 6994 } 6995 } 6996 6997 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6998 return ExprError( 6999 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 7000 << Arg->getSourceRange()); 7001 } 7002 7003 ExprResult Result(Literal); 7004 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 7005 InitializedEntity Entity = 7006 InitializedEntity::InitializeParameter(Context, ResultTy, false); 7007 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 7008 return Result; 7009 } 7010 7011 /// Check that the user is calling the appropriate va_start builtin for the 7012 /// target and calling convention. 7013 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 7014 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 7015 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 7016 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 7017 TT.getArch() == llvm::Triple::aarch64_32); 7018 bool IsWindows = TT.isOSWindows(); 7019 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 7020 if (IsX64 || IsAArch64) { 7021 CallingConv CC = CC_C; 7022 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 7023 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 7024 if (IsMSVAStart) { 7025 // Don't allow this in System V ABI functions. 7026 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 7027 return S.Diag(Fn->getBeginLoc(), 7028 diag::err_ms_va_start_used_in_sysv_function); 7029 } else { 7030 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 7031 // On x64 Windows, don't allow this in System V ABI functions. 7032 // (Yes, that means there's no corresponding way to support variadic 7033 // System V ABI functions on Windows.) 7034 if ((IsWindows && CC == CC_X86_64SysV) || 7035 (!IsWindows && CC == CC_Win64)) 7036 return S.Diag(Fn->getBeginLoc(), 7037 diag::err_va_start_used_in_wrong_abi_function) 7038 << !IsWindows; 7039 } 7040 return false; 7041 } 7042 7043 if (IsMSVAStart) 7044 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 7045 return false; 7046 } 7047 7048 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 7049 ParmVarDecl **LastParam = nullptr) { 7050 // Determine whether the current function, block, or obj-c method is variadic 7051 // and get its parameter list. 7052 bool IsVariadic = false; 7053 ArrayRef<ParmVarDecl *> Params; 7054 DeclContext *Caller = S.CurContext; 7055 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 7056 IsVariadic = Block->isVariadic(); 7057 Params = Block->parameters(); 7058 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 7059 IsVariadic = FD->isVariadic(); 7060 Params = FD->parameters(); 7061 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 7062 IsVariadic = MD->isVariadic(); 7063 // FIXME: This isn't correct for methods (results in bogus warning). 7064 Params = MD->parameters(); 7065 } else if (isa<CapturedDecl>(Caller)) { 7066 // We don't support va_start in a CapturedDecl. 7067 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 7068 return true; 7069 } else { 7070 // This must be some other declcontext that parses exprs. 7071 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 7072 return true; 7073 } 7074 7075 if (!IsVariadic) { 7076 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 7077 return true; 7078 } 7079 7080 if (LastParam) 7081 *LastParam = Params.empty() ? nullptr : Params.back(); 7082 7083 return false; 7084 } 7085 7086 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 7087 /// for validity. Emit an error and return true on failure; return false 7088 /// on success. 7089 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 7090 Expr *Fn = TheCall->getCallee(); 7091 7092 if (checkVAStartABI(*this, BuiltinID, Fn)) 7093 return true; 7094 7095 if (checkArgCount(*this, TheCall, 2)) 7096 return true; 7097 7098 // Type-check the first argument normally. 7099 if (checkBuiltinArgument(*this, TheCall, 0)) 7100 return true; 7101 7102 // Check that the current function is variadic, and get its last parameter. 7103 ParmVarDecl *LastParam; 7104 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 7105 return true; 7106 7107 // Verify that the second argument to the builtin is the last argument of the 7108 // current function or method. 7109 bool SecondArgIsLastNamedArgument = false; 7110 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 7111 7112 // These are valid if SecondArgIsLastNamedArgument is false after the next 7113 // block. 7114 QualType Type; 7115 SourceLocation ParamLoc; 7116 bool IsCRegister = false; 7117 7118 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 7119 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 7120 SecondArgIsLastNamedArgument = PV == LastParam; 7121 7122 Type = PV->getType(); 7123 ParamLoc = PV->getLocation(); 7124 IsCRegister = 7125 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 7126 } 7127 } 7128 7129 if (!SecondArgIsLastNamedArgument) 7130 Diag(TheCall->getArg(1)->getBeginLoc(), 7131 diag::warn_second_arg_of_va_start_not_last_named_param); 7132 else if (IsCRegister || Type->isReferenceType() || 7133 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 7134 // Promotable integers are UB, but enumerations need a bit of 7135 // extra checking to see what their promotable type actually is. 7136 if (!Type->isPromotableIntegerType()) 7137 return false; 7138 if (!Type->isEnumeralType()) 7139 return true; 7140 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 7141 return !(ED && 7142 Context.typesAreCompatible(ED->getPromotionType(), Type)); 7143 }()) { 7144 unsigned Reason = 0; 7145 if (Type->isReferenceType()) Reason = 1; 7146 else if (IsCRegister) Reason = 2; 7147 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 7148 Diag(ParamLoc, diag::note_parameter_type) << Type; 7149 } 7150 7151 TheCall->setType(Context.VoidTy); 7152 return false; 7153 } 7154 7155 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 7156 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 7157 const LangOptions &LO = getLangOpts(); 7158 7159 if (LO.CPlusPlus) 7160 return Arg->getType() 7161 .getCanonicalType() 7162 .getTypePtr() 7163 ->getPointeeType() 7164 .withoutLocalFastQualifiers() == Context.CharTy; 7165 7166 // In C, allow aliasing through `char *`, this is required for AArch64 at 7167 // least. 7168 return true; 7169 }; 7170 7171 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 7172 // const char *named_addr); 7173 7174 Expr *Func = Call->getCallee(); 7175 7176 if (Call->getNumArgs() < 3) 7177 return Diag(Call->getEndLoc(), 7178 diag::err_typecheck_call_too_few_args_at_least) 7179 << 0 /*function call*/ << 3 << Call->getNumArgs(); 7180 7181 // Type-check the first argument normally. 7182 if (checkBuiltinArgument(*this, Call, 0)) 7183 return true; 7184 7185 // Check that the current function is variadic. 7186 if (checkVAStartIsInVariadicFunction(*this, Func)) 7187 return true; 7188 7189 // __va_start on Windows does not validate the parameter qualifiers 7190 7191 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 7192 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 7193 7194 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 7195 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 7196 7197 const QualType &ConstCharPtrTy = 7198 Context.getPointerType(Context.CharTy.withConst()); 7199 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 7200 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 7201 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 7202 << 0 /* qualifier difference */ 7203 << 3 /* parameter mismatch */ 7204 << 2 << Arg1->getType() << ConstCharPtrTy; 7205 7206 const QualType SizeTy = Context.getSizeType(); 7207 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 7208 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 7209 << Arg2->getType() << SizeTy << 1 /* different class */ 7210 << 0 /* qualifier difference */ 7211 << 3 /* parameter mismatch */ 7212 << 3 << Arg2->getType() << SizeTy; 7213 7214 return false; 7215 } 7216 7217 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 7218 /// friends. This is declared to take (...), so we have to check everything. 7219 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 7220 if (checkArgCount(*this, TheCall, 2)) 7221 return true; 7222 7223 ExprResult OrigArg0 = TheCall->getArg(0); 7224 ExprResult OrigArg1 = TheCall->getArg(1); 7225 7226 // Do standard promotions between the two arguments, returning their common 7227 // type. 7228 QualType Res = UsualArithmeticConversions( 7229 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 7230 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 7231 return true; 7232 7233 // Make sure any conversions are pushed back into the call; this is 7234 // type safe since unordered compare builtins are declared as "_Bool 7235 // foo(...)". 7236 TheCall->setArg(0, OrigArg0.get()); 7237 TheCall->setArg(1, OrigArg1.get()); 7238 7239 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 7240 return false; 7241 7242 // If the common type isn't a real floating type, then the arguments were 7243 // invalid for this operation. 7244 if (Res.isNull() || !Res->isRealFloatingType()) 7245 return Diag(OrigArg0.get()->getBeginLoc(), 7246 diag::err_typecheck_call_invalid_ordered_compare) 7247 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 7248 << SourceRange(OrigArg0.get()->getBeginLoc(), 7249 OrigArg1.get()->getEndLoc()); 7250 7251 return false; 7252 } 7253 7254 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 7255 /// __builtin_isnan and friends. This is declared to take (...), so we have 7256 /// to check everything. We expect the last argument to be a floating point 7257 /// value. 7258 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 7259 if (checkArgCount(*this, TheCall, NumArgs)) 7260 return true; 7261 7262 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 7263 // on all preceding parameters just being int. Try all of those. 7264 for (unsigned i = 0; i < NumArgs - 1; ++i) { 7265 Expr *Arg = TheCall->getArg(i); 7266 7267 if (Arg->isTypeDependent()) 7268 return false; 7269 7270 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 7271 7272 if (Res.isInvalid()) 7273 return true; 7274 TheCall->setArg(i, Res.get()); 7275 } 7276 7277 Expr *OrigArg = TheCall->getArg(NumArgs-1); 7278 7279 if (OrigArg->isTypeDependent()) 7280 return false; 7281 7282 // Usual Unary Conversions will convert half to float, which we want for 7283 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 7284 // type how it is, but do normal L->Rvalue conversions. 7285 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 7286 OrigArg = UsualUnaryConversions(OrigArg).get(); 7287 else 7288 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 7289 TheCall->setArg(NumArgs - 1, OrigArg); 7290 7291 // This operation requires a non-_Complex floating-point number. 7292 if (!OrigArg->getType()->isRealFloatingType()) 7293 return Diag(OrigArg->getBeginLoc(), 7294 diag::err_typecheck_call_invalid_unary_fp) 7295 << OrigArg->getType() << OrigArg->getSourceRange(); 7296 7297 return false; 7298 } 7299 7300 /// Perform semantic analysis for a call to __builtin_complex. 7301 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 7302 if (checkArgCount(*this, TheCall, 2)) 7303 return true; 7304 7305 bool Dependent = false; 7306 for (unsigned I = 0; I != 2; ++I) { 7307 Expr *Arg = TheCall->getArg(I); 7308 QualType T = Arg->getType(); 7309 if (T->isDependentType()) { 7310 Dependent = true; 7311 continue; 7312 } 7313 7314 // Despite supporting _Complex int, GCC requires a real floating point type 7315 // for the operands of __builtin_complex. 7316 if (!T->isRealFloatingType()) { 7317 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 7318 << Arg->getType() << Arg->getSourceRange(); 7319 } 7320 7321 ExprResult Converted = DefaultLvalueConversion(Arg); 7322 if (Converted.isInvalid()) 7323 return true; 7324 TheCall->setArg(I, Converted.get()); 7325 } 7326 7327 if (Dependent) { 7328 TheCall->setType(Context.DependentTy); 7329 return false; 7330 } 7331 7332 Expr *Real = TheCall->getArg(0); 7333 Expr *Imag = TheCall->getArg(1); 7334 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 7335 return Diag(Real->getBeginLoc(), 7336 diag::err_typecheck_call_different_arg_types) 7337 << Real->getType() << Imag->getType() 7338 << Real->getSourceRange() << Imag->getSourceRange(); 7339 } 7340 7341 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 7342 // don't allow this builtin to form those types either. 7343 // FIXME: Should we allow these types? 7344 if (Real->getType()->isFloat16Type()) 7345 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 7346 << "_Float16"; 7347 if (Real->getType()->isHalfType()) 7348 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 7349 << "half"; 7350 7351 TheCall->setType(Context.getComplexType(Real->getType())); 7352 return false; 7353 } 7354 7355 // Customized Sema Checking for VSX builtins that have the following signature: 7356 // vector [...] builtinName(vector [...], vector [...], const int); 7357 // Which takes the same type of vectors (any legal vector type) for the first 7358 // two arguments and takes compile time constant for the third argument. 7359 // Example builtins are : 7360 // vector double vec_xxpermdi(vector double, vector double, int); 7361 // vector short vec_xxsldwi(vector short, vector short, int); 7362 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 7363 unsigned ExpectedNumArgs = 3; 7364 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 7365 return true; 7366 7367 // Check the third argument is a compile time constant 7368 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 7369 return Diag(TheCall->getBeginLoc(), 7370 diag::err_vsx_builtin_nonconstant_argument) 7371 << 3 /* argument index */ << TheCall->getDirectCallee() 7372 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 7373 TheCall->getArg(2)->getEndLoc()); 7374 7375 QualType Arg1Ty = TheCall->getArg(0)->getType(); 7376 QualType Arg2Ty = TheCall->getArg(1)->getType(); 7377 7378 // Check the type of argument 1 and argument 2 are vectors. 7379 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 7380 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 7381 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 7382 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 7383 << TheCall->getDirectCallee() 7384 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7385 TheCall->getArg(1)->getEndLoc()); 7386 } 7387 7388 // Check the first two arguments are the same type. 7389 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 7390 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 7391 << TheCall->getDirectCallee() 7392 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7393 TheCall->getArg(1)->getEndLoc()); 7394 } 7395 7396 // When default clang type checking is turned off and the customized type 7397 // checking is used, the returning type of the function must be explicitly 7398 // set. Otherwise it is _Bool by default. 7399 TheCall->setType(Arg1Ty); 7400 7401 return false; 7402 } 7403 7404 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 7405 // This is declared to take (...), so we have to check everything. 7406 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 7407 if (TheCall->getNumArgs() < 2) 7408 return ExprError(Diag(TheCall->getEndLoc(), 7409 diag::err_typecheck_call_too_few_args_at_least) 7410 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 7411 << TheCall->getSourceRange()); 7412 7413 // Determine which of the following types of shufflevector we're checking: 7414 // 1) unary, vector mask: (lhs, mask) 7415 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 7416 QualType resType = TheCall->getArg(0)->getType(); 7417 unsigned numElements = 0; 7418 7419 if (!TheCall->getArg(0)->isTypeDependent() && 7420 !TheCall->getArg(1)->isTypeDependent()) { 7421 QualType LHSType = TheCall->getArg(0)->getType(); 7422 QualType RHSType = TheCall->getArg(1)->getType(); 7423 7424 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 7425 return ExprError( 7426 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 7427 << TheCall->getDirectCallee() 7428 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7429 TheCall->getArg(1)->getEndLoc())); 7430 7431 numElements = LHSType->castAs<VectorType>()->getNumElements(); 7432 unsigned numResElements = TheCall->getNumArgs() - 2; 7433 7434 // Check to see if we have a call with 2 vector arguments, the unary shuffle 7435 // with mask. If so, verify that RHS is an integer vector type with the 7436 // same number of elts as lhs. 7437 if (TheCall->getNumArgs() == 2) { 7438 if (!RHSType->hasIntegerRepresentation() || 7439 RHSType->castAs<VectorType>()->getNumElements() != numElements) 7440 return ExprError(Diag(TheCall->getBeginLoc(), 7441 diag::err_vec_builtin_incompatible_vector) 7442 << TheCall->getDirectCallee() 7443 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 7444 TheCall->getArg(1)->getEndLoc())); 7445 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 7446 return ExprError(Diag(TheCall->getBeginLoc(), 7447 diag::err_vec_builtin_incompatible_vector) 7448 << TheCall->getDirectCallee() 7449 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7450 TheCall->getArg(1)->getEndLoc())); 7451 } else if (numElements != numResElements) { 7452 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 7453 resType = Context.getVectorType(eltType, numResElements, 7454 VectorType::GenericVector); 7455 } 7456 } 7457 7458 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 7459 if (TheCall->getArg(i)->isTypeDependent() || 7460 TheCall->getArg(i)->isValueDependent()) 7461 continue; 7462 7463 Optional<llvm::APSInt> Result; 7464 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 7465 return ExprError(Diag(TheCall->getBeginLoc(), 7466 diag::err_shufflevector_nonconstant_argument) 7467 << TheCall->getArg(i)->getSourceRange()); 7468 7469 // Allow -1 which will be translated to undef in the IR. 7470 if (Result->isSigned() && Result->isAllOnes()) 7471 continue; 7472 7473 if (Result->getActiveBits() > 64 || 7474 Result->getZExtValue() >= numElements * 2) 7475 return ExprError(Diag(TheCall->getBeginLoc(), 7476 diag::err_shufflevector_argument_too_large) 7477 << TheCall->getArg(i)->getSourceRange()); 7478 } 7479 7480 SmallVector<Expr*, 32> exprs; 7481 7482 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 7483 exprs.push_back(TheCall->getArg(i)); 7484 TheCall->setArg(i, nullptr); 7485 } 7486 7487 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 7488 TheCall->getCallee()->getBeginLoc(), 7489 TheCall->getRParenLoc()); 7490 } 7491 7492 /// SemaConvertVectorExpr - Handle __builtin_convertvector 7493 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 7494 SourceLocation BuiltinLoc, 7495 SourceLocation RParenLoc) { 7496 ExprValueKind VK = VK_PRValue; 7497 ExprObjectKind OK = OK_Ordinary; 7498 QualType DstTy = TInfo->getType(); 7499 QualType SrcTy = E->getType(); 7500 7501 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 7502 return ExprError(Diag(BuiltinLoc, 7503 diag::err_convertvector_non_vector) 7504 << E->getSourceRange()); 7505 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 7506 return ExprError(Diag(BuiltinLoc, 7507 diag::err_convertvector_non_vector_type)); 7508 7509 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 7510 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 7511 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 7512 if (SrcElts != DstElts) 7513 return ExprError(Diag(BuiltinLoc, 7514 diag::err_convertvector_incompatible_vector) 7515 << E->getSourceRange()); 7516 } 7517 7518 return new (Context) 7519 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 7520 } 7521 7522 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 7523 // This is declared to take (const void*, ...) and can take two 7524 // optional constant int args. 7525 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 7526 unsigned NumArgs = TheCall->getNumArgs(); 7527 7528 if (NumArgs > 3) 7529 return Diag(TheCall->getEndLoc(), 7530 diag::err_typecheck_call_too_many_args_at_most) 7531 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7532 7533 // Argument 0 is checked for us and the remaining arguments must be 7534 // constant integers. 7535 for (unsigned i = 1; i != NumArgs; ++i) 7536 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 7537 return true; 7538 7539 return false; 7540 } 7541 7542 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 7543 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 7544 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 7545 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 7546 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7547 if (checkArgCount(*this, TheCall, 1)) 7548 return true; 7549 Expr *Arg = TheCall->getArg(0); 7550 if (Arg->isInstantiationDependent()) 7551 return false; 7552 7553 QualType ArgTy = Arg->getType(); 7554 if (!ArgTy->hasFloatingRepresentation()) 7555 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 7556 << ArgTy; 7557 if (Arg->isLValue()) { 7558 ExprResult FirstArg = DefaultLvalueConversion(Arg); 7559 TheCall->setArg(0, FirstArg.get()); 7560 } 7561 TheCall->setType(TheCall->getArg(0)->getType()); 7562 return false; 7563 } 7564 7565 /// SemaBuiltinAssume - Handle __assume (MS Extension). 7566 // __assume does not evaluate its arguments, and should warn if its argument 7567 // has side effects. 7568 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 7569 Expr *Arg = TheCall->getArg(0); 7570 if (Arg->isInstantiationDependent()) return false; 7571 7572 if (Arg->HasSideEffects(Context)) 7573 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 7574 << Arg->getSourceRange() 7575 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 7576 7577 return false; 7578 } 7579 7580 /// Handle __builtin_alloca_with_align. This is declared 7581 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 7582 /// than 8. 7583 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 7584 // The alignment must be a constant integer. 7585 Expr *Arg = TheCall->getArg(1); 7586 7587 // We can't check the value of a dependent argument. 7588 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7589 if (const auto *UE = 7590 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 7591 if (UE->getKind() == UETT_AlignOf || 7592 UE->getKind() == UETT_PreferredAlignOf) 7593 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 7594 << Arg->getSourceRange(); 7595 7596 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 7597 7598 if (!Result.isPowerOf2()) 7599 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7600 << Arg->getSourceRange(); 7601 7602 if (Result < Context.getCharWidth()) 7603 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 7604 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 7605 7606 if (Result > std::numeric_limits<int32_t>::max()) 7607 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 7608 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 7609 } 7610 7611 return false; 7612 } 7613 7614 /// Handle __builtin_assume_aligned. This is declared 7615 /// as (const void*, size_t, ...) and can take one optional constant int arg. 7616 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 7617 unsigned NumArgs = TheCall->getNumArgs(); 7618 7619 if (NumArgs > 3) 7620 return Diag(TheCall->getEndLoc(), 7621 diag::err_typecheck_call_too_many_args_at_most) 7622 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7623 7624 // The alignment must be a constant integer. 7625 Expr *Arg = TheCall->getArg(1); 7626 7627 // We can't check the value of a dependent argument. 7628 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7629 llvm::APSInt Result; 7630 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7631 return true; 7632 7633 if (!Result.isPowerOf2()) 7634 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7635 << Arg->getSourceRange(); 7636 7637 if (Result > Sema::MaximumAlignment) 7638 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 7639 << Arg->getSourceRange() << Sema::MaximumAlignment; 7640 } 7641 7642 if (NumArgs > 2) { 7643 ExprResult Arg(TheCall->getArg(2)); 7644 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 7645 Context.getSizeType(), false); 7646 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7647 if (Arg.isInvalid()) return true; 7648 TheCall->setArg(2, Arg.get()); 7649 } 7650 7651 return false; 7652 } 7653 7654 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 7655 unsigned BuiltinID = 7656 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 7657 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 7658 7659 unsigned NumArgs = TheCall->getNumArgs(); 7660 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 7661 if (NumArgs < NumRequiredArgs) { 7662 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 7663 << 0 /* function call */ << NumRequiredArgs << NumArgs 7664 << TheCall->getSourceRange(); 7665 } 7666 if (NumArgs >= NumRequiredArgs + 0x100) { 7667 return Diag(TheCall->getEndLoc(), 7668 diag::err_typecheck_call_too_many_args_at_most) 7669 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 7670 << TheCall->getSourceRange(); 7671 } 7672 unsigned i = 0; 7673 7674 // For formatting call, check buffer arg. 7675 if (!IsSizeCall) { 7676 ExprResult Arg(TheCall->getArg(i)); 7677 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7678 Context, Context.VoidPtrTy, false); 7679 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7680 if (Arg.isInvalid()) 7681 return true; 7682 TheCall->setArg(i, Arg.get()); 7683 i++; 7684 } 7685 7686 // Check string literal arg. 7687 unsigned FormatIdx = i; 7688 { 7689 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 7690 if (Arg.isInvalid()) 7691 return true; 7692 TheCall->setArg(i, Arg.get()); 7693 i++; 7694 } 7695 7696 // Make sure variadic args are scalar. 7697 unsigned FirstDataArg = i; 7698 while (i < NumArgs) { 7699 ExprResult Arg = DefaultVariadicArgumentPromotion( 7700 TheCall->getArg(i), VariadicFunction, nullptr); 7701 if (Arg.isInvalid()) 7702 return true; 7703 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7704 if (ArgSize.getQuantity() >= 0x100) { 7705 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7706 << i << (int)ArgSize.getQuantity() << 0xff 7707 << TheCall->getSourceRange(); 7708 } 7709 TheCall->setArg(i, Arg.get()); 7710 i++; 7711 } 7712 7713 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7714 // call to avoid duplicate diagnostics. 7715 if (!IsSizeCall) { 7716 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7717 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7718 bool Success = CheckFormatArguments( 7719 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7720 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7721 CheckedVarArgs); 7722 if (!Success) 7723 return true; 7724 } 7725 7726 if (IsSizeCall) { 7727 TheCall->setType(Context.getSizeType()); 7728 } else { 7729 TheCall->setType(Context.VoidPtrTy); 7730 } 7731 return false; 7732 } 7733 7734 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7735 /// TheCall is a constant expression. 7736 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7737 llvm::APSInt &Result) { 7738 Expr *Arg = TheCall->getArg(ArgNum); 7739 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7740 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7741 7742 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7743 7744 Optional<llvm::APSInt> R; 7745 if (!(R = Arg->getIntegerConstantExpr(Context))) 7746 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7747 << FDecl->getDeclName() << Arg->getSourceRange(); 7748 Result = *R; 7749 return false; 7750 } 7751 7752 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7753 /// TheCall is a constant expression in the range [Low, High]. 7754 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7755 int Low, int High, bool RangeIsError) { 7756 if (isConstantEvaluated()) 7757 return false; 7758 llvm::APSInt Result; 7759 7760 // We can't check the value of a dependent argument. 7761 Expr *Arg = TheCall->getArg(ArgNum); 7762 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7763 return false; 7764 7765 // Check constant-ness first. 7766 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7767 return true; 7768 7769 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7770 if (RangeIsError) 7771 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7772 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7773 else 7774 // Defer the warning until we know if the code will be emitted so that 7775 // dead code can ignore this. 7776 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7777 PDiag(diag::warn_argument_invalid_range) 7778 << toString(Result, 10) << Low << High 7779 << Arg->getSourceRange()); 7780 } 7781 7782 return false; 7783 } 7784 7785 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7786 /// TheCall is a constant expression is a multiple of Num.. 7787 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7788 unsigned Num) { 7789 llvm::APSInt Result; 7790 7791 // We can't check the value of a dependent argument. 7792 Expr *Arg = TheCall->getArg(ArgNum); 7793 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7794 return false; 7795 7796 // Check constant-ness first. 7797 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7798 return true; 7799 7800 if (Result.getSExtValue() % Num != 0) 7801 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7802 << Num << Arg->getSourceRange(); 7803 7804 return false; 7805 } 7806 7807 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7808 /// constant expression representing a power of 2. 7809 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7810 llvm::APSInt Result; 7811 7812 // We can't check the value of a dependent argument. 7813 Expr *Arg = TheCall->getArg(ArgNum); 7814 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7815 return false; 7816 7817 // Check constant-ness first. 7818 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7819 return true; 7820 7821 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7822 // and only if x is a power of 2. 7823 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7824 return false; 7825 7826 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7827 << Arg->getSourceRange(); 7828 } 7829 7830 static bool IsShiftedByte(llvm::APSInt Value) { 7831 if (Value.isNegative()) 7832 return false; 7833 7834 // Check if it's a shifted byte, by shifting it down 7835 while (true) { 7836 // If the value fits in the bottom byte, the check passes. 7837 if (Value < 0x100) 7838 return true; 7839 7840 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7841 // fails. 7842 if ((Value & 0xFF) != 0) 7843 return false; 7844 7845 // If the bottom 8 bits are all 0, but something above that is nonzero, 7846 // then shifting the value right by 8 bits won't affect whether it's a 7847 // shifted byte or not. So do that, and go round again. 7848 Value >>= 8; 7849 } 7850 } 7851 7852 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7853 /// a constant expression representing an arbitrary byte value shifted left by 7854 /// a multiple of 8 bits. 7855 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7856 unsigned ArgBits) { 7857 llvm::APSInt Result; 7858 7859 // We can't check the value of a dependent argument. 7860 Expr *Arg = TheCall->getArg(ArgNum); 7861 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7862 return false; 7863 7864 // Check constant-ness first. 7865 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7866 return true; 7867 7868 // Truncate to the given size. 7869 Result = Result.getLoBits(ArgBits); 7870 Result.setIsUnsigned(true); 7871 7872 if (IsShiftedByte(Result)) 7873 return false; 7874 7875 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7876 << Arg->getSourceRange(); 7877 } 7878 7879 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7880 /// TheCall is a constant expression representing either a shifted byte value, 7881 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7882 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7883 /// Arm MVE intrinsics. 7884 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7885 int ArgNum, 7886 unsigned ArgBits) { 7887 llvm::APSInt Result; 7888 7889 // We can't check the value of a dependent argument. 7890 Expr *Arg = TheCall->getArg(ArgNum); 7891 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7892 return false; 7893 7894 // Check constant-ness first. 7895 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7896 return true; 7897 7898 // Truncate to the given size. 7899 Result = Result.getLoBits(ArgBits); 7900 Result.setIsUnsigned(true); 7901 7902 // Check to see if it's in either of the required forms. 7903 if (IsShiftedByte(Result) || 7904 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7905 return false; 7906 7907 return Diag(TheCall->getBeginLoc(), 7908 diag::err_argument_not_shifted_byte_or_xxff) 7909 << Arg->getSourceRange(); 7910 } 7911 7912 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7913 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7914 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7915 if (checkArgCount(*this, TheCall, 2)) 7916 return true; 7917 Expr *Arg0 = TheCall->getArg(0); 7918 Expr *Arg1 = TheCall->getArg(1); 7919 7920 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7921 if (FirstArg.isInvalid()) 7922 return true; 7923 QualType FirstArgType = FirstArg.get()->getType(); 7924 if (!FirstArgType->isAnyPointerType()) 7925 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7926 << "first" << FirstArgType << Arg0->getSourceRange(); 7927 TheCall->setArg(0, FirstArg.get()); 7928 7929 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7930 if (SecArg.isInvalid()) 7931 return true; 7932 QualType SecArgType = SecArg.get()->getType(); 7933 if (!SecArgType->isIntegerType()) 7934 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7935 << "second" << SecArgType << Arg1->getSourceRange(); 7936 7937 // Derive the return type from the pointer argument. 7938 TheCall->setType(FirstArgType); 7939 return false; 7940 } 7941 7942 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7943 if (checkArgCount(*this, TheCall, 2)) 7944 return true; 7945 7946 Expr *Arg0 = TheCall->getArg(0); 7947 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7948 if (FirstArg.isInvalid()) 7949 return true; 7950 QualType FirstArgType = FirstArg.get()->getType(); 7951 if (!FirstArgType->isAnyPointerType()) 7952 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7953 << "first" << FirstArgType << Arg0->getSourceRange(); 7954 TheCall->setArg(0, FirstArg.get()); 7955 7956 // Derive the return type from the pointer argument. 7957 TheCall->setType(FirstArgType); 7958 7959 // Second arg must be an constant in range [0,15] 7960 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7961 } 7962 7963 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7964 if (checkArgCount(*this, TheCall, 2)) 7965 return true; 7966 Expr *Arg0 = TheCall->getArg(0); 7967 Expr *Arg1 = TheCall->getArg(1); 7968 7969 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7970 if (FirstArg.isInvalid()) 7971 return true; 7972 QualType FirstArgType = FirstArg.get()->getType(); 7973 if (!FirstArgType->isAnyPointerType()) 7974 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7975 << "first" << FirstArgType << Arg0->getSourceRange(); 7976 7977 QualType SecArgType = Arg1->getType(); 7978 if (!SecArgType->isIntegerType()) 7979 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7980 << "second" << SecArgType << Arg1->getSourceRange(); 7981 TheCall->setType(Context.IntTy); 7982 return false; 7983 } 7984 7985 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7986 BuiltinID == AArch64::BI__builtin_arm_stg) { 7987 if (checkArgCount(*this, TheCall, 1)) 7988 return true; 7989 Expr *Arg0 = TheCall->getArg(0); 7990 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7991 if (FirstArg.isInvalid()) 7992 return true; 7993 7994 QualType FirstArgType = FirstArg.get()->getType(); 7995 if (!FirstArgType->isAnyPointerType()) 7996 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7997 << "first" << FirstArgType << Arg0->getSourceRange(); 7998 TheCall->setArg(0, FirstArg.get()); 7999 8000 // Derive the return type from the pointer argument. 8001 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 8002 TheCall->setType(FirstArgType); 8003 return false; 8004 } 8005 8006 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 8007 Expr *ArgA = TheCall->getArg(0); 8008 Expr *ArgB = TheCall->getArg(1); 8009 8010 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 8011 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 8012 8013 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 8014 return true; 8015 8016 QualType ArgTypeA = ArgExprA.get()->getType(); 8017 QualType ArgTypeB = ArgExprB.get()->getType(); 8018 8019 auto isNull = [&] (Expr *E) -> bool { 8020 return E->isNullPointerConstant( 8021 Context, Expr::NPC_ValueDependentIsNotNull); }; 8022 8023 // argument should be either a pointer or null 8024 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 8025 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 8026 << "first" << ArgTypeA << ArgA->getSourceRange(); 8027 8028 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 8029 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 8030 << "second" << ArgTypeB << ArgB->getSourceRange(); 8031 8032 // Ensure Pointee types are compatible 8033 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 8034 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 8035 QualType pointeeA = ArgTypeA->getPointeeType(); 8036 QualType pointeeB = ArgTypeB->getPointeeType(); 8037 if (!Context.typesAreCompatible( 8038 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 8039 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 8040 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 8041 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 8042 << ArgB->getSourceRange(); 8043 } 8044 } 8045 8046 // at least one argument should be pointer type 8047 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 8048 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 8049 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 8050 8051 if (isNull(ArgA)) // adopt type of the other pointer 8052 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 8053 8054 if (isNull(ArgB)) 8055 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 8056 8057 TheCall->setArg(0, ArgExprA.get()); 8058 TheCall->setArg(1, ArgExprB.get()); 8059 TheCall->setType(Context.LongLongTy); 8060 return false; 8061 } 8062 assert(false && "Unhandled ARM MTE intrinsic"); 8063 return true; 8064 } 8065 8066 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 8067 /// TheCall is an ARM/AArch64 special register string literal. 8068 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 8069 int ArgNum, unsigned ExpectedFieldNum, 8070 bool AllowName) { 8071 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 8072 BuiltinID == ARM::BI__builtin_arm_wsr64 || 8073 BuiltinID == ARM::BI__builtin_arm_rsr || 8074 BuiltinID == ARM::BI__builtin_arm_rsrp || 8075 BuiltinID == ARM::BI__builtin_arm_wsr || 8076 BuiltinID == ARM::BI__builtin_arm_wsrp; 8077 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 8078 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 8079 BuiltinID == AArch64::BI__builtin_arm_rsr || 8080 BuiltinID == AArch64::BI__builtin_arm_rsrp || 8081 BuiltinID == AArch64::BI__builtin_arm_wsr || 8082 BuiltinID == AArch64::BI__builtin_arm_wsrp; 8083 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 8084 8085 // We can't check the value of a dependent argument. 8086 Expr *Arg = TheCall->getArg(ArgNum); 8087 if (Arg->isTypeDependent() || Arg->isValueDependent()) 8088 return false; 8089 8090 // Check if the argument is a string literal. 8091 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 8092 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 8093 << Arg->getSourceRange(); 8094 8095 // Check the type of special register given. 8096 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 8097 SmallVector<StringRef, 6> Fields; 8098 Reg.split(Fields, ":"); 8099 8100 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 8101 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 8102 << Arg->getSourceRange(); 8103 8104 // If the string is the name of a register then we cannot check that it is 8105 // valid here but if the string is of one the forms described in ACLE then we 8106 // can check that the supplied fields are integers and within the valid 8107 // ranges. 8108 if (Fields.size() > 1) { 8109 bool FiveFields = Fields.size() == 5; 8110 8111 bool ValidString = true; 8112 if (IsARMBuiltin) { 8113 ValidString &= Fields[0].startswith_insensitive("cp") || 8114 Fields[0].startswith_insensitive("p"); 8115 if (ValidString) 8116 Fields[0] = Fields[0].drop_front( 8117 Fields[0].startswith_insensitive("cp") ? 2 : 1); 8118 8119 ValidString &= Fields[2].startswith_insensitive("c"); 8120 if (ValidString) 8121 Fields[2] = Fields[2].drop_front(1); 8122 8123 if (FiveFields) { 8124 ValidString &= Fields[3].startswith_insensitive("c"); 8125 if (ValidString) 8126 Fields[3] = Fields[3].drop_front(1); 8127 } 8128 } 8129 8130 SmallVector<int, 5> Ranges; 8131 if (FiveFields) 8132 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 8133 else 8134 Ranges.append({15, 7, 15}); 8135 8136 for (unsigned i=0; i<Fields.size(); ++i) { 8137 int IntField; 8138 ValidString &= !Fields[i].getAsInteger(10, IntField); 8139 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 8140 } 8141 8142 if (!ValidString) 8143 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 8144 << Arg->getSourceRange(); 8145 } else if (IsAArch64Builtin && Fields.size() == 1) { 8146 // If the register name is one of those that appear in the condition below 8147 // and the special register builtin being used is one of the write builtins, 8148 // then we require that the argument provided for writing to the register 8149 // is an integer constant expression. This is because it will be lowered to 8150 // an MSR (immediate) instruction, so we need to know the immediate at 8151 // compile time. 8152 if (TheCall->getNumArgs() != 2) 8153 return false; 8154 8155 std::string RegLower = Reg.lower(); 8156 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 8157 RegLower != "pan" && RegLower != "uao") 8158 return false; 8159 8160 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 8161 } 8162 8163 return false; 8164 } 8165 8166 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 8167 /// Emit an error and return true on failure; return false on success. 8168 /// TypeStr is a string containing the type descriptor of the value returned by 8169 /// the builtin and the descriptors of the expected type of the arguments. 8170 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 8171 const char *TypeStr) { 8172 8173 assert((TypeStr[0] != '\0') && 8174 "Invalid types in PPC MMA builtin declaration"); 8175 8176 switch (BuiltinID) { 8177 default: 8178 // This function is called in CheckPPCBuiltinFunctionCall where the 8179 // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here 8180 // we are isolating the pair vector memop builtins that can be used with mma 8181 // off so the default case is every builtin that requires mma and paired 8182 // vector memops. 8183 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 8184 diag::err_ppc_builtin_only_on_arch, "10") || 8185 SemaFeatureCheck(*this, TheCall, "mma", 8186 diag::err_ppc_builtin_only_on_arch, "10")) 8187 return true; 8188 break; 8189 case PPC::BI__builtin_vsx_lxvp: 8190 case PPC::BI__builtin_vsx_stxvp: 8191 case PPC::BI__builtin_vsx_assemble_pair: 8192 case PPC::BI__builtin_vsx_disassemble_pair: 8193 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 8194 diag::err_ppc_builtin_only_on_arch, "10")) 8195 return true; 8196 break; 8197 } 8198 8199 unsigned Mask = 0; 8200 unsigned ArgNum = 0; 8201 8202 // The first type in TypeStr is the type of the value returned by the 8203 // builtin. So we first read that type and change the type of TheCall. 8204 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 8205 TheCall->setType(type); 8206 8207 while (*TypeStr != '\0') { 8208 Mask = 0; 8209 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 8210 if (ArgNum >= TheCall->getNumArgs()) { 8211 ArgNum++; 8212 break; 8213 } 8214 8215 Expr *Arg = TheCall->getArg(ArgNum); 8216 QualType PassedType = Arg->getType(); 8217 QualType StrippedRVType = PassedType.getCanonicalType(); 8218 8219 // Strip Restrict/Volatile qualifiers. 8220 if (StrippedRVType.isRestrictQualified() || 8221 StrippedRVType.isVolatileQualified()) 8222 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType(); 8223 8224 // The only case where the argument type and expected type are allowed to 8225 // mismatch is if the argument type is a non-void pointer (or array) and 8226 // expected type is a void pointer. 8227 if (StrippedRVType != ExpectedType) 8228 if (!(ExpectedType->isVoidPointerType() && 8229 (StrippedRVType->isPointerType() || StrippedRVType->isArrayType()))) 8230 return Diag(Arg->getBeginLoc(), 8231 diag::err_typecheck_convert_incompatible) 8232 << PassedType << ExpectedType << 1 << 0 << 0; 8233 8234 // If the value of the Mask is not 0, we have a constraint in the size of 8235 // the integer argument so here we ensure the argument is a constant that 8236 // is in the valid range. 8237 if (Mask != 0 && 8238 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 8239 return true; 8240 8241 ArgNum++; 8242 } 8243 8244 // In case we exited early from the previous loop, there are other types to 8245 // read from TypeStr. So we need to read them all to ensure we have the right 8246 // number of arguments in TheCall and if it is not the case, to display a 8247 // better error message. 8248 while (*TypeStr != '\0') { 8249 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 8250 ArgNum++; 8251 } 8252 if (checkArgCount(*this, TheCall, ArgNum)) 8253 return true; 8254 8255 return false; 8256 } 8257 8258 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 8259 /// This checks that the target supports __builtin_longjmp and 8260 /// that val is a constant 1. 8261 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 8262 if (!Context.getTargetInfo().hasSjLjLowering()) 8263 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 8264 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 8265 8266 Expr *Arg = TheCall->getArg(1); 8267 llvm::APSInt Result; 8268 8269 // TODO: This is less than ideal. Overload this to take a value. 8270 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 8271 return true; 8272 8273 if (Result != 1) 8274 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 8275 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 8276 8277 return false; 8278 } 8279 8280 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 8281 /// This checks that the target supports __builtin_setjmp. 8282 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 8283 if (!Context.getTargetInfo().hasSjLjLowering()) 8284 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 8285 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 8286 return false; 8287 } 8288 8289 namespace { 8290 8291 class UncoveredArgHandler { 8292 enum { Unknown = -1, AllCovered = -2 }; 8293 8294 signed FirstUncoveredArg = Unknown; 8295 SmallVector<const Expr *, 4> DiagnosticExprs; 8296 8297 public: 8298 UncoveredArgHandler() = default; 8299 8300 bool hasUncoveredArg() const { 8301 return (FirstUncoveredArg >= 0); 8302 } 8303 8304 unsigned getUncoveredArg() const { 8305 assert(hasUncoveredArg() && "no uncovered argument"); 8306 return FirstUncoveredArg; 8307 } 8308 8309 void setAllCovered() { 8310 // A string has been found with all arguments covered, so clear out 8311 // the diagnostics. 8312 DiagnosticExprs.clear(); 8313 FirstUncoveredArg = AllCovered; 8314 } 8315 8316 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 8317 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 8318 8319 // Don't update if a previous string covers all arguments. 8320 if (FirstUncoveredArg == AllCovered) 8321 return; 8322 8323 // UncoveredArgHandler tracks the highest uncovered argument index 8324 // and with it all the strings that match this index. 8325 if (NewFirstUncoveredArg == FirstUncoveredArg) 8326 DiagnosticExprs.push_back(StrExpr); 8327 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 8328 DiagnosticExprs.clear(); 8329 DiagnosticExprs.push_back(StrExpr); 8330 FirstUncoveredArg = NewFirstUncoveredArg; 8331 } 8332 } 8333 8334 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 8335 }; 8336 8337 enum StringLiteralCheckType { 8338 SLCT_NotALiteral, 8339 SLCT_UncheckedLiteral, 8340 SLCT_CheckedLiteral 8341 }; 8342 8343 } // namespace 8344 8345 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 8346 BinaryOperatorKind BinOpKind, 8347 bool AddendIsRight) { 8348 unsigned BitWidth = Offset.getBitWidth(); 8349 unsigned AddendBitWidth = Addend.getBitWidth(); 8350 // There might be negative interim results. 8351 if (Addend.isUnsigned()) { 8352 Addend = Addend.zext(++AddendBitWidth); 8353 Addend.setIsSigned(true); 8354 } 8355 // Adjust the bit width of the APSInts. 8356 if (AddendBitWidth > BitWidth) { 8357 Offset = Offset.sext(AddendBitWidth); 8358 BitWidth = AddendBitWidth; 8359 } else if (BitWidth > AddendBitWidth) { 8360 Addend = Addend.sext(BitWidth); 8361 } 8362 8363 bool Ov = false; 8364 llvm::APSInt ResOffset = Offset; 8365 if (BinOpKind == BO_Add) 8366 ResOffset = Offset.sadd_ov(Addend, Ov); 8367 else { 8368 assert(AddendIsRight && BinOpKind == BO_Sub && 8369 "operator must be add or sub with addend on the right"); 8370 ResOffset = Offset.ssub_ov(Addend, Ov); 8371 } 8372 8373 // We add an offset to a pointer here so we should support an offset as big as 8374 // possible. 8375 if (Ov) { 8376 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 8377 "index (intermediate) result too big"); 8378 Offset = Offset.sext(2 * BitWidth); 8379 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 8380 return; 8381 } 8382 8383 Offset = ResOffset; 8384 } 8385 8386 namespace { 8387 8388 // This is a wrapper class around StringLiteral to support offsetted string 8389 // literals as format strings. It takes the offset into account when returning 8390 // the string and its length or the source locations to display notes correctly. 8391 class FormatStringLiteral { 8392 const StringLiteral *FExpr; 8393 int64_t Offset; 8394 8395 public: 8396 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 8397 : FExpr(fexpr), Offset(Offset) {} 8398 8399 StringRef getString() const { 8400 return FExpr->getString().drop_front(Offset); 8401 } 8402 8403 unsigned getByteLength() const { 8404 return FExpr->getByteLength() - getCharByteWidth() * Offset; 8405 } 8406 8407 unsigned getLength() const { return FExpr->getLength() - Offset; } 8408 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 8409 8410 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 8411 8412 QualType getType() const { return FExpr->getType(); } 8413 8414 bool isAscii() const { return FExpr->isAscii(); } 8415 bool isWide() const { return FExpr->isWide(); } 8416 bool isUTF8() const { return FExpr->isUTF8(); } 8417 bool isUTF16() const { return FExpr->isUTF16(); } 8418 bool isUTF32() const { return FExpr->isUTF32(); } 8419 bool isPascal() const { return FExpr->isPascal(); } 8420 8421 SourceLocation getLocationOfByte( 8422 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 8423 const TargetInfo &Target, unsigned *StartToken = nullptr, 8424 unsigned *StartTokenByteOffset = nullptr) const { 8425 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 8426 StartToken, StartTokenByteOffset); 8427 } 8428 8429 SourceLocation getBeginLoc() const LLVM_READONLY { 8430 return FExpr->getBeginLoc().getLocWithOffset(Offset); 8431 } 8432 8433 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 8434 }; 8435 8436 } // namespace 8437 8438 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8439 const Expr *OrigFormatExpr, 8440 ArrayRef<const Expr *> Args, 8441 bool HasVAListArg, unsigned format_idx, 8442 unsigned firstDataArg, 8443 Sema::FormatStringType Type, 8444 bool inFunctionCall, 8445 Sema::VariadicCallType CallType, 8446 llvm::SmallBitVector &CheckedVarArgs, 8447 UncoveredArgHandler &UncoveredArg, 8448 bool IgnoreStringsWithoutSpecifiers); 8449 8450 // Determine if an expression is a string literal or constant string. 8451 // If this function returns false on the arguments to a function expecting a 8452 // format string, we will usually need to emit a warning. 8453 // True string literals are then checked by CheckFormatString. 8454 static StringLiteralCheckType 8455 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 8456 bool HasVAListArg, unsigned format_idx, 8457 unsigned firstDataArg, Sema::FormatStringType Type, 8458 Sema::VariadicCallType CallType, bool InFunctionCall, 8459 llvm::SmallBitVector &CheckedVarArgs, 8460 UncoveredArgHandler &UncoveredArg, 8461 llvm::APSInt Offset, 8462 bool IgnoreStringsWithoutSpecifiers = false) { 8463 if (S.isConstantEvaluated()) 8464 return SLCT_NotALiteral; 8465 tryAgain: 8466 assert(Offset.isSigned() && "invalid offset"); 8467 8468 if (E->isTypeDependent() || E->isValueDependent()) 8469 return SLCT_NotALiteral; 8470 8471 E = E->IgnoreParenCasts(); 8472 8473 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 8474 // Technically -Wformat-nonliteral does not warn about this case. 8475 // The behavior of printf and friends in this case is implementation 8476 // dependent. Ideally if the format string cannot be null then 8477 // it should have a 'nonnull' attribute in the function prototype. 8478 return SLCT_UncheckedLiteral; 8479 8480 switch (E->getStmtClass()) { 8481 case Stmt::BinaryConditionalOperatorClass: 8482 case Stmt::ConditionalOperatorClass: { 8483 // The expression is a literal if both sub-expressions were, and it was 8484 // completely checked only if both sub-expressions were checked. 8485 const AbstractConditionalOperator *C = 8486 cast<AbstractConditionalOperator>(E); 8487 8488 // Determine whether it is necessary to check both sub-expressions, for 8489 // example, because the condition expression is a constant that can be 8490 // evaluated at compile time. 8491 bool CheckLeft = true, CheckRight = true; 8492 8493 bool Cond; 8494 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 8495 S.isConstantEvaluated())) { 8496 if (Cond) 8497 CheckRight = false; 8498 else 8499 CheckLeft = false; 8500 } 8501 8502 // We need to maintain the offsets for the right and the left hand side 8503 // separately to check if every possible indexed expression is a valid 8504 // string literal. They might have different offsets for different string 8505 // literals in the end. 8506 StringLiteralCheckType Left; 8507 if (!CheckLeft) 8508 Left = SLCT_UncheckedLiteral; 8509 else { 8510 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 8511 HasVAListArg, format_idx, firstDataArg, 8512 Type, CallType, InFunctionCall, 8513 CheckedVarArgs, UncoveredArg, Offset, 8514 IgnoreStringsWithoutSpecifiers); 8515 if (Left == SLCT_NotALiteral || !CheckRight) { 8516 return Left; 8517 } 8518 } 8519 8520 StringLiteralCheckType Right = checkFormatStringExpr( 8521 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 8522 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8523 IgnoreStringsWithoutSpecifiers); 8524 8525 return (CheckLeft && Left < Right) ? Left : Right; 8526 } 8527 8528 case Stmt::ImplicitCastExprClass: 8529 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 8530 goto tryAgain; 8531 8532 case Stmt::OpaqueValueExprClass: 8533 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 8534 E = src; 8535 goto tryAgain; 8536 } 8537 return SLCT_NotALiteral; 8538 8539 case Stmt::PredefinedExprClass: 8540 // While __func__, etc., are technically not string literals, they 8541 // cannot contain format specifiers and thus are not a security 8542 // liability. 8543 return SLCT_UncheckedLiteral; 8544 8545 case Stmt::DeclRefExprClass: { 8546 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8547 8548 // As an exception, do not flag errors for variables binding to 8549 // const string literals. 8550 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 8551 bool isConstant = false; 8552 QualType T = DR->getType(); 8553 8554 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 8555 isConstant = AT->getElementType().isConstant(S.Context); 8556 } else if (const PointerType *PT = T->getAs<PointerType>()) { 8557 isConstant = T.isConstant(S.Context) && 8558 PT->getPointeeType().isConstant(S.Context); 8559 } else if (T->isObjCObjectPointerType()) { 8560 // In ObjC, there is usually no "const ObjectPointer" type, 8561 // so don't check if the pointee type is constant. 8562 isConstant = T.isConstant(S.Context); 8563 } 8564 8565 if (isConstant) { 8566 if (const Expr *Init = VD->getAnyInitializer()) { 8567 // Look through initializers like const char c[] = { "foo" } 8568 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 8569 if (InitList->isStringLiteralInit()) 8570 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 8571 } 8572 return checkFormatStringExpr(S, Init, Args, 8573 HasVAListArg, format_idx, 8574 firstDataArg, Type, CallType, 8575 /*InFunctionCall*/ false, CheckedVarArgs, 8576 UncoveredArg, Offset); 8577 } 8578 } 8579 8580 // For vprintf* functions (i.e., HasVAListArg==true), we add a 8581 // special check to see if the format string is a function parameter 8582 // of the function calling the printf function. If the function 8583 // has an attribute indicating it is a printf-like function, then we 8584 // should suppress warnings concerning non-literals being used in a call 8585 // to a vprintf function. For example: 8586 // 8587 // void 8588 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 8589 // va_list ap; 8590 // va_start(ap, fmt); 8591 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 8592 // ... 8593 // } 8594 if (HasVAListArg) { 8595 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 8596 if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) { 8597 int PVIndex = PV->getFunctionScopeIndex() + 1; 8598 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) { 8599 // adjust for implicit parameter 8600 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 8601 if (MD->isInstance()) 8602 ++PVIndex; 8603 // We also check if the formats are compatible. 8604 // We can't pass a 'scanf' string to a 'printf' function. 8605 if (PVIndex == PVFormat->getFormatIdx() && 8606 Type == S.GetFormatStringType(PVFormat)) 8607 return SLCT_UncheckedLiteral; 8608 } 8609 } 8610 } 8611 } 8612 } 8613 8614 return SLCT_NotALiteral; 8615 } 8616 8617 case Stmt::CallExprClass: 8618 case Stmt::CXXMemberCallExprClass: { 8619 const CallExpr *CE = cast<CallExpr>(E); 8620 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 8621 bool IsFirst = true; 8622 StringLiteralCheckType CommonResult; 8623 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 8624 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 8625 StringLiteralCheckType Result = checkFormatStringExpr( 8626 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8627 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8628 IgnoreStringsWithoutSpecifiers); 8629 if (IsFirst) { 8630 CommonResult = Result; 8631 IsFirst = false; 8632 } 8633 } 8634 if (!IsFirst) 8635 return CommonResult; 8636 8637 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 8638 unsigned BuiltinID = FD->getBuiltinID(); 8639 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 8640 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 8641 const Expr *Arg = CE->getArg(0); 8642 return checkFormatStringExpr(S, Arg, Args, 8643 HasVAListArg, format_idx, 8644 firstDataArg, Type, CallType, 8645 InFunctionCall, CheckedVarArgs, 8646 UncoveredArg, Offset, 8647 IgnoreStringsWithoutSpecifiers); 8648 } 8649 } 8650 } 8651 8652 return SLCT_NotALiteral; 8653 } 8654 case Stmt::ObjCMessageExprClass: { 8655 const auto *ME = cast<ObjCMessageExpr>(E); 8656 if (const auto *MD = ME->getMethodDecl()) { 8657 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 8658 // As a special case heuristic, if we're using the method -[NSBundle 8659 // localizedStringForKey:value:table:], ignore any key strings that lack 8660 // format specifiers. The idea is that if the key doesn't have any 8661 // format specifiers then its probably just a key to map to the 8662 // localized strings. If it does have format specifiers though, then its 8663 // likely that the text of the key is the format string in the 8664 // programmer's language, and should be checked. 8665 const ObjCInterfaceDecl *IFace; 8666 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 8667 IFace->getIdentifier()->isStr("NSBundle") && 8668 MD->getSelector().isKeywordSelector( 8669 {"localizedStringForKey", "value", "table"})) { 8670 IgnoreStringsWithoutSpecifiers = true; 8671 } 8672 8673 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 8674 return checkFormatStringExpr( 8675 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8676 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8677 IgnoreStringsWithoutSpecifiers); 8678 } 8679 } 8680 8681 return SLCT_NotALiteral; 8682 } 8683 case Stmt::ObjCStringLiteralClass: 8684 case Stmt::StringLiteralClass: { 8685 const StringLiteral *StrE = nullptr; 8686 8687 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 8688 StrE = ObjCFExpr->getString(); 8689 else 8690 StrE = cast<StringLiteral>(E); 8691 8692 if (StrE) { 8693 if (Offset.isNegative() || Offset > StrE->getLength()) { 8694 // TODO: It would be better to have an explicit warning for out of 8695 // bounds literals. 8696 return SLCT_NotALiteral; 8697 } 8698 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 8699 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 8700 firstDataArg, Type, InFunctionCall, CallType, 8701 CheckedVarArgs, UncoveredArg, 8702 IgnoreStringsWithoutSpecifiers); 8703 return SLCT_CheckedLiteral; 8704 } 8705 8706 return SLCT_NotALiteral; 8707 } 8708 case Stmt::BinaryOperatorClass: { 8709 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 8710 8711 // A string literal + an int offset is still a string literal. 8712 if (BinOp->isAdditiveOp()) { 8713 Expr::EvalResult LResult, RResult; 8714 8715 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 8716 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8717 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 8718 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8719 8720 if (LIsInt != RIsInt) { 8721 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 8722 8723 if (LIsInt) { 8724 if (BinOpKind == BO_Add) { 8725 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 8726 E = BinOp->getRHS(); 8727 goto tryAgain; 8728 } 8729 } else { 8730 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8731 E = BinOp->getLHS(); 8732 goto tryAgain; 8733 } 8734 } 8735 } 8736 8737 return SLCT_NotALiteral; 8738 } 8739 case Stmt::UnaryOperatorClass: { 8740 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8741 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8742 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8743 Expr::EvalResult IndexResult; 8744 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8745 Expr::SE_NoSideEffects, 8746 S.isConstantEvaluated())) { 8747 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8748 /*RHS is int*/ true); 8749 E = ASE->getBase(); 8750 goto tryAgain; 8751 } 8752 } 8753 8754 return SLCT_NotALiteral; 8755 } 8756 8757 default: 8758 return SLCT_NotALiteral; 8759 } 8760 } 8761 8762 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8763 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8764 .Case("scanf", FST_Scanf) 8765 .Cases("printf", "printf0", FST_Printf) 8766 .Cases("NSString", "CFString", FST_NSString) 8767 .Case("strftime", FST_Strftime) 8768 .Case("strfmon", FST_Strfmon) 8769 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8770 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8771 .Case("os_trace", FST_OSLog) 8772 .Case("os_log", FST_OSLog) 8773 .Default(FST_Unknown); 8774 } 8775 8776 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8777 /// functions) for correct use of format strings. 8778 /// Returns true if a format string has been fully checked. 8779 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8780 ArrayRef<const Expr *> Args, 8781 bool IsCXXMember, 8782 VariadicCallType CallType, 8783 SourceLocation Loc, SourceRange Range, 8784 llvm::SmallBitVector &CheckedVarArgs) { 8785 FormatStringInfo FSI; 8786 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8787 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8788 FSI.FirstDataArg, GetFormatStringType(Format), 8789 CallType, Loc, Range, CheckedVarArgs); 8790 return false; 8791 } 8792 8793 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8794 bool HasVAListArg, unsigned format_idx, 8795 unsigned firstDataArg, FormatStringType Type, 8796 VariadicCallType CallType, 8797 SourceLocation Loc, SourceRange Range, 8798 llvm::SmallBitVector &CheckedVarArgs) { 8799 // CHECK: printf/scanf-like function is called with no format string. 8800 if (format_idx >= Args.size()) { 8801 Diag(Loc, diag::warn_missing_format_string) << Range; 8802 return false; 8803 } 8804 8805 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8806 8807 // CHECK: format string is not a string literal. 8808 // 8809 // Dynamically generated format strings are difficult to 8810 // automatically vet at compile time. Requiring that format strings 8811 // are string literals: (1) permits the checking of format strings by 8812 // the compiler and thereby (2) can practically remove the source of 8813 // many format string exploits. 8814 8815 // Format string can be either ObjC string (e.g. @"%d") or 8816 // C string (e.g. "%d") 8817 // ObjC string uses the same format specifiers as C string, so we can use 8818 // the same format string checking logic for both ObjC and C strings. 8819 UncoveredArgHandler UncoveredArg; 8820 StringLiteralCheckType CT = 8821 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8822 format_idx, firstDataArg, Type, CallType, 8823 /*IsFunctionCall*/ true, CheckedVarArgs, 8824 UncoveredArg, 8825 /*no string offset*/ llvm::APSInt(64, false) = 0); 8826 8827 // Generate a diagnostic where an uncovered argument is detected. 8828 if (UncoveredArg.hasUncoveredArg()) { 8829 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8830 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8831 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8832 } 8833 8834 if (CT != SLCT_NotALiteral) 8835 // Literal format string found, check done! 8836 return CT == SLCT_CheckedLiteral; 8837 8838 // Strftime is particular as it always uses a single 'time' argument, 8839 // so it is safe to pass a non-literal string. 8840 if (Type == FST_Strftime) 8841 return false; 8842 8843 // Do not emit diag when the string param is a macro expansion and the 8844 // format is either NSString or CFString. This is a hack to prevent 8845 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8846 // which are usually used in place of NS and CF string literals. 8847 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8848 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8849 return false; 8850 8851 // If there are no arguments specified, warn with -Wformat-security, otherwise 8852 // warn only with -Wformat-nonliteral. 8853 if (Args.size() == firstDataArg) { 8854 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8855 << OrigFormatExpr->getSourceRange(); 8856 switch (Type) { 8857 default: 8858 break; 8859 case FST_Kprintf: 8860 case FST_FreeBSDKPrintf: 8861 case FST_Printf: 8862 Diag(FormatLoc, diag::note_format_security_fixit) 8863 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8864 break; 8865 case FST_NSString: 8866 Diag(FormatLoc, diag::note_format_security_fixit) 8867 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8868 break; 8869 } 8870 } else { 8871 Diag(FormatLoc, diag::warn_format_nonliteral) 8872 << OrigFormatExpr->getSourceRange(); 8873 } 8874 return false; 8875 } 8876 8877 namespace { 8878 8879 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8880 protected: 8881 Sema &S; 8882 const FormatStringLiteral *FExpr; 8883 const Expr *OrigFormatExpr; 8884 const Sema::FormatStringType FSType; 8885 const unsigned FirstDataArg; 8886 const unsigned NumDataArgs; 8887 const char *Beg; // Start of format string. 8888 const bool HasVAListArg; 8889 ArrayRef<const Expr *> Args; 8890 unsigned FormatIdx; 8891 llvm::SmallBitVector CoveredArgs; 8892 bool usesPositionalArgs = false; 8893 bool atFirstArg = true; 8894 bool inFunctionCall; 8895 Sema::VariadicCallType CallType; 8896 llvm::SmallBitVector &CheckedVarArgs; 8897 UncoveredArgHandler &UncoveredArg; 8898 8899 public: 8900 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8901 const Expr *origFormatExpr, 8902 const Sema::FormatStringType type, unsigned firstDataArg, 8903 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8904 ArrayRef<const Expr *> Args, unsigned formatIdx, 8905 bool inFunctionCall, Sema::VariadicCallType callType, 8906 llvm::SmallBitVector &CheckedVarArgs, 8907 UncoveredArgHandler &UncoveredArg) 8908 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8909 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8910 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8911 inFunctionCall(inFunctionCall), CallType(callType), 8912 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8913 CoveredArgs.resize(numDataArgs); 8914 CoveredArgs.reset(); 8915 } 8916 8917 void DoneProcessing(); 8918 8919 void HandleIncompleteSpecifier(const char *startSpecifier, 8920 unsigned specifierLen) override; 8921 8922 void HandleInvalidLengthModifier( 8923 const analyze_format_string::FormatSpecifier &FS, 8924 const analyze_format_string::ConversionSpecifier &CS, 8925 const char *startSpecifier, unsigned specifierLen, 8926 unsigned DiagID); 8927 8928 void HandleNonStandardLengthModifier( 8929 const analyze_format_string::FormatSpecifier &FS, 8930 const char *startSpecifier, unsigned specifierLen); 8931 8932 void HandleNonStandardConversionSpecifier( 8933 const analyze_format_string::ConversionSpecifier &CS, 8934 const char *startSpecifier, unsigned specifierLen); 8935 8936 void HandlePosition(const char *startPos, unsigned posLen) override; 8937 8938 void HandleInvalidPosition(const char *startSpecifier, 8939 unsigned specifierLen, 8940 analyze_format_string::PositionContext p) override; 8941 8942 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8943 8944 void HandleNullChar(const char *nullCharacter) override; 8945 8946 template <typename Range> 8947 static void 8948 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8949 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8950 bool IsStringLocation, Range StringRange, 8951 ArrayRef<FixItHint> Fixit = None); 8952 8953 protected: 8954 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8955 const char *startSpec, 8956 unsigned specifierLen, 8957 const char *csStart, unsigned csLen); 8958 8959 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8960 const char *startSpec, 8961 unsigned specifierLen); 8962 8963 SourceRange getFormatStringRange(); 8964 CharSourceRange getSpecifierRange(const char *startSpecifier, 8965 unsigned specifierLen); 8966 SourceLocation getLocationOfByte(const char *x); 8967 8968 const Expr *getDataArg(unsigned i) const; 8969 8970 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8971 const analyze_format_string::ConversionSpecifier &CS, 8972 const char *startSpecifier, unsigned specifierLen, 8973 unsigned argIndex); 8974 8975 template <typename Range> 8976 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8977 bool IsStringLocation, Range StringRange, 8978 ArrayRef<FixItHint> Fixit = None); 8979 }; 8980 8981 } // namespace 8982 8983 SourceRange CheckFormatHandler::getFormatStringRange() { 8984 return OrigFormatExpr->getSourceRange(); 8985 } 8986 8987 CharSourceRange CheckFormatHandler:: 8988 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8989 SourceLocation Start = getLocationOfByte(startSpecifier); 8990 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8991 8992 // Advance the end SourceLocation by one due to half-open ranges. 8993 End = End.getLocWithOffset(1); 8994 8995 return CharSourceRange::getCharRange(Start, End); 8996 } 8997 8998 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8999 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 9000 S.getLangOpts(), S.Context.getTargetInfo()); 9001 } 9002 9003 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 9004 unsigned specifierLen){ 9005 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 9006 getLocationOfByte(startSpecifier), 9007 /*IsStringLocation*/true, 9008 getSpecifierRange(startSpecifier, specifierLen)); 9009 } 9010 9011 void CheckFormatHandler::HandleInvalidLengthModifier( 9012 const analyze_format_string::FormatSpecifier &FS, 9013 const analyze_format_string::ConversionSpecifier &CS, 9014 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 9015 using namespace analyze_format_string; 9016 9017 const LengthModifier &LM = FS.getLengthModifier(); 9018 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 9019 9020 // See if we know how to fix this length modifier. 9021 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 9022 if (FixedLM) { 9023 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 9024 getLocationOfByte(LM.getStart()), 9025 /*IsStringLocation*/true, 9026 getSpecifierRange(startSpecifier, specifierLen)); 9027 9028 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 9029 << FixedLM->toString() 9030 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 9031 9032 } else { 9033 FixItHint Hint; 9034 if (DiagID == diag::warn_format_nonsensical_length) 9035 Hint = FixItHint::CreateRemoval(LMRange); 9036 9037 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 9038 getLocationOfByte(LM.getStart()), 9039 /*IsStringLocation*/true, 9040 getSpecifierRange(startSpecifier, specifierLen), 9041 Hint); 9042 } 9043 } 9044 9045 void CheckFormatHandler::HandleNonStandardLengthModifier( 9046 const analyze_format_string::FormatSpecifier &FS, 9047 const char *startSpecifier, unsigned specifierLen) { 9048 using namespace analyze_format_string; 9049 9050 const LengthModifier &LM = FS.getLengthModifier(); 9051 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 9052 9053 // See if we know how to fix this length modifier. 9054 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 9055 if (FixedLM) { 9056 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 9057 << LM.toString() << 0, 9058 getLocationOfByte(LM.getStart()), 9059 /*IsStringLocation*/true, 9060 getSpecifierRange(startSpecifier, specifierLen)); 9061 9062 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 9063 << FixedLM->toString() 9064 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 9065 9066 } else { 9067 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 9068 << LM.toString() << 0, 9069 getLocationOfByte(LM.getStart()), 9070 /*IsStringLocation*/true, 9071 getSpecifierRange(startSpecifier, specifierLen)); 9072 } 9073 } 9074 9075 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 9076 const analyze_format_string::ConversionSpecifier &CS, 9077 const char *startSpecifier, unsigned specifierLen) { 9078 using namespace analyze_format_string; 9079 9080 // See if we know how to fix this conversion specifier. 9081 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 9082 if (FixedCS) { 9083 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 9084 << CS.toString() << /*conversion specifier*/1, 9085 getLocationOfByte(CS.getStart()), 9086 /*IsStringLocation*/true, 9087 getSpecifierRange(startSpecifier, specifierLen)); 9088 9089 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 9090 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 9091 << FixedCS->toString() 9092 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 9093 } else { 9094 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 9095 << CS.toString() << /*conversion specifier*/1, 9096 getLocationOfByte(CS.getStart()), 9097 /*IsStringLocation*/true, 9098 getSpecifierRange(startSpecifier, specifierLen)); 9099 } 9100 } 9101 9102 void CheckFormatHandler::HandlePosition(const char *startPos, 9103 unsigned posLen) { 9104 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 9105 getLocationOfByte(startPos), 9106 /*IsStringLocation*/true, 9107 getSpecifierRange(startPos, posLen)); 9108 } 9109 9110 void 9111 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 9112 analyze_format_string::PositionContext p) { 9113 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 9114 << (unsigned) p, 9115 getLocationOfByte(startPos), /*IsStringLocation*/true, 9116 getSpecifierRange(startPos, posLen)); 9117 } 9118 9119 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 9120 unsigned posLen) { 9121 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 9122 getLocationOfByte(startPos), 9123 /*IsStringLocation*/true, 9124 getSpecifierRange(startPos, posLen)); 9125 } 9126 9127 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 9128 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 9129 // The presence of a null character is likely an error. 9130 EmitFormatDiagnostic( 9131 S.PDiag(diag::warn_printf_format_string_contains_null_char), 9132 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 9133 getFormatStringRange()); 9134 } 9135 } 9136 9137 // Note that this may return NULL if there was an error parsing or building 9138 // one of the argument expressions. 9139 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 9140 return Args[FirstDataArg + i]; 9141 } 9142 9143 void CheckFormatHandler::DoneProcessing() { 9144 // Does the number of data arguments exceed the number of 9145 // format conversions in the format string? 9146 if (!HasVAListArg) { 9147 // Find any arguments that weren't covered. 9148 CoveredArgs.flip(); 9149 signed notCoveredArg = CoveredArgs.find_first(); 9150 if (notCoveredArg >= 0) { 9151 assert((unsigned)notCoveredArg < NumDataArgs); 9152 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 9153 } else { 9154 UncoveredArg.setAllCovered(); 9155 } 9156 } 9157 } 9158 9159 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 9160 const Expr *ArgExpr) { 9161 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 9162 "Invalid state"); 9163 9164 if (!ArgExpr) 9165 return; 9166 9167 SourceLocation Loc = ArgExpr->getBeginLoc(); 9168 9169 if (S.getSourceManager().isInSystemMacro(Loc)) 9170 return; 9171 9172 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 9173 for (auto E : DiagnosticExprs) 9174 PDiag << E->getSourceRange(); 9175 9176 CheckFormatHandler::EmitFormatDiagnostic( 9177 S, IsFunctionCall, DiagnosticExprs[0], 9178 PDiag, Loc, /*IsStringLocation*/false, 9179 DiagnosticExprs[0]->getSourceRange()); 9180 } 9181 9182 bool 9183 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 9184 SourceLocation Loc, 9185 const char *startSpec, 9186 unsigned specifierLen, 9187 const char *csStart, 9188 unsigned csLen) { 9189 bool keepGoing = true; 9190 if (argIndex < NumDataArgs) { 9191 // Consider the argument coverered, even though the specifier doesn't 9192 // make sense. 9193 CoveredArgs.set(argIndex); 9194 } 9195 else { 9196 // If argIndex exceeds the number of data arguments we 9197 // don't issue a warning because that is just a cascade of warnings (and 9198 // they may have intended '%%' anyway). We don't want to continue processing 9199 // the format string after this point, however, as we will like just get 9200 // gibberish when trying to match arguments. 9201 keepGoing = false; 9202 } 9203 9204 StringRef Specifier(csStart, csLen); 9205 9206 // If the specifier in non-printable, it could be the first byte of a UTF-8 9207 // sequence. In that case, print the UTF-8 code point. If not, print the byte 9208 // hex value. 9209 std::string CodePointStr; 9210 if (!llvm::sys::locale::isPrint(*csStart)) { 9211 llvm::UTF32 CodePoint; 9212 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 9213 const llvm::UTF8 *E = 9214 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 9215 llvm::ConversionResult Result = 9216 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 9217 9218 if (Result != llvm::conversionOK) { 9219 unsigned char FirstChar = *csStart; 9220 CodePoint = (llvm::UTF32)FirstChar; 9221 } 9222 9223 llvm::raw_string_ostream OS(CodePointStr); 9224 if (CodePoint < 256) 9225 OS << "\\x" << llvm::format("%02x", CodePoint); 9226 else if (CodePoint <= 0xFFFF) 9227 OS << "\\u" << llvm::format("%04x", CodePoint); 9228 else 9229 OS << "\\U" << llvm::format("%08x", CodePoint); 9230 OS.flush(); 9231 Specifier = CodePointStr; 9232 } 9233 9234 EmitFormatDiagnostic( 9235 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 9236 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 9237 9238 return keepGoing; 9239 } 9240 9241 void 9242 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 9243 const char *startSpec, 9244 unsigned specifierLen) { 9245 EmitFormatDiagnostic( 9246 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 9247 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 9248 } 9249 9250 bool 9251 CheckFormatHandler::CheckNumArgs( 9252 const analyze_format_string::FormatSpecifier &FS, 9253 const analyze_format_string::ConversionSpecifier &CS, 9254 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 9255 9256 if (argIndex >= NumDataArgs) { 9257 PartialDiagnostic PDiag = FS.usesPositionalArg() 9258 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 9259 << (argIndex+1) << NumDataArgs) 9260 : S.PDiag(diag::warn_printf_insufficient_data_args); 9261 EmitFormatDiagnostic( 9262 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 9263 getSpecifierRange(startSpecifier, specifierLen)); 9264 9265 // Since more arguments than conversion tokens are given, by extension 9266 // all arguments are covered, so mark this as so. 9267 UncoveredArg.setAllCovered(); 9268 return false; 9269 } 9270 return true; 9271 } 9272 9273 template<typename Range> 9274 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 9275 SourceLocation Loc, 9276 bool IsStringLocation, 9277 Range StringRange, 9278 ArrayRef<FixItHint> FixIt) { 9279 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 9280 Loc, IsStringLocation, StringRange, FixIt); 9281 } 9282 9283 /// If the format string is not within the function call, emit a note 9284 /// so that the function call and string are in diagnostic messages. 9285 /// 9286 /// \param InFunctionCall if true, the format string is within the function 9287 /// call and only one diagnostic message will be produced. Otherwise, an 9288 /// extra note will be emitted pointing to location of the format string. 9289 /// 9290 /// \param ArgumentExpr the expression that is passed as the format string 9291 /// argument in the function call. Used for getting locations when two 9292 /// diagnostics are emitted. 9293 /// 9294 /// \param PDiag the callee should already have provided any strings for the 9295 /// diagnostic message. This function only adds locations and fixits 9296 /// to diagnostics. 9297 /// 9298 /// \param Loc primary location for diagnostic. If two diagnostics are 9299 /// required, one will be at Loc and a new SourceLocation will be created for 9300 /// the other one. 9301 /// 9302 /// \param IsStringLocation if true, Loc points to the format string should be 9303 /// used for the note. Otherwise, Loc points to the argument list and will 9304 /// be used with PDiag. 9305 /// 9306 /// \param StringRange some or all of the string to highlight. This is 9307 /// templated so it can accept either a CharSourceRange or a SourceRange. 9308 /// 9309 /// \param FixIt optional fix it hint for the format string. 9310 template <typename Range> 9311 void CheckFormatHandler::EmitFormatDiagnostic( 9312 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 9313 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 9314 Range StringRange, ArrayRef<FixItHint> FixIt) { 9315 if (InFunctionCall) { 9316 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 9317 D << StringRange; 9318 D << FixIt; 9319 } else { 9320 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 9321 << ArgumentExpr->getSourceRange(); 9322 9323 const Sema::SemaDiagnosticBuilder &Note = 9324 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 9325 diag::note_format_string_defined); 9326 9327 Note << StringRange; 9328 Note << FixIt; 9329 } 9330 } 9331 9332 //===--- CHECK: Printf format string checking ------------------------------===// 9333 9334 namespace { 9335 9336 class CheckPrintfHandler : public CheckFormatHandler { 9337 public: 9338 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 9339 const Expr *origFormatExpr, 9340 const Sema::FormatStringType type, unsigned firstDataArg, 9341 unsigned numDataArgs, bool isObjC, const char *beg, 9342 bool hasVAListArg, ArrayRef<const Expr *> Args, 9343 unsigned formatIdx, bool inFunctionCall, 9344 Sema::VariadicCallType CallType, 9345 llvm::SmallBitVector &CheckedVarArgs, 9346 UncoveredArgHandler &UncoveredArg) 9347 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9348 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9349 inFunctionCall, CallType, CheckedVarArgs, 9350 UncoveredArg) {} 9351 9352 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 9353 9354 /// Returns true if '%@' specifiers are allowed in the format string. 9355 bool allowsObjCArg() const { 9356 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 9357 FSType == Sema::FST_OSTrace; 9358 } 9359 9360 bool HandleInvalidPrintfConversionSpecifier( 9361 const analyze_printf::PrintfSpecifier &FS, 9362 const char *startSpecifier, 9363 unsigned specifierLen) override; 9364 9365 void handleInvalidMaskType(StringRef MaskType) override; 9366 9367 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 9368 const char *startSpecifier, unsigned specifierLen, 9369 const TargetInfo &Target) override; 9370 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9371 const char *StartSpecifier, 9372 unsigned SpecifierLen, 9373 const Expr *E); 9374 9375 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 9376 const char *startSpecifier, unsigned specifierLen); 9377 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 9378 const analyze_printf::OptionalAmount &Amt, 9379 unsigned type, 9380 const char *startSpecifier, unsigned specifierLen); 9381 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 9382 const analyze_printf::OptionalFlag &flag, 9383 const char *startSpecifier, unsigned specifierLen); 9384 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 9385 const analyze_printf::OptionalFlag &ignoredFlag, 9386 const analyze_printf::OptionalFlag &flag, 9387 const char *startSpecifier, unsigned specifierLen); 9388 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 9389 const Expr *E); 9390 9391 void HandleEmptyObjCModifierFlag(const char *startFlag, 9392 unsigned flagLen) override; 9393 9394 void HandleInvalidObjCModifierFlag(const char *startFlag, 9395 unsigned flagLen) override; 9396 9397 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 9398 const char *flagsEnd, 9399 const char *conversionPosition) 9400 override; 9401 }; 9402 9403 } // namespace 9404 9405 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 9406 const analyze_printf::PrintfSpecifier &FS, 9407 const char *startSpecifier, 9408 unsigned specifierLen) { 9409 const analyze_printf::PrintfConversionSpecifier &CS = 9410 FS.getConversionSpecifier(); 9411 9412 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9413 getLocationOfByte(CS.getStart()), 9414 startSpecifier, specifierLen, 9415 CS.getStart(), CS.getLength()); 9416 } 9417 9418 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 9419 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 9420 } 9421 9422 bool CheckPrintfHandler::HandleAmount( 9423 const analyze_format_string::OptionalAmount &Amt, 9424 unsigned k, const char *startSpecifier, 9425 unsigned specifierLen) { 9426 if (Amt.hasDataArgument()) { 9427 if (!HasVAListArg) { 9428 unsigned argIndex = Amt.getArgIndex(); 9429 if (argIndex >= NumDataArgs) { 9430 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 9431 << k, 9432 getLocationOfByte(Amt.getStart()), 9433 /*IsStringLocation*/true, 9434 getSpecifierRange(startSpecifier, specifierLen)); 9435 // Don't do any more checking. We will just emit 9436 // spurious errors. 9437 return false; 9438 } 9439 9440 // Type check the data argument. It should be an 'int'. 9441 // Although not in conformance with C99, we also allow the argument to be 9442 // an 'unsigned int' as that is a reasonably safe case. GCC also 9443 // doesn't emit a warning for that case. 9444 CoveredArgs.set(argIndex); 9445 const Expr *Arg = getDataArg(argIndex); 9446 if (!Arg) 9447 return false; 9448 9449 QualType T = Arg->getType(); 9450 9451 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 9452 assert(AT.isValid()); 9453 9454 if (!AT.matchesType(S.Context, T)) { 9455 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 9456 << k << AT.getRepresentativeTypeName(S.Context) 9457 << T << Arg->getSourceRange(), 9458 getLocationOfByte(Amt.getStart()), 9459 /*IsStringLocation*/true, 9460 getSpecifierRange(startSpecifier, specifierLen)); 9461 // Don't do any more checking. We will just emit 9462 // spurious errors. 9463 return false; 9464 } 9465 } 9466 } 9467 return true; 9468 } 9469 9470 void CheckPrintfHandler::HandleInvalidAmount( 9471 const analyze_printf::PrintfSpecifier &FS, 9472 const analyze_printf::OptionalAmount &Amt, 9473 unsigned type, 9474 const char *startSpecifier, 9475 unsigned specifierLen) { 9476 const analyze_printf::PrintfConversionSpecifier &CS = 9477 FS.getConversionSpecifier(); 9478 9479 FixItHint fixit = 9480 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 9481 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 9482 Amt.getConstantLength())) 9483 : FixItHint(); 9484 9485 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 9486 << type << CS.toString(), 9487 getLocationOfByte(Amt.getStart()), 9488 /*IsStringLocation*/true, 9489 getSpecifierRange(startSpecifier, specifierLen), 9490 fixit); 9491 } 9492 9493 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 9494 const analyze_printf::OptionalFlag &flag, 9495 const char *startSpecifier, 9496 unsigned specifierLen) { 9497 // Warn about pointless flag with a fixit removal. 9498 const analyze_printf::PrintfConversionSpecifier &CS = 9499 FS.getConversionSpecifier(); 9500 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 9501 << flag.toString() << CS.toString(), 9502 getLocationOfByte(flag.getPosition()), 9503 /*IsStringLocation*/true, 9504 getSpecifierRange(startSpecifier, specifierLen), 9505 FixItHint::CreateRemoval( 9506 getSpecifierRange(flag.getPosition(), 1))); 9507 } 9508 9509 void CheckPrintfHandler::HandleIgnoredFlag( 9510 const analyze_printf::PrintfSpecifier &FS, 9511 const analyze_printf::OptionalFlag &ignoredFlag, 9512 const analyze_printf::OptionalFlag &flag, 9513 const char *startSpecifier, 9514 unsigned specifierLen) { 9515 // Warn about ignored flag with a fixit removal. 9516 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 9517 << ignoredFlag.toString() << flag.toString(), 9518 getLocationOfByte(ignoredFlag.getPosition()), 9519 /*IsStringLocation*/true, 9520 getSpecifierRange(startSpecifier, specifierLen), 9521 FixItHint::CreateRemoval( 9522 getSpecifierRange(ignoredFlag.getPosition(), 1))); 9523 } 9524 9525 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 9526 unsigned flagLen) { 9527 // Warn about an empty flag. 9528 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 9529 getLocationOfByte(startFlag), 9530 /*IsStringLocation*/true, 9531 getSpecifierRange(startFlag, flagLen)); 9532 } 9533 9534 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 9535 unsigned flagLen) { 9536 // Warn about an invalid flag. 9537 auto Range = getSpecifierRange(startFlag, flagLen); 9538 StringRef flag(startFlag, flagLen); 9539 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 9540 getLocationOfByte(startFlag), 9541 /*IsStringLocation*/true, 9542 Range, FixItHint::CreateRemoval(Range)); 9543 } 9544 9545 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 9546 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 9547 // Warn about using '[...]' without a '@' conversion. 9548 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 9549 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 9550 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 9551 getLocationOfByte(conversionPosition), 9552 /*IsStringLocation*/true, 9553 Range, FixItHint::CreateRemoval(Range)); 9554 } 9555 9556 // Determines if the specified is a C++ class or struct containing 9557 // a member with the specified name and kind (e.g. a CXXMethodDecl named 9558 // "c_str()"). 9559 template<typename MemberKind> 9560 static llvm::SmallPtrSet<MemberKind*, 1> 9561 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 9562 const RecordType *RT = Ty->getAs<RecordType>(); 9563 llvm::SmallPtrSet<MemberKind*, 1> Results; 9564 9565 if (!RT) 9566 return Results; 9567 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 9568 if (!RD || !RD->getDefinition()) 9569 return Results; 9570 9571 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 9572 Sema::LookupMemberName); 9573 R.suppressDiagnostics(); 9574 9575 // We just need to include all members of the right kind turned up by the 9576 // filter, at this point. 9577 if (S.LookupQualifiedName(R, RT->getDecl())) 9578 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9579 NamedDecl *decl = (*I)->getUnderlyingDecl(); 9580 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 9581 Results.insert(FK); 9582 } 9583 return Results; 9584 } 9585 9586 /// Check if we could call '.c_str()' on an object. 9587 /// 9588 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 9589 /// allow the call, or if it would be ambiguous). 9590 bool Sema::hasCStrMethod(const Expr *E) { 9591 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 9592 9593 MethodSet Results = 9594 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 9595 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9596 MI != ME; ++MI) 9597 if ((*MI)->getMinRequiredArguments() == 0) 9598 return true; 9599 return false; 9600 } 9601 9602 // Check if a (w)string was passed when a (w)char* was needed, and offer a 9603 // better diagnostic if so. AT is assumed to be valid. 9604 // Returns true when a c_str() conversion method is found. 9605 bool CheckPrintfHandler::checkForCStrMembers( 9606 const analyze_printf::ArgType &AT, const Expr *E) { 9607 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 9608 9609 MethodSet Results = 9610 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 9611 9612 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9613 MI != ME; ++MI) { 9614 const CXXMethodDecl *Method = *MI; 9615 if (Method->getMinRequiredArguments() == 0 && 9616 AT.matchesType(S.Context, Method->getReturnType())) { 9617 // FIXME: Suggest parens if the expression needs them. 9618 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 9619 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 9620 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 9621 return true; 9622 } 9623 } 9624 9625 return false; 9626 } 9627 9628 bool CheckPrintfHandler::HandlePrintfSpecifier( 9629 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier, 9630 unsigned specifierLen, const TargetInfo &Target) { 9631 using namespace analyze_format_string; 9632 using namespace analyze_printf; 9633 9634 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 9635 9636 if (FS.consumesDataArgument()) { 9637 if (atFirstArg) { 9638 atFirstArg = false; 9639 usesPositionalArgs = FS.usesPositionalArg(); 9640 } 9641 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9642 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9643 startSpecifier, specifierLen); 9644 return false; 9645 } 9646 } 9647 9648 // First check if the field width, precision, and conversion specifier 9649 // have matching data arguments. 9650 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 9651 startSpecifier, specifierLen)) { 9652 return false; 9653 } 9654 9655 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 9656 startSpecifier, specifierLen)) { 9657 return false; 9658 } 9659 9660 if (!CS.consumesDataArgument()) { 9661 // FIXME: Technically specifying a precision or field width here 9662 // makes no sense. Worth issuing a warning at some point. 9663 return true; 9664 } 9665 9666 // Consume the argument. 9667 unsigned argIndex = FS.getArgIndex(); 9668 if (argIndex < NumDataArgs) { 9669 // The check to see if the argIndex is valid will come later. 9670 // We set the bit here because we may exit early from this 9671 // function if we encounter some other error. 9672 CoveredArgs.set(argIndex); 9673 } 9674 9675 // FreeBSD kernel extensions. 9676 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 9677 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 9678 // We need at least two arguments. 9679 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 9680 return false; 9681 9682 // Claim the second argument. 9683 CoveredArgs.set(argIndex + 1); 9684 9685 // Type check the first argument (int for %b, pointer for %D) 9686 const Expr *Ex = getDataArg(argIndex); 9687 const analyze_printf::ArgType &AT = 9688 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 9689 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 9690 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 9691 EmitFormatDiagnostic( 9692 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9693 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 9694 << false << Ex->getSourceRange(), 9695 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9696 getSpecifierRange(startSpecifier, specifierLen)); 9697 9698 // Type check the second argument (char * for both %b and %D) 9699 Ex = getDataArg(argIndex + 1); 9700 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 9701 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 9702 EmitFormatDiagnostic( 9703 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9704 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 9705 << false << Ex->getSourceRange(), 9706 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9707 getSpecifierRange(startSpecifier, specifierLen)); 9708 9709 return true; 9710 } 9711 9712 // Check for using an Objective-C specific conversion specifier 9713 // in a non-ObjC literal. 9714 if (!allowsObjCArg() && CS.isObjCArg()) { 9715 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9716 specifierLen); 9717 } 9718 9719 // %P can only be used with os_log. 9720 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 9721 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9722 specifierLen); 9723 } 9724 9725 // %n is not allowed with os_log. 9726 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9727 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9728 getLocationOfByte(CS.getStart()), 9729 /*IsStringLocation*/ false, 9730 getSpecifierRange(startSpecifier, specifierLen)); 9731 9732 return true; 9733 } 9734 9735 // Only scalars are allowed for os_trace. 9736 if (FSType == Sema::FST_OSTrace && 9737 (CS.getKind() == ConversionSpecifier::PArg || 9738 CS.getKind() == ConversionSpecifier::sArg || 9739 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9740 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9741 specifierLen); 9742 } 9743 9744 // Check for use of public/private annotation outside of os_log(). 9745 if (FSType != Sema::FST_OSLog) { 9746 if (FS.isPublic().isSet()) { 9747 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9748 << "public", 9749 getLocationOfByte(FS.isPublic().getPosition()), 9750 /*IsStringLocation*/ false, 9751 getSpecifierRange(startSpecifier, specifierLen)); 9752 } 9753 if (FS.isPrivate().isSet()) { 9754 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9755 << "private", 9756 getLocationOfByte(FS.isPrivate().getPosition()), 9757 /*IsStringLocation*/ false, 9758 getSpecifierRange(startSpecifier, specifierLen)); 9759 } 9760 } 9761 9762 const llvm::Triple &Triple = Target.getTriple(); 9763 if (CS.getKind() == ConversionSpecifier::nArg && 9764 (Triple.isAndroid() || Triple.isOSFuchsia())) { 9765 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported), 9766 getLocationOfByte(CS.getStart()), 9767 /*IsStringLocation*/ false, 9768 getSpecifierRange(startSpecifier, specifierLen)); 9769 } 9770 9771 // Check for invalid use of field width 9772 if (!FS.hasValidFieldWidth()) { 9773 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9774 startSpecifier, specifierLen); 9775 } 9776 9777 // Check for invalid use of precision 9778 if (!FS.hasValidPrecision()) { 9779 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9780 startSpecifier, specifierLen); 9781 } 9782 9783 // Precision is mandatory for %P specifier. 9784 if (CS.getKind() == ConversionSpecifier::PArg && 9785 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9786 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9787 getLocationOfByte(startSpecifier), 9788 /*IsStringLocation*/ false, 9789 getSpecifierRange(startSpecifier, specifierLen)); 9790 } 9791 9792 // Check each flag does not conflict with any other component. 9793 if (!FS.hasValidThousandsGroupingPrefix()) 9794 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9795 if (!FS.hasValidLeadingZeros()) 9796 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9797 if (!FS.hasValidPlusPrefix()) 9798 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9799 if (!FS.hasValidSpacePrefix()) 9800 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9801 if (!FS.hasValidAlternativeForm()) 9802 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9803 if (!FS.hasValidLeftJustified()) 9804 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9805 9806 // Check that flags are not ignored by another flag 9807 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9808 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9809 startSpecifier, specifierLen); 9810 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9811 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9812 startSpecifier, specifierLen); 9813 9814 // Check the length modifier is valid with the given conversion specifier. 9815 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9816 S.getLangOpts())) 9817 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9818 diag::warn_format_nonsensical_length); 9819 else if (!FS.hasStandardLengthModifier()) 9820 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9821 else if (!FS.hasStandardLengthConversionCombination()) 9822 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9823 diag::warn_format_non_standard_conversion_spec); 9824 9825 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9826 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9827 9828 // The remaining checks depend on the data arguments. 9829 if (HasVAListArg) 9830 return true; 9831 9832 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9833 return false; 9834 9835 const Expr *Arg = getDataArg(argIndex); 9836 if (!Arg) 9837 return true; 9838 9839 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9840 } 9841 9842 static bool requiresParensToAddCast(const Expr *E) { 9843 // FIXME: We should have a general way to reason about operator 9844 // precedence and whether parens are actually needed here. 9845 // Take care of a few common cases where they aren't. 9846 const Expr *Inside = E->IgnoreImpCasts(); 9847 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9848 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9849 9850 switch (Inside->getStmtClass()) { 9851 case Stmt::ArraySubscriptExprClass: 9852 case Stmt::CallExprClass: 9853 case Stmt::CharacterLiteralClass: 9854 case Stmt::CXXBoolLiteralExprClass: 9855 case Stmt::DeclRefExprClass: 9856 case Stmt::FloatingLiteralClass: 9857 case Stmt::IntegerLiteralClass: 9858 case Stmt::MemberExprClass: 9859 case Stmt::ObjCArrayLiteralClass: 9860 case Stmt::ObjCBoolLiteralExprClass: 9861 case Stmt::ObjCBoxedExprClass: 9862 case Stmt::ObjCDictionaryLiteralClass: 9863 case Stmt::ObjCEncodeExprClass: 9864 case Stmt::ObjCIvarRefExprClass: 9865 case Stmt::ObjCMessageExprClass: 9866 case Stmt::ObjCPropertyRefExprClass: 9867 case Stmt::ObjCStringLiteralClass: 9868 case Stmt::ObjCSubscriptRefExprClass: 9869 case Stmt::ParenExprClass: 9870 case Stmt::StringLiteralClass: 9871 case Stmt::UnaryOperatorClass: 9872 return false; 9873 default: 9874 return true; 9875 } 9876 } 9877 9878 static std::pair<QualType, StringRef> 9879 shouldNotPrintDirectly(const ASTContext &Context, 9880 QualType IntendedTy, 9881 const Expr *E) { 9882 // Use a 'while' to peel off layers of typedefs. 9883 QualType TyTy = IntendedTy; 9884 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9885 StringRef Name = UserTy->getDecl()->getName(); 9886 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9887 .Case("CFIndex", Context.getNSIntegerType()) 9888 .Case("NSInteger", Context.getNSIntegerType()) 9889 .Case("NSUInteger", Context.getNSUIntegerType()) 9890 .Case("SInt32", Context.IntTy) 9891 .Case("UInt32", Context.UnsignedIntTy) 9892 .Default(QualType()); 9893 9894 if (!CastTy.isNull()) 9895 return std::make_pair(CastTy, Name); 9896 9897 TyTy = UserTy->desugar(); 9898 } 9899 9900 // Strip parens if necessary. 9901 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9902 return shouldNotPrintDirectly(Context, 9903 PE->getSubExpr()->getType(), 9904 PE->getSubExpr()); 9905 9906 // If this is a conditional expression, then its result type is constructed 9907 // via usual arithmetic conversions and thus there might be no necessary 9908 // typedef sugar there. Recurse to operands to check for NSInteger & 9909 // Co. usage condition. 9910 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9911 QualType TrueTy, FalseTy; 9912 StringRef TrueName, FalseName; 9913 9914 std::tie(TrueTy, TrueName) = 9915 shouldNotPrintDirectly(Context, 9916 CO->getTrueExpr()->getType(), 9917 CO->getTrueExpr()); 9918 std::tie(FalseTy, FalseName) = 9919 shouldNotPrintDirectly(Context, 9920 CO->getFalseExpr()->getType(), 9921 CO->getFalseExpr()); 9922 9923 if (TrueTy == FalseTy) 9924 return std::make_pair(TrueTy, TrueName); 9925 else if (TrueTy.isNull()) 9926 return std::make_pair(FalseTy, FalseName); 9927 else if (FalseTy.isNull()) 9928 return std::make_pair(TrueTy, TrueName); 9929 } 9930 9931 return std::make_pair(QualType(), StringRef()); 9932 } 9933 9934 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9935 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9936 /// type do not count. 9937 static bool 9938 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9939 QualType From = ICE->getSubExpr()->getType(); 9940 QualType To = ICE->getType(); 9941 // It's an integer promotion if the destination type is the promoted 9942 // source type. 9943 if (ICE->getCastKind() == CK_IntegralCast && 9944 From->isPromotableIntegerType() && 9945 S.Context.getPromotedIntegerType(From) == To) 9946 return true; 9947 // Look through vector types, since we do default argument promotion for 9948 // those in OpenCL. 9949 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9950 From = VecTy->getElementType(); 9951 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9952 To = VecTy->getElementType(); 9953 // It's a floating promotion if the source type is a lower rank. 9954 return ICE->getCastKind() == CK_FloatingCast && 9955 S.Context.getFloatingTypeOrder(From, To) < 0; 9956 } 9957 9958 bool 9959 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9960 const char *StartSpecifier, 9961 unsigned SpecifierLen, 9962 const Expr *E) { 9963 using namespace analyze_format_string; 9964 using namespace analyze_printf; 9965 9966 // Now type check the data expression that matches the 9967 // format specifier. 9968 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9969 if (!AT.isValid()) 9970 return true; 9971 9972 QualType ExprTy = E->getType(); 9973 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9974 ExprTy = TET->getUnderlyingExpr()->getType(); 9975 } 9976 9977 // Diagnose attempts to print a boolean value as a character. Unlike other 9978 // -Wformat diagnostics, this is fine from a type perspective, but it still 9979 // doesn't make sense. 9980 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9981 E->isKnownToHaveBooleanValue()) { 9982 const CharSourceRange &CSR = 9983 getSpecifierRange(StartSpecifier, SpecifierLen); 9984 SmallString<4> FSString; 9985 llvm::raw_svector_ostream os(FSString); 9986 FS.toString(os); 9987 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9988 << FSString, 9989 E->getExprLoc(), false, CSR); 9990 return true; 9991 } 9992 9993 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9994 if (Match == analyze_printf::ArgType::Match) 9995 return true; 9996 9997 // Look through argument promotions for our error message's reported type. 9998 // This includes the integral and floating promotions, but excludes array 9999 // and function pointer decay (seeing that an argument intended to be a 10000 // string has type 'char [6]' is probably more confusing than 'char *') and 10001 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 10002 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10003 if (isArithmeticArgumentPromotion(S, ICE)) { 10004 E = ICE->getSubExpr(); 10005 ExprTy = E->getType(); 10006 10007 // Check if we didn't match because of an implicit cast from a 'char' 10008 // or 'short' to an 'int'. This is done because printf is a varargs 10009 // function. 10010 if (ICE->getType() == S.Context.IntTy || 10011 ICE->getType() == S.Context.UnsignedIntTy) { 10012 // All further checking is done on the subexpression 10013 const analyze_printf::ArgType::MatchKind ImplicitMatch = 10014 AT.matchesType(S.Context, ExprTy); 10015 if (ImplicitMatch == analyze_printf::ArgType::Match) 10016 return true; 10017 if (ImplicitMatch == ArgType::NoMatchPedantic || 10018 ImplicitMatch == ArgType::NoMatchTypeConfusion) 10019 Match = ImplicitMatch; 10020 } 10021 } 10022 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 10023 // Special case for 'a', which has type 'int' in C. 10024 // Note, however, that we do /not/ want to treat multibyte constants like 10025 // 'MooV' as characters! This form is deprecated but still exists. In 10026 // addition, don't treat expressions as of type 'char' if one byte length 10027 // modifier is provided. 10028 if (ExprTy == S.Context.IntTy && 10029 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 10030 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 10031 ExprTy = S.Context.CharTy; 10032 } 10033 10034 // Look through enums to their underlying type. 10035 bool IsEnum = false; 10036 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 10037 ExprTy = EnumTy->getDecl()->getIntegerType(); 10038 IsEnum = true; 10039 } 10040 10041 // %C in an Objective-C context prints a unichar, not a wchar_t. 10042 // If the argument is an integer of some kind, believe the %C and suggest 10043 // a cast instead of changing the conversion specifier. 10044 QualType IntendedTy = ExprTy; 10045 if (isObjCContext() && 10046 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 10047 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 10048 !ExprTy->isCharType()) { 10049 // 'unichar' is defined as a typedef of unsigned short, but we should 10050 // prefer using the typedef if it is visible. 10051 IntendedTy = S.Context.UnsignedShortTy; 10052 10053 // While we are here, check if the value is an IntegerLiteral that happens 10054 // to be within the valid range. 10055 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 10056 const llvm::APInt &V = IL->getValue(); 10057 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 10058 return true; 10059 } 10060 10061 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 10062 Sema::LookupOrdinaryName); 10063 if (S.LookupName(Result, S.getCurScope())) { 10064 NamedDecl *ND = Result.getFoundDecl(); 10065 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 10066 if (TD->getUnderlyingType() == IntendedTy) 10067 IntendedTy = S.Context.getTypedefType(TD); 10068 } 10069 } 10070 } 10071 10072 // Special-case some of Darwin's platform-independence types by suggesting 10073 // casts to primitive types that are known to be large enough. 10074 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 10075 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 10076 QualType CastTy; 10077 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 10078 if (!CastTy.isNull()) { 10079 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 10080 // (long in ASTContext). Only complain to pedants. 10081 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 10082 (AT.isSizeT() || AT.isPtrdiffT()) && 10083 AT.matchesType(S.Context, CastTy)) 10084 Match = ArgType::NoMatchPedantic; 10085 IntendedTy = CastTy; 10086 ShouldNotPrintDirectly = true; 10087 } 10088 } 10089 10090 // We may be able to offer a FixItHint if it is a supported type. 10091 PrintfSpecifier fixedFS = FS; 10092 bool Success = 10093 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 10094 10095 if (Success) { 10096 // Get the fix string from the fixed format specifier 10097 SmallString<16> buf; 10098 llvm::raw_svector_ostream os(buf); 10099 fixedFS.toString(os); 10100 10101 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 10102 10103 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 10104 unsigned Diag; 10105 switch (Match) { 10106 case ArgType::Match: llvm_unreachable("expected non-matching"); 10107 case ArgType::NoMatchPedantic: 10108 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 10109 break; 10110 case ArgType::NoMatchTypeConfusion: 10111 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 10112 break; 10113 case ArgType::NoMatch: 10114 Diag = diag::warn_format_conversion_argument_type_mismatch; 10115 break; 10116 } 10117 10118 // In this case, the specifier is wrong and should be changed to match 10119 // the argument. 10120 EmitFormatDiagnostic(S.PDiag(Diag) 10121 << AT.getRepresentativeTypeName(S.Context) 10122 << IntendedTy << IsEnum << E->getSourceRange(), 10123 E->getBeginLoc(), 10124 /*IsStringLocation*/ false, SpecRange, 10125 FixItHint::CreateReplacement(SpecRange, os.str())); 10126 } else { 10127 // The canonical type for formatting this value is different from the 10128 // actual type of the expression. (This occurs, for example, with Darwin's 10129 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 10130 // should be printed as 'long' for 64-bit compatibility.) 10131 // Rather than emitting a normal format/argument mismatch, we want to 10132 // add a cast to the recommended type (and correct the format string 10133 // if necessary). 10134 SmallString<16> CastBuf; 10135 llvm::raw_svector_ostream CastFix(CastBuf); 10136 CastFix << "("; 10137 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 10138 CastFix << ")"; 10139 10140 SmallVector<FixItHint,4> Hints; 10141 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 10142 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 10143 10144 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 10145 // If there's already a cast present, just replace it. 10146 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 10147 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 10148 10149 } else if (!requiresParensToAddCast(E)) { 10150 // If the expression has high enough precedence, 10151 // just write the C-style cast. 10152 Hints.push_back( 10153 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 10154 } else { 10155 // Otherwise, add parens around the expression as well as the cast. 10156 CastFix << "("; 10157 Hints.push_back( 10158 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 10159 10160 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 10161 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 10162 } 10163 10164 if (ShouldNotPrintDirectly) { 10165 // The expression has a type that should not be printed directly. 10166 // We extract the name from the typedef because we don't want to show 10167 // the underlying type in the diagnostic. 10168 StringRef Name; 10169 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 10170 Name = TypedefTy->getDecl()->getName(); 10171 else 10172 Name = CastTyName; 10173 unsigned Diag = Match == ArgType::NoMatchPedantic 10174 ? diag::warn_format_argument_needs_cast_pedantic 10175 : diag::warn_format_argument_needs_cast; 10176 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 10177 << E->getSourceRange(), 10178 E->getBeginLoc(), /*IsStringLocation=*/false, 10179 SpecRange, Hints); 10180 } else { 10181 // In this case, the expression could be printed using a different 10182 // specifier, but we've decided that the specifier is probably correct 10183 // and we should cast instead. Just use the normal warning message. 10184 EmitFormatDiagnostic( 10185 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 10186 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 10187 << E->getSourceRange(), 10188 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 10189 } 10190 } 10191 } else { 10192 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 10193 SpecifierLen); 10194 // Since the warning for passing non-POD types to variadic functions 10195 // was deferred until now, we emit a warning for non-POD 10196 // arguments here. 10197 switch (S.isValidVarArgType(ExprTy)) { 10198 case Sema::VAK_Valid: 10199 case Sema::VAK_ValidInCXX11: { 10200 unsigned Diag; 10201 switch (Match) { 10202 case ArgType::Match: llvm_unreachable("expected non-matching"); 10203 case ArgType::NoMatchPedantic: 10204 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 10205 break; 10206 case ArgType::NoMatchTypeConfusion: 10207 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 10208 break; 10209 case ArgType::NoMatch: 10210 Diag = diag::warn_format_conversion_argument_type_mismatch; 10211 break; 10212 } 10213 10214 EmitFormatDiagnostic( 10215 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 10216 << IsEnum << CSR << E->getSourceRange(), 10217 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 10218 break; 10219 } 10220 case Sema::VAK_Undefined: 10221 case Sema::VAK_MSVCUndefined: 10222 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 10223 << S.getLangOpts().CPlusPlus11 << ExprTy 10224 << CallType 10225 << AT.getRepresentativeTypeName(S.Context) << CSR 10226 << E->getSourceRange(), 10227 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 10228 checkForCStrMembers(AT, E); 10229 break; 10230 10231 case Sema::VAK_Invalid: 10232 if (ExprTy->isObjCObjectType()) 10233 EmitFormatDiagnostic( 10234 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 10235 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 10236 << AT.getRepresentativeTypeName(S.Context) << CSR 10237 << E->getSourceRange(), 10238 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 10239 else 10240 // FIXME: If this is an initializer list, suggest removing the braces 10241 // or inserting a cast to the target type. 10242 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 10243 << isa<InitListExpr>(E) << ExprTy << CallType 10244 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 10245 break; 10246 } 10247 10248 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 10249 "format string specifier index out of range"); 10250 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 10251 } 10252 10253 return true; 10254 } 10255 10256 //===--- CHECK: Scanf format string checking ------------------------------===// 10257 10258 namespace { 10259 10260 class CheckScanfHandler : public CheckFormatHandler { 10261 public: 10262 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 10263 const Expr *origFormatExpr, Sema::FormatStringType type, 10264 unsigned firstDataArg, unsigned numDataArgs, 10265 const char *beg, bool hasVAListArg, 10266 ArrayRef<const Expr *> Args, unsigned formatIdx, 10267 bool inFunctionCall, Sema::VariadicCallType CallType, 10268 llvm::SmallBitVector &CheckedVarArgs, 10269 UncoveredArgHandler &UncoveredArg) 10270 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 10271 numDataArgs, beg, hasVAListArg, Args, formatIdx, 10272 inFunctionCall, CallType, CheckedVarArgs, 10273 UncoveredArg) {} 10274 10275 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 10276 const char *startSpecifier, 10277 unsigned specifierLen) override; 10278 10279 bool HandleInvalidScanfConversionSpecifier( 10280 const analyze_scanf::ScanfSpecifier &FS, 10281 const char *startSpecifier, 10282 unsigned specifierLen) override; 10283 10284 void HandleIncompleteScanList(const char *start, const char *end) override; 10285 }; 10286 10287 } // namespace 10288 10289 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 10290 const char *end) { 10291 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 10292 getLocationOfByte(end), /*IsStringLocation*/true, 10293 getSpecifierRange(start, end - start)); 10294 } 10295 10296 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 10297 const analyze_scanf::ScanfSpecifier &FS, 10298 const char *startSpecifier, 10299 unsigned specifierLen) { 10300 const analyze_scanf::ScanfConversionSpecifier &CS = 10301 FS.getConversionSpecifier(); 10302 10303 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 10304 getLocationOfByte(CS.getStart()), 10305 startSpecifier, specifierLen, 10306 CS.getStart(), CS.getLength()); 10307 } 10308 10309 bool CheckScanfHandler::HandleScanfSpecifier( 10310 const analyze_scanf::ScanfSpecifier &FS, 10311 const char *startSpecifier, 10312 unsigned specifierLen) { 10313 using namespace analyze_scanf; 10314 using namespace analyze_format_string; 10315 10316 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 10317 10318 // Handle case where '%' and '*' don't consume an argument. These shouldn't 10319 // be used to decide if we are using positional arguments consistently. 10320 if (FS.consumesDataArgument()) { 10321 if (atFirstArg) { 10322 atFirstArg = false; 10323 usesPositionalArgs = FS.usesPositionalArg(); 10324 } 10325 else if (usesPositionalArgs != FS.usesPositionalArg()) { 10326 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 10327 startSpecifier, specifierLen); 10328 return false; 10329 } 10330 } 10331 10332 // Check if the field with is non-zero. 10333 const OptionalAmount &Amt = FS.getFieldWidth(); 10334 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 10335 if (Amt.getConstantAmount() == 0) { 10336 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 10337 Amt.getConstantLength()); 10338 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 10339 getLocationOfByte(Amt.getStart()), 10340 /*IsStringLocation*/true, R, 10341 FixItHint::CreateRemoval(R)); 10342 } 10343 } 10344 10345 if (!FS.consumesDataArgument()) { 10346 // FIXME: Technically specifying a precision or field width here 10347 // makes no sense. Worth issuing a warning at some point. 10348 return true; 10349 } 10350 10351 // Consume the argument. 10352 unsigned argIndex = FS.getArgIndex(); 10353 if (argIndex < NumDataArgs) { 10354 // The check to see if the argIndex is valid will come later. 10355 // We set the bit here because we may exit early from this 10356 // function if we encounter some other error. 10357 CoveredArgs.set(argIndex); 10358 } 10359 10360 // Check the length modifier is valid with the given conversion specifier. 10361 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 10362 S.getLangOpts())) 10363 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 10364 diag::warn_format_nonsensical_length); 10365 else if (!FS.hasStandardLengthModifier()) 10366 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 10367 else if (!FS.hasStandardLengthConversionCombination()) 10368 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 10369 diag::warn_format_non_standard_conversion_spec); 10370 10371 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 10372 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 10373 10374 // The remaining checks depend on the data arguments. 10375 if (HasVAListArg) 10376 return true; 10377 10378 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 10379 return false; 10380 10381 // Check that the argument type matches the format specifier. 10382 const Expr *Ex = getDataArg(argIndex); 10383 if (!Ex) 10384 return true; 10385 10386 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 10387 10388 if (!AT.isValid()) { 10389 return true; 10390 } 10391 10392 analyze_format_string::ArgType::MatchKind Match = 10393 AT.matchesType(S.Context, Ex->getType()); 10394 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 10395 if (Match == analyze_format_string::ArgType::Match) 10396 return true; 10397 10398 ScanfSpecifier fixedFS = FS; 10399 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 10400 S.getLangOpts(), S.Context); 10401 10402 unsigned Diag = 10403 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 10404 : diag::warn_format_conversion_argument_type_mismatch; 10405 10406 if (Success) { 10407 // Get the fix string from the fixed format specifier. 10408 SmallString<128> buf; 10409 llvm::raw_svector_ostream os(buf); 10410 fixedFS.toString(os); 10411 10412 EmitFormatDiagnostic( 10413 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 10414 << Ex->getType() << false << Ex->getSourceRange(), 10415 Ex->getBeginLoc(), 10416 /*IsStringLocation*/ false, 10417 getSpecifierRange(startSpecifier, specifierLen), 10418 FixItHint::CreateReplacement( 10419 getSpecifierRange(startSpecifier, specifierLen), os.str())); 10420 } else { 10421 EmitFormatDiagnostic(S.PDiag(Diag) 10422 << AT.getRepresentativeTypeName(S.Context) 10423 << Ex->getType() << false << Ex->getSourceRange(), 10424 Ex->getBeginLoc(), 10425 /*IsStringLocation*/ false, 10426 getSpecifierRange(startSpecifier, specifierLen)); 10427 } 10428 10429 return true; 10430 } 10431 10432 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 10433 const Expr *OrigFormatExpr, 10434 ArrayRef<const Expr *> Args, 10435 bool HasVAListArg, unsigned format_idx, 10436 unsigned firstDataArg, 10437 Sema::FormatStringType Type, 10438 bool inFunctionCall, 10439 Sema::VariadicCallType CallType, 10440 llvm::SmallBitVector &CheckedVarArgs, 10441 UncoveredArgHandler &UncoveredArg, 10442 bool IgnoreStringsWithoutSpecifiers) { 10443 // CHECK: is the format string a wide literal? 10444 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 10445 CheckFormatHandler::EmitFormatDiagnostic( 10446 S, inFunctionCall, Args[format_idx], 10447 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 10448 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 10449 return; 10450 } 10451 10452 // Str - The format string. NOTE: this is NOT null-terminated! 10453 StringRef StrRef = FExpr->getString(); 10454 const char *Str = StrRef.data(); 10455 // Account for cases where the string literal is truncated in a declaration. 10456 const ConstantArrayType *T = 10457 S.Context.getAsConstantArrayType(FExpr->getType()); 10458 assert(T && "String literal not of constant array type!"); 10459 size_t TypeSize = T->getSize().getZExtValue(); 10460 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 10461 const unsigned numDataArgs = Args.size() - firstDataArg; 10462 10463 if (IgnoreStringsWithoutSpecifiers && 10464 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 10465 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 10466 return; 10467 10468 // Emit a warning if the string literal is truncated and does not contain an 10469 // embedded null character. 10470 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 10471 CheckFormatHandler::EmitFormatDiagnostic( 10472 S, inFunctionCall, Args[format_idx], 10473 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 10474 FExpr->getBeginLoc(), 10475 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 10476 return; 10477 } 10478 10479 // CHECK: empty format string? 10480 if (StrLen == 0 && numDataArgs > 0) { 10481 CheckFormatHandler::EmitFormatDiagnostic( 10482 S, inFunctionCall, Args[format_idx], 10483 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 10484 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 10485 return; 10486 } 10487 10488 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 10489 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 10490 Type == Sema::FST_OSTrace) { 10491 CheckPrintfHandler H( 10492 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 10493 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 10494 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 10495 CheckedVarArgs, UncoveredArg); 10496 10497 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 10498 S.getLangOpts(), 10499 S.Context.getTargetInfo(), 10500 Type == Sema::FST_FreeBSDKPrintf)) 10501 H.DoneProcessing(); 10502 } else if (Type == Sema::FST_Scanf) { 10503 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 10504 numDataArgs, Str, HasVAListArg, Args, format_idx, 10505 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 10506 10507 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 10508 S.getLangOpts(), 10509 S.Context.getTargetInfo())) 10510 H.DoneProcessing(); 10511 } // TODO: handle other formats 10512 } 10513 10514 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 10515 // Str - The format string. NOTE: this is NOT null-terminated! 10516 StringRef StrRef = FExpr->getString(); 10517 const char *Str = StrRef.data(); 10518 // Account for cases where the string literal is truncated in a declaration. 10519 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 10520 assert(T && "String literal not of constant array type!"); 10521 size_t TypeSize = T->getSize().getZExtValue(); 10522 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 10523 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 10524 getLangOpts(), 10525 Context.getTargetInfo()); 10526 } 10527 10528 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 10529 10530 // Returns the related absolute value function that is larger, of 0 if one 10531 // does not exist. 10532 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 10533 switch (AbsFunction) { 10534 default: 10535 return 0; 10536 10537 case Builtin::BI__builtin_abs: 10538 return Builtin::BI__builtin_labs; 10539 case Builtin::BI__builtin_labs: 10540 return Builtin::BI__builtin_llabs; 10541 case Builtin::BI__builtin_llabs: 10542 return 0; 10543 10544 case Builtin::BI__builtin_fabsf: 10545 return Builtin::BI__builtin_fabs; 10546 case Builtin::BI__builtin_fabs: 10547 return Builtin::BI__builtin_fabsl; 10548 case Builtin::BI__builtin_fabsl: 10549 return 0; 10550 10551 case Builtin::BI__builtin_cabsf: 10552 return Builtin::BI__builtin_cabs; 10553 case Builtin::BI__builtin_cabs: 10554 return Builtin::BI__builtin_cabsl; 10555 case Builtin::BI__builtin_cabsl: 10556 return 0; 10557 10558 case Builtin::BIabs: 10559 return Builtin::BIlabs; 10560 case Builtin::BIlabs: 10561 return Builtin::BIllabs; 10562 case Builtin::BIllabs: 10563 return 0; 10564 10565 case Builtin::BIfabsf: 10566 return Builtin::BIfabs; 10567 case Builtin::BIfabs: 10568 return Builtin::BIfabsl; 10569 case Builtin::BIfabsl: 10570 return 0; 10571 10572 case Builtin::BIcabsf: 10573 return Builtin::BIcabs; 10574 case Builtin::BIcabs: 10575 return Builtin::BIcabsl; 10576 case Builtin::BIcabsl: 10577 return 0; 10578 } 10579 } 10580 10581 // Returns the argument type of the absolute value function. 10582 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 10583 unsigned AbsType) { 10584 if (AbsType == 0) 10585 return QualType(); 10586 10587 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 10588 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 10589 if (Error != ASTContext::GE_None) 10590 return QualType(); 10591 10592 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 10593 if (!FT) 10594 return QualType(); 10595 10596 if (FT->getNumParams() != 1) 10597 return QualType(); 10598 10599 return FT->getParamType(0); 10600 } 10601 10602 // Returns the best absolute value function, or zero, based on type and 10603 // current absolute value function. 10604 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 10605 unsigned AbsFunctionKind) { 10606 unsigned BestKind = 0; 10607 uint64_t ArgSize = Context.getTypeSize(ArgType); 10608 for (unsigned Kind = AbsFunctionKind; Kind != 0; 10609 Kind = getLargerAbsoluteValueFunction(Kind)) { 10610 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 10611 if (Context.getTypeSize(ParamType) >= ArgSize) { 10612 if (BestKind == 0) 10613 BestKind = Kind; 10614 else if (Context.hasSameType(ParamType, ArgType)) { 10615 BestKind = Kind; 10616 break; 10617 } 10618 } 10619 } 10620 return BestKind; 10621 } 10622 10623 enum AbsoluteValueKind { 10624 AVK_Integer, 10625 AVK_Floating, 10626 AVK_Complex 10627 }; 10628 10629 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 10630 if (T->isIntegralOrEnumerationType()) 10631 return AVK_Integer; 10632 if (T->isRealFloatingType()) 10633 return AVK_Floating; 10634 if (T->isAnyComplexType()) 10635 return AVK_Complex; 10636 10637 llvm_unreachable("Type not integer, floating, or complex"); 10638 } 10639 10640 // Changes the absolute value function to a different type. Preserves whether 10641 // the function is a builtin. 10642 static unsigned changeAbsFunction(unsigned AbsKind, 10643 AbsoluteValueKind ValueKind) { 10644 switch (ValueKind) { 10645 case AVK_Integer: 10646 switch (AbsKind) { 10647 default: 10648 return 0; 10649 case Builtin::BI__builtin_fabsf: 10650 case Builtin::BI__builtin_fabs: 10651 case Builtin::BI__builtin_fabsl: 10652 case Builtin::BI__builtin_cabsf: 10653 case Builtin::BI__builtin_cabs: 10654 case Builtin::BI__builtin_cabsl: 10655 return Builtin::BI__builtin_abs; 10656 case Builtin::BIfabsf: 10657 case Builtin::BIfabs: 10658 case Builtin::BIfabsl: 10659 case Builtin::BIcabsf: 10660 case Builtin::BIcabs: 10661 case Builtin::BIcabsl: 10662 return Builtin::BIabs; 10663 } 10664 case AVK_Floating: 10665 switch (AbsKind) { 10666 default: 10667 return 0; 10668 case Builtin::BI__builtin_abs: 10669 case Builtin::BI__builtin_labs: 10670 case Builtin::BI__builtin_llabs: 10671 case Builtin::BI__builtin_cabsf: 10672 case Builtin::BI__builtin_cabs: 10673 case Builtin::BI__builtin_cabsl: 10674 return Builtin::BI__builtin_fabsf; 10675 case Builtin::BIabs: 10676 case Builtin::BIlabs: 10677 case Builtin::BIllabs: 10678 case Builtin::BIcabsf: 10679 case Builtin::BIcabs: 10680 case Builtin::BIcabsl: 10681 return Builtin::BIfabsf; 10682 } 10683 case AVK_Complex: 10684 switch (AbsKind) { 10685 default: 10686 return 0; 10687 case Builtin::BI__builtin_abs: 10688 case Builtin::BI__builtin_labs: 10689 case Builtin::BI__builtin_llabs: 10690 case Builtin::BI__builtin_fabsf: 10691 case Builtin::BI__builtin_fabs: 10692 case Builtin::BI__builtin_fabsl: 10693 return Builtin::BI__builtin_cabsf; 10694 case Builtin::BIabs: 10695 case Builtin::BIlabs: 10696 case Builtin::BIllabs: 10697 case Builtin::BIfabsf: 10698 case Builtin::BIfabs: 10699 case Builtin::BIfabsl: 10700 return Builtin::BIcabsf; 10701 } 10702 } 10703 llvm_unreachable("Unable to convert function"); 10704 } 10705 10706 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 10707 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 10708 if (!FnInfo) 10709 return 0; 10710 10711 switch (FDecl->getBuiltinID()) { 10712 default: 10713 return 0; 10714 case Builtin::BI__builtin_abs: 10715 case Builtin::BI__builtin_fabs: 10716 case Builtin::BI__builtin_fabsf: 10717 case Builtin::BI__builtin_fabsl: 10718 case Builtin::BI__builtin_labs: 10719 case Builtin::BI__builtin_llabs: 10720 case Builtin::BI__builtin_cabs: 10721 case Builtin::BI__builtin_cabsf: 10722 case Builtin::BI__builtin_cabsl: 10723 case Builtin::BIabs: 10724 case Builtin::BIlabs: 10725 case Builtin::BIllabs: 10726 case Builtin::BIfabs: 10727 case Builtin::BIfabsf: 10728 case Builtin::BIfabsl: 10729 case Builtin::BIcabs: 10730 case Builtin::BIcabsf: 10731 case Builtin::BIcabsl: 10732 return FDecl->getBuiltinID(); 10733 } 10734 llvm_unreachable("Unknown Builtin type"); 10735 } 10736 10737 // If the replacement is valid, emit a note with replacement function. 10738 // Additionally, suggest including the proper header if not already included. 10739 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10740 unsigned AbsKind, QualType ArgType) { 10741 bool EmitHeaderHint = true; 10742 const char *HeaderName = nullptr; 10743 const char *FunctionName = nullptr; 10744 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10745 FunctionName = "std::abs"; 10746 if (ArgType->isIntegralOrEnumerationType()) { 10747 HeaderName = "cstdlib"; 10748 } else if (ArgType->isRealFloatingType()) { 10749 HeaderName = "cmath"; 10750 } else { 10751 llvm_unreachable("Invalid Type"); 10752 } 10753 10754 // Lookup all std::abs 10755 if (NamespaceDecl *Std = S.getStdNamespace()) { 10756 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10757 R.suppressDiagnostics(); 10758 S.LookupQualifiedName(R, Std); 10759 10760 for (const auto *I : R) { 10761 const FunctionDecl *FDecl = nullptr; 10762 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10763 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10764 } else { 10765 FDecl = dyn_cast<FunctionDecl>(I); 10766 } 10767 if (!FDecl) 10768 continue; 10769 10770 // Found std::abs(), check that they are the right ones. 10771 if (FDecl->getNumParams() != 1) 10772 continue; 10773 10774 // Check that the parameter type can handle the argument. 10775 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10776 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10777 S.Context.getTypeSize(ArgType) <= 10778 S.Context.getTypeSize(ParamType)) { 10779 // Found a function, don't need the header hint. 10780 EmitHeaderHint = false; 10781 break; 10782 } 10783 } 10784 } 10785 } else { 10786 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10787 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10788 10789 if (HeaderName) { 10790 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10791 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10792 R.suppressDiagnostics(); 10793 S.LookupName(R, S.getCurScope()); 10794 10795 if (R.isSingleResult()) { 10796 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10797 if (FD && FD->getBuiltinID() == AbsKind) { 10798 EmitHeaderHint = false; 10799 } else { 10800 return; 10801 } 10802 } else if (!R.empty()) { 10803 return; 10804 } 10805 } 10806 } 10807 10808 S.Diag(Loc, diag::note_replace_abs_function) 10809 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10810 10811 if (!HeaderName) 10812 return; 10813 10814 if (!EmitHeaderHint) 10815 return; 10816 10817 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10818 << FunctionName; 10819 } 10820 10821 template <std::size_t StrLen> 10822 static bool IsStdFunction(const FunctionDecl *FDecl, 10823 const char (&Str)[StrLen]) { 10824 if (!FDecl) 10825 return false; 10826 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10827 return false; 10828 if (!FDecl->isInStdNamespace()) 10829 return false; 10830 10831 return true; 10832 } 10833 10834 // Warn when using the wrong abs() function. 10835 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10836 const FunctionDecl *FDecl) { 10837 if (Call->getNumArgs() != 1) 10838 return; 10839 10840 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10841 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10842 if (AbsKind == 0 && !IsStdAbs) 10843 return; 10844 10845 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10846 QualType ParamType = Call->getArg(0)->getType(); 10847 10848 // Unsigned types cannot be negative. Suggest removing the absolute value 10849 // function call. 10850 if (ArgType->isUnsignedIntegerType()) { 10851 const char *FunctionName = 10852 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10853 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10854 Diag(Call->getExprLoc(), diag::note_remove_abs) 10855 << FunctionName 10856 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10857 return; 10858 } 10859 10860 // Taking the absolute value of a pointer is very suspicious, they probably 10861 // wanted to index into an array, dereference a pointer, call a function, etc. 10862 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10863 unsigned DiagType = 0; 10864 if (ArgType->isFunctionType()) 10865 DiagType = 1; 10866 else if (ArgType->isArrayType()) 10867 DiagType = 2; 10868 10869 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10870 return; 10871 } 10872 10873 // std::abs has overloads which prevent most of the absolute value problems 10874 // from occurring. 10875 if (IsStdAbs) 10876 return; 10877 10878 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10879 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10880 10881 // The argument and parameter are the same kind. Check if they are the right 10882 // size. 10883 if (ArgValueKind == ParamValueKind) { 10884 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10885 return; 10886 10887 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10888 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10889 << FDecl << ArgType << ParamType; 10890 10891 if (NewAbsKind == 0) 10892 return; 10893 10894 emitReplacement(*this, Call->getExprLoc(), 10895 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10896 return; 10897 } 10898 10899 // ArgValueKind != ParamValueKind 10900 // The wrong type of absolute value function was used. Attempt to find the 10901 // proper one. 10902 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10903 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10904 if (NewAbsKind == 0) 10905 return; 10906 10907 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10908 << FDecl << ParamValueKind << ArgValueKind; 10909 10910 emitReplacement(*this, Call->getExprLoc(), 10911 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10912 } 10913 10914 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10915 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10916 const FunctionDecl *FDecl) { 10917 if (!Call || !FDecl) return; 10918 10919 // Ignore template specializations and macros. 10920 if (inTemplateInstantiation()) return; 10921 if (Call->getExprLoc().isMacroID()) return; 10922 10923 // Only care about the one template argument, two function parameter std::max 10924 if (Call->getNumArgs() != 2) return; 10925 if (!IsStdFunction(FDecl, "max")) return; 10926 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10927 if (!ArgList) return; 10928 if (ArgList->size() != 1) return; 10929 10930 // Check that template type argument is unsigned integer. 10931 const auto& TA = ArgList->get(0); 10932 if (TA.getKind() != TemplateArgument::Type) return; 10933 QualType ArgType = TA.getAsType(); 10934 if (!ArgType->isUnsignedIntegerType()) return; 10935 10936 // See if either argument is a literal zero. 10937 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10938 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10939 if (!MTE) return false; 10940 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10941 if (!Num) return false; 10942 if (Num->getValue() != 0) return false; 10943 return true; 10944 }; 10945 10946 const Expr *FirstArg = Call->getArg(0); 10947 const Expr *SecondArg = Call->getArg(1); 10948 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10949 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10950 10951 // Only warn when exactly one argument is zero. 10952 if (IsFirstArgZero == IsSecondArgZero) return; 10953 10954 SourceRange FirstRange = FirstArg->getSourceRange(); 10955 SourceRange SecondRange = SecondArg->getSourceRange(); 10956 10957 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10958 10959 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10960 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10961 10962 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10963 SourceRange RemovalRange; 10964 if (IsFirstArgZero) { 10965 RemovalRange = SourceRange(FirstRange.getBegin(), 10966 SecondRange.getBegin().getLocWithOffset(-1)); 10967 } else { 10968 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10969 SecondRange.getEnd()); 10970 } 10971 10972 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10973 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10974 << FixItHint::CreateRemoval(RemovalRange); 10975 } 10976 10977 //===--- CHECK: Standard memory functions ---------------------------------===// 10978 10979 /// Takes the expression passed to the size_t parameter of functions 10980 /// such as memcmp, strncat, etc and warns if it's a comparison. 10981 /// 10982 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10983 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10984 IdentifierInfo *FnName, 10985 SourceLocation FnLoc, 10986 SourceLocation RParenLoc) { 10987 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10988 if (!Size) 10989 return false; 10990 10991 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10992 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10993 return false; 10994 10995 SourceRange SizeRange = Size->getSourceRange(); 10996 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10997 << SizeRange << FnName; 10998 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10999 << FnName 11000 << FixItHint::CreateInsertion( 11001 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 11002 << FixItHint::CreateRemoval(RParenLoc); 11003 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 11004 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 11005 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 11006 ")"); 11007 11008 return true; 11009 } 11010 11011 /// Determine whether the given type is or contains a dynamic class type 11012 /// (e.g., whether it has a vtable). 11013 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 11014 bool &IsContained) { 11015 // Look through array types while ignoring qualifiers. 11016 const Type *Ty = T->getBaseElementTypeUnsafe(); 11017 IsContained = false; 11018 11019 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 11020 RD = RD ? RD->getDefinition() : nullptr; 11021 if (!RD || RD->isInvalidDecl()) 11022 return nullptr; 11023 11024 if (RD->isDynamicClass()) 11025 return RD; 11026 11027 // Check all the fields. If any bases were dynamic, the class is dynamic. 11028 // It's impossible for a class to transitively contain itself by value, so 11029 // infinite recursion is impossible. 11030 for (auto *FD : RD->fields()) { 11031 bool SubContained; 11032 if (const CXXRecordDecl *ContainedRD = 11033 getContainedDynamicClass(FD->getType(), SubContained)) { 11034 IsContained = true; 11035 return ContainedRD; 11036 } 11037 } 11038 11039 return nullptr; 11040 } 11041 11042 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 11043 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 11044 if (Unary->getKind() == UETT_SizeOf) 11045 return Unary; 11046 return nullptr; 11047 } 11048 11049 /// If E is a sizeof expression, returns its argument expression, 11050 /// otherwise returns NULL. 11051 static const Expr *getSizeOfExprArg(const Expr *E) { 11052 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 11053 if (!SizeOf->isArgumentType()) 11054 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 11055 return nullptr; 11056 } 11057 11058 /// If E is a sizeof expression, returns its argument type. 11059 static QualType getSizeOfArgType(const Expr *E) { 11060 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 11061 return SizeOf->getTypeOfArgument(); 11062 return QualType(); 11063 } 11064 11065 namespace { 11066 11067 struct SearchNonTrivialToInitializeField 11068 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 11069 using Super = 11070 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 11071 11072 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 11073 11074 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 11075 SourceLocation SL) { 11076 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 11077 asDerived().visitArray(PDIK, AT, SL); 11078 return; 11079 } 11080 11081 Super::visitWithKind(PDIK, FT, SL); 11082 } 11083 11084 void visitARCStrong(QualType FT, SourceLocation SL) { 11085 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 11086 } 11087 void visitARCWeak(QualType FT, SourceLocation SL) { 11088 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 11089 } 11090 void visitStruct(QualType FT, SourceLocation SL) { 11091 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 11092 visit(FD->getType(), FD->getLocation()); 11093 } 11094 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 11095 const ArrayType *AT, SourceLocation SL) { 11096 visit(getContext().getBaseElementType(AT), SL); 11097 } 11098 void visitTrivial(QualType FT, SourceLocation SL) {} 11099 11100 static void diag(QualType RT, const Expr *E, Sema &S) { 11101 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 11102 } 11103 11104 ASTContext &getContext() { return S.getASTContext(); } 11105 11106 const Expr *E; 11107 Sema &S; 11108 }; 11109 11110 struct SearchNonTrivialToCopyField 11111 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 11112 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 11113 11114 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 11115 11116 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 11117 SourceLocation SL) { 11118 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 11119 asDerived().visitArray(PCK, AT, SL); 11120 return; 11121 } 11122 11123 Super::visitWithKind(PCK, FT, SL); 11124 } 11125 11126 void visitARCStrong(QualType FT, SourceLocation SL) { 11127 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 11128 } 11129 void visitARCWeak(QualType FT, SourceLocation SL) { 11130 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 11131 } 11132 void visitStruct(QualType FT, SourceLocation SL) { 11133 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 11134 visit(FD->getType(), FD->getLocation()); 11135 } 11136 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 11137 SourceLocation SL) { 11138 visit(getContext().getBaseElementType(AT), SL); 11139 } 11140 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 11141 SourceLocation SL) {} 11142 void visitTrivial(QualType FT, SourceLocation SL) {} 11143 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 11144 11145 static void diag(QualType RT, const Expr *E, Sema &S) { 11146 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 11147 } 11148 11149 ASTContext &getContext() { return S.getASTContext(); } 11150 11151 const Expr *E; 11152 Sema &S; 11153 }; 11154 11155 } 11156 11157 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 11158 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 11159 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 11160 11161 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 11162 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 11163 return false; 11164 11165 return doesExprLikelyComputeSize(BO->getLHS()) || 11166 doesExprLikelyComputeSize(BO->getRHS()); 11167 } 11168 11169 return getAsSizeOfExpr(SizeofExpr) != nullptr; 11170 } 11171 11172 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 11173 /// 11174 /// \code 11175 /// #define MACRO 0 11176 /// foo(MACRO); 11177 /// foo(0); 11178 /// \endcode 11179 /// 11180 /// This should return true for the first call to foo, but not for the second 11181 /// (regardless of whether foo is a macro or function). 11182 static bool isArgumentExpandedFromMacro(SourceManager &SM, 11183 SourceLocation CallLoc, 11184 SourceLocation ArgLoc) { 11185 if (!CallLoc.isMacroID()) 11186 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 11187 11188 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 11189 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 11190 } 11191 11192 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 11193 /// last two arguments transposed. 11194 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 11195 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 11196 return; 11197 11198 const Expr *SizeArg = 11199 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 11200 11201 auto isLiteralZero = [](const Expr *E) { 11202 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 11203 }; 11204 11205 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 11206 SourceLocation CallLoc = Call->getRParenLoc(); 11207 SourceManager &SM = S.getSourceManager(); 11208 if (isLiteralZero(SizeArg) && 11209 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 11210 11211 SourceLocation DiagLoc = SizeArg->getExprLoc(); 11212 11213 // Some platforms #define bzero to __builtin_memset. See if this is the 11214 // case, and if so, emit a better diagnostic. 11215 if (BId == Builtin::BIbzero || 11216 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 11217 CallLoc, SM, S.getLangOpts()) == "bzero")) { 11218 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 11219 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 11220 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 11221 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 11222 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 11223 } 11224 return; 11225 } 11226 11227 // If the second argument to a memset is a sizeof expression and the third 11228 // isn't, this is also likely an error. This should catch 11229 // 'memset(buf, sizeof(buf), 0xff)'. 11230 if (BId == Builtin::BImemset && 11231 doesExprLikelyComputeSize(Call->getArg(1)) && 11232 !doesExprLikelyComputeSize(Call->getArg(2))) { 11233 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 11234 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 11235 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 11236 return; 11237 } 11238 } 11239 11240 /// Check for dangerous or invalid arguments to memset(). 11241 /// 11242 /// This issues warnings on known problematic, dangerous or unspecified 11243 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 11244 /// function calls. 11245 /// 11246 /// \param Call The call expression to diagnose. 11247 void Sema::CheckMemaccessArguments(const CallExpr *Call, 11248 unsigned BId, 11249 IdentifierInfo *FnName) { 11250 assert(BId != 0); 11251 11252 // It is possible to have a non-standard definition of memset. Validate 11253 // we have enough arguments, and if not, abort further checking. 11254 unsigned ExpectedNumArgs = 11255 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 11256 if (Call->getNumArgs() < ExpectedNumArgs) 11257 return; 11258 11259 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 11260 BId == Builtin::BIstrndup ? 1 : 2); 11261 unsigned LenArg = 11262 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 11263 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 11264 11265 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 11266 Call->getBeginLoc(), Call->getRParenLoc())) 11267 return; 11268 11269 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 11270 CheckMemaccessSize(*this, BId, Call); 11271 11272 // We have special checking when the length is a sizeof expression. 11273 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 11274 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 11275 llvm::FoldingSetNodeID SizeOfArgID; 11276 11277 // Although widely used, 'bzero' is not a standard function. Be more strict 11278 // with the argument types before allowing diagnostics and only allow the 11279 // form bzero(ptr, sizeof(...)). 11280 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 11281 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 11282 return; 11283 11284 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 11285 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 11286 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 11287 11288 QualType DestTy = Dest->getType(); 11289 QualType PointeeTy; 11290 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 11291 PointeeTy = DestPtrTy->getPointeeType(); 11292 11293 // Never warn about void type pointers. This can be used to suppress 11294 // false positives. 11295 if (PointeeTy->isVoidType()) 11296 continue; 11297 11298 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 11299 // actually comparing the expressions for equality. Because computing the 11300 // expression IDs can be expensive, we only do this if the diagnostic is 11301 // enabled. 11302 if (SizeOfArg && 11303 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 11304 SizeOfArg->getExprLoc())) { 11305 // We only compute IDs for expressions if the warning is enabled, and 11306 // cache the sizeof arg's ID. 11307 if (SizeOfArgID == llvm::FoldingSetNodeID()) 11308 SizeOfArg->Profile(SizeOfArgID, Context, true); 11309 llvm::FoldingSetNodeID DestID; 11310 Dest->Profile(DestID, Context, true); 11311 if (DestID == SizeOfArgID) { 11312 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 11313 // over sizeof(src) as well. 11314 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 11315 StringRef ReadableName = FnName->getName(); 11316 11317 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 11318 if (UnaryOp->getOpcode() == UO_AddrOf) 11319 ActionIdx = 1; // If its an address-of operator, just remove it. 11320 if (!PointeeTy->isIncompleteType() && 11321 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 11322 ActionIdx = 2; // If the pointee's size is sizeof(char), 11323 // suggest an explicit length. 11324 11325 // If the function is defined as a builtin macro, do not show macro 11326 // expansion. 11327 SourceLocation SL = SizeOfArg->getExprLoc(); 11328 SourceRange DSR = Dest->getSourceRange(); 11329 SourceRange SSR = SizeOfArg->getSourceRange(); 11330 SourceManager &SM = getSourceManager(); 11331 11332 if (SM.isMacroArgExpansion(SL)) { 11333 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 11334 SL = SM.getSpellingLoc(SL); 11335 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 11336 SM.getSpellingLoc(DSR.getEnd())); 11337 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 11338 SM.getSpellingLoc(SSR.getEnd())); 11339 } 11340 11341 DiagRuntimeBehavior(SL, SizeOfArg, 11342 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 11343 << ReadableName 11344 << PointeeTy 11345 << DestTy 11346 << DSR 11347 << SSR); 11348 DiagRuntimeBehavior(SL, SizeOfArg, 11349 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 11350 << ActionIdx 11351 << SSR); 11352 11353 break; 11354 } 11355 } 11356 11357 // Also check for cases where the sizeof argument is the exact same 11358 // type as the memory argument, and where it points to a user-defined 11359 // record type. 11360 if (SizeOfArgTy != QualType()) { 11361 if (PointeeTy->isRecordType() && 11362 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 11363 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 11364 PDiag(diag::warn_sizeof_pointer_type_memaccess) 11365 << FnName << SizeOfArgTy << ArgIdx 11366 << PointeeTy << Dest->getSourceRange() 11367 << LenExpr->getSourceRange()); 11368 break; 11369 } 11370 } 11371 } else if (DestTy->isArrayType()) { 11372 PointeeTy = DestTy; 11373 } 11374 11375 if (PointeeTy == QualType()) 11376 continue; 11377 11378 // Always complain about dynamic classes. 11379 bool IsContained; 11380 if (const CXXRecordDecl *ContainedRD = 11381 getContainedDynamicClass(PointeeTy, IsContained)) { 11382 11383 unsigned OperationType = 0; 11384 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 11385 // "overwritten" if we're warning about the destination for any call 11386 // but memcmp; otherwise a verb appropriate to the call. 11387 if (ArgIdx != 0 || IsCmp) { 11388 if (BId == Builtin::BImemcpy) 11389 OperationType = 1; 11390 else if(BId == Builtin::BImemmove) 11391 OperationType = 2; 11392 else if (IsCmp) 11393 OperationType = 3; 11394 } 11395 11396 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 11397 PDiag(diag::warn_dyn_class_memaccess) 11398 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 11399 << IsContained << ContainedRD << OperationType 11400 << Call->getCallee()->getSourceRange()); 11401 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 11402 BId != Builtin::BImemset) 11403 DiagRuntimeBehavior( 11404 Dest->getExprLoc(), Dest, 11405 PDiag(diag::warn_arc_object_memaccess) 11406 << ArgIdx << FnName << PointeeTy 11407 << Call->getCallee()->getSourceRange()); 11408 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 11409 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 11410 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 11411 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 11412 PDiag(diag::warn_cstruct_memaccess) 11413 << ArgIdx << FnName << PointeeTy << 0); 11414 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 11415 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 11416 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 11417 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 11418 PDiag(diag::warn_cstruct_memaccess) 11419 << ArgIdx << FnName << PointeeTy << 1); 11420 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 11421 } else { 11422 continue; 11423 } 11424 } else 11425 continue; 11426 11427 DiagRuntimeBehavior( 11428 Dest->getExprLoc(), Dest, 11429 PDiag(diag::note_bad_memaccess_silence) 11430 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 11431 break; 11432 } 11433 } 11434 11435 // A little helper routine: ignore addition and subtraction of integer literals. 11436 // This intentionally does not ignore all integer constant expressions because 11437 // we don't want to remove sizeof(). 11438 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 11439 Ex = Ex->IgnoreParenCasts(); 11440 11441 while (true) { 11442 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 11443 if (!BO || !BO->isAdditiveOp()) 11444 break; 11445 11446 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 11447 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 11448 11449 if (isa<IntegerLiteral>(RHS)) 11450 Ex = LHS; 11451 else if (isa<IntegerLiteral>(LHS)) 11452 Ex = RHS; 11453 else 11454 break; 11455 } 11456 11457 return Ex; 11458 } 11459 11460 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 11461 ASTContext &Context) { 11462 // Only handle constant-sized or VLAs, but not flexible members. 11463 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 11464 // Only issue the FIXIT for arrays of size > 1. 11465 if (CAT->getSize().getSExtValue() <= 1) 11466 return false; 11467 } else if (!Ty->isVariableArrayType()) { 11468 return false; 11469 } 11470 return true; 11471 } 11472 11473 // Warn if the user has made the 'size' argument to strlcpy or strlcat 11474 // be the size of the source, instead of the destination. 11475 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 11476 IdentifierInfo *FnName) { 11477 11478 // Don't crash if the user has the wrong number of arguments 11479 unsigned NumArgs = Call->getNumArgs(); 11480 if ((NumArgs != 3) && (NumArgs != 4)) 11481 return; 11482 11483 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 11484 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 11485 const Expr *CompareWithSrc = nullptr; 11486 11487 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 11488 Call->getBeginLoc(), Call->getRParenLoc())) 11489 return; 11490 11491 // Look for 'strlcpy(dst, x, sizeof(x))' 11492 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 11493 CompareWithSrc = Ex; 11494 else { 11495 // Look for 'strlcpy(dst, x, strlen(x))' 11496 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 11497 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 11498 SizeCall->getNumArgs() == 1) 11499 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 11500 } 11501 } 11502 11503 if (!CompareWithSrc) 11504 return; 11505 11506 // Determine if the argument to sizeof/strlen is equal to the source 11507 // argument. In principle there's all kinds of things you could do 11508 // here, for instance creating an == expression and evaluating it with 11509 // EvaluateAsBooleanCondition, but this uses a more direct technique: 11510 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 11511 if (!SrcArgDRE) 11512 return; 11513 11514 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 11515 if (!CompareWithSrcDRE || 11516 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 11517 return; 11518 11519 const Expr *OriginalSizeArg = Call->getArg(2); 11520 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 11521 << OriginalSizeArg->getSourceRange() << FnName; 11522 11523 // Output a FIXIT hint if the destination is an array (rather than a 11524 // pointer to an array). This could be enhanced to handle some 11525 // pointers if we know the actual size, like if DstArg is 'array+2' 11526 // we could say 'sizeof(array)-2'. 11527 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 11528 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 11529 return; 11530 11531 SmallString<128> sizeString; 11532 llvm::raw_svector_ostream OS(sizeString); 11533 OS << "sizeof("; 11534 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11535 OS << ")"; 11536 11537 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 11538 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 11539 OS.str()); 11540 } 11541 11542 /// Check if two expressions refer to the same declaration. 11543 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 11544 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 11545 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 11546 return D1->getDecl() == D2->getDecl(); 11547 return false; 11548 } 11549 11550 static const Expr *getStrlenExprArg(const Expr *E) { 11551 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11552 const FunctionDecl *FD = CE->getDirectCallee(); 11553 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 11554 return nullptr; 11555 return CE->getArg(0)->IgnoreParenCasts(); 11556 } 11557 return nullptr; 11558 } 11559 11560 // Warn on anti-patterns as the 'size' argument to strncat. 11561 // The correct size argument should look like following: 11562 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 11563 void Sema::CheckStrncatArguments(const CallExpr *CE, 11564 IdentifierInfo *FnName) { 11565 // Don't crash if the user has the wrong number of arguments. 11566 if (CE->getNumArgs() < 3) 11567 return; 11568 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 11569 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 11570 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 11571 11572 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 11573 CE->getRParenLoc())) 11574 return; 11575 11576 // Identify common expressions, which are wrongly used as the size argument 11577 // to strncat and may lead to buffer overflows. 11578 unsigned PatternType = 0; 11579 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 11580 // - sizeof(dst) 11581 if (referToTheSameDecl(SizeOfArg, DstArg)) 11582 PatternType = 1; 11583 // - sizeof(src) 11584 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 11585 PatternType = 2; 11586 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 11587 if (BE->getOpcode() == BO_Sub) { 11588 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 11589 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 11590 // - sizeof(dst) - strlen(dst) 11591 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 11592 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 11593 PatternType = 1; 11594 // - sizeof(src) - (anything) 11595 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 11596 PatternType = 2; 11597 } 11598 } 11599 11600 if (PatternType == 0) 11601 return; 11602 11603 // Generate the diagnostic. 11604 SourceLocation SL = LenArg->getBeginLoc(); 11605 SourceRange SR = LenArg->getSourceRange(); 11606 SourceManager &SM = getSourceManager(); 11607 11608 // If the function is defined as a builtin macro, do not show macro expansion. 11609 if (SM.isMacroArgExpansion(SL)) { 11610 SL = SM.getSpellingLoc(SL); 11611 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 11612 SM.getSpellingLoc(SR.getEnd())); 11613 } 11614 11615 // Check if the destination is an array (rather than a pointer to an array). 11616 QualType DstTy = DstArg->getType(); 11617 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 11618 Context); 11619 if (!isKnownSizeArray) { 11620 if (PatternType == 1) 11621 Diag(SL, diag::warn_strncat_wrong_size) << SR; 11622 else 11623 Diag(SL, diag::warn_strncat_src_size) << SR; 11624 return; 11625 } 11626 11627 if (PatternType == 1) 11628 Diag(SL, diag::warn_strncat_large_size) << SR; 11629 else 11630 Diag(SL, diag::warn_strncat_src_size) << SR; 11631 11632 SmallString<128> sizeString; 11633 llvm::raw_svector_ostream OS(sizeString); 11634 OS << "sizeof("; 11635 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11636 OS << ") - "; 11637 OS << "strlen("; 11638 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11639 OS << ") - 1"; 11640 11641 Diag(SL, diag::note_strncat_wrong_size) 11642 << FixItHint::CreateReplacement(SR, OS.str()); 11643 } 11644 11645 namespace { 11646 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 11647 const UnaryOperator *UnaryExpr, const Decl *D) { 11648 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 11649 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 11650 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 11651 return; 11652 } 11653 } 11654 11655 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 11656 const UnaryOperator *UnaryExpr) { 11657 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 11658 const Decl *D = Lvalue->getDecl(); 11659 if (isa<DeclaratorDecl>(D)) 11660 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 11661 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 11662 } 11663 11664 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 11665 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 11666 Lvalue->getMemberDecl()); 11667 } 11668 11669 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 11670 const UnaryOperator *UnaryExpr) { 11671 const auto *Lambda = dyn_cast<LambdaExpr>( 11672 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 11673 if (!Lambda) 11674 return; 11675 11676 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 11677 << CalleeName << 2 /*object: lambda expression*/; 11678 } 11679 11680 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 11681 const DeclRefExpr *Lvalue) { 11682 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 11683 if (Var == nullptr) 11684 return; 11685 11686 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 11687 << CalleeName << 0 /*object: */ << Var; 11688 } 11689 11690 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 11691 const CastExpr *Cast) { 11692 SmallString<128> SizeString; 11693 llvm::raw_svector_ostream OS(SizeString); 11694 11695 clang::CastKind Kind = Cast->getCastKind(); 11696 if (Kind == clang::CK_BitCast && 11697 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 11698 return; 11699 if (Kind == clang::CK_IntegralToPointer && 11700 !isa<IntegerLiteral>( 11701 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 11702 return; 11703 11704 switch (Cast->getCastKind()) { 11705 case clang::CK_BitCast: 11706 case clang::CK_IntegralToPointer: 11707 case clang::CK_FunctionToPointerDecay: 11708 OS << '\''; 11709 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 11710 OS << '\''; 11711 break; 11712 default: 11713 return; 11714 } 11715 11716 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 11717 << CalleeName << 0 /*object: */ << OS.str(); 11718 } 11719 } // namespace 11720 11721 /// Alerts the user that they are attempting to free a non-malloc'd object. 11722 void Sema::CheckFreeArguments(const CallExpr *E) { 11723 const std::string CalleeName = 11724 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 11725 11726 { // Prefer something that doesn't involve a cast to make things simpler. 11727 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 11728 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 11729 switch (UnaryExpr->getOpcode()) { 11730 case UnaryOperator::Opcode::UO_AddrOf: 11731 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 11732 case UnaryOperator::Opcode::UO_Plus: 11733 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 11734 default: 11735 break; 11736 } 11737 11738 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11739 if (Lvalue->getType()->isArrayType()) 11740 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11741 11742 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11743 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11744 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11745 return; 11746 } 11747 11748 if (isa<BlockExpr>(Arg)) { 11749 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11750 << CalleeName << 1 /*object: block*/; 11751 return; 11752 } 11753 } 11754 // Maybe the cast was important, check after the other cases. 11755 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11756 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11757 } 11758 11759 void 11760 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11761 SourceLocation ReturnLoc, 11762 bool isObjCMethod, 11763 const AttrVec *Attrs, 11764 const FunctionDecl *FD) { 11765 // Check if the return value is null but should not be. 11766 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11767 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11768 CheckNonNullExpr(*this, RetValExp)) 11769 Diag(ReturnLoc, diag::warn_null_ret) 11770 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11771 11772 // C++11 [basic.stc.dynamic.allocation]p4: 11773 // If an allocation function declared with a non-throwing 11774 // exception-specification fails to allocate storage, it shall return 11775 // a null pointer. Any other allocation function that fails to allocate 11776 // storage shall indicate failure only by throwing an exception [...] 11777 if (FD) { 11778 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11779 if (Op == OO_New || Op == OO_Array_New) { 11780 const FunctionProtoType *Proto 11781 = FD->getType()->castAs<FunctionProtoType>(); 11782 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11783 CheckNonNullExpr(*this, RetValExp)) 11784 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11785 << FD << getLangOpts().CPlusPlus11; 11786 } 11787 } 11788 11789 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11790 // here prevent the user from using a PPC MMA type as trailing return type. 11791 if (Context.getTargetInfo().getTriple().isPPC64()) 11792 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11793 } 11794 11795 /// Check for comparisons of floating-point values using == and !=. Issue a 11796 /// warning if the comparison is not likely to do what the programmer intended. 11797 void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, 11798 BinaryOperatorKind Opcode) { 11799 // Match and capture subexpressions such as "(float) X == 0.1". 11800 FloatingLiteral *FPLiteral; 11801 CastExpr *FPCast; 11802 auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) { 11803 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens()); 11804 FPCast = dyn_cast<CastExpr>(R->IgnoreParens()); 11805 return FPLiteral && FPCast; 11806 }; 11807 11808 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) { 11809 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>(); 11810 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>(); 11811 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() && 11812 TargetTy->isFloatingPoint()) { 11813 bool Lossy; 11814 llvm::APFloat TargetC = FPLiteral->getValue(); 11815 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)), 11816 llvm::APFloat::rmNearestTiesToEven, &Lossy); 11817 if (Lossy) { 11818 // If the literal cannot be represented in the source type, then a 11819 // check for == is always false and check for != is always true. 11820 Diag(Loc, diag::warn_float_compare_literal) 11821 << (Opcode == BO_EQ) << QualType(SourceTy, 0) 11822 << LHS->getSourceRange() << RHS->getSourceRange(); 11823 return; 11824 } 11825 } 11826 } 11827 11828 // Match a more general floating-point equality comparison (-Wfloat-equal). 11829 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11830 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11831 11832 // Special case: check for x == x (which is OK). 11833 // Do not emit warnings for such cases. 11834 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11835 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11836 if (DRL->getDecl() == DRR->getDecl()) 11837 return; 11838 11839 // Special case: check for comparisons against literals that can be exactly 11840 // represented by APFloat. In such cases, do not emit a warning. This 11841 // is a heuristic: often comparison against such literals are used to 11842 // detect if a value in a variable has not changed. This clearly can 11843 // lead to false negatives. 11844 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11845 if (FLL->isExact()) 11846 return; 11847 } else 11848 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11849 if (FLR->isExact()) 11850 return; 11851 11852 // Check for comparisons with builtin types. 11853 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11854 if (CL->getBuiltinCallee()) 11855 return; 11856 11857 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11858 if (CR->getBuiltinCallee()) 11859 return; 11860 11861 // Emit the diagnostic. 11862 Diag(Loc, diag::warn_floatingpoint_eq) 11863 << LHS->getSourceRange() << RHS->getSourceRange(); 11864 } 11865 11866 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11867 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11868 11869 namespace { 11870 11871 /// Structure recording the 'active' range of an integer-valued 11872 /// expression. 11873 struct IntRange { 11874 /// The number of bits active in the int. Note that this includes exactly one 11875 /// sign bit if !NonNegative. 11876 unsigned Width; 11877 11878 /// True if the int is known not to have negative values. If so, all leading 11879 /// bits before Width are known zero, otherwise they are known to be the 11880 /// same as the MSB within Width. 11881 bool NonNegative; 11882 11883 IntRange(unsigned Width, bool NonNegative) 11884 : Width(Width), NonNegative(NonNegative) {} 11885 11886 /// Number of bits excluding the sign bit. 11887 unsigned valueBits() const { 11888 return NonNegative ? Width : Width - 1; 11889 } 11890 11891 /// Returns the range of the bool type. 11892 static IntRange forBoolType() { 11893 return IntRange(1, true); 11894 } 11895 11896 /// Returns the range of an opaque value of the given integral type. 11897 static IntRange forValueOfType(ASTContext &C, QualType T) { 11898 return forValueOfCanonicalType(C, 11899 T->getCanonicalTypeInternal().getTypePtr()); 11900 } 11901 11902 /// Returns the range of an opaque value of a canonical integral type. 11903 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11904 assert(T->isCanonicalUnqualified()); 11905 11906 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11907 T = VT->getElementType().getTypePtr(); 11908 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11909 T = CT->getElementType().getTypePtr(); 11910 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11911 T = AT->getValueType().getTypePtr(); 11912 11913 if (!C.getLangOpts().CPlusPlus) { 11914 // For enum types in C code, use the underlying datatype. 11915 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11916 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11917 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11918 // For enum types in C++, use the known bit width of the enumerators. 11919 EnumDecl *Enum = ET->getDecl(); 11920 // In C++11, enums can have a fixed underlying type. Use this type to 11921 // compute the range. 11922 if (Enum->isFixed()) { 11923 return IntRange(C.getIntWidth(QualType(T, 0)), 11924 !ET->isSignedIntegerOrEnumerationType()); 11925 } 11926 11927 unsigned NumPositive = Enum->getNumPositiveBits(); 11928 unsigned NumNegative = Enum->getNumNegativeBits(); 11929 11930 if (NumNegative == 0) 11931 return IntRange(NumPositive, true/*NonNegative*/); 11932 else 11933 return IntRange(std::max(NumPositive + 1, NumNegative), 11934 false/*NonNegative*/); 11935 } 11936 11937 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11938 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11939 11940 const BuiltinType *BT = cast<BuiltinType>(T); 11941 assert(BT->isInteger()); 11942 11943 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11944 } 11945 11946 /// Returns the "target" range of a canonical integral type, i.e. 11947 /// the range of values expressible in the type. 11948 /// 11949 /// This matches forValueOfCanonicalType except that enums have the 11950 /// full range of their type, not the range of their enumerators. 11951 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11952 assert(T->isCanonicalUnqualified()); 11953 11954 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11955 T = VT->getElementType().getTypePtr(); 11956 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11957 T = CT->getElementType().getTypePtr(); 11958 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11959 T = AT->getValueType().getTypePtr(); 11960 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11961 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11962 11963 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11964 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11965 11966 const BuiltinType *BT = cast<BuiltinType>(T); 11967 assert(BT->isInteger()); 11968 11969 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11970 } 11971 11972 /// Returns the supremum of two ranges: i.e. their conservative merge. 11973 static IntRange join(IntRange L, IntRange R) { 11974 bool Unsigned = L.NonNegative && R.NonNegative; 11975 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11976 L.NonNegative && R.NonNegative); 11977 } 11978 11979 /// Return the range of a bitwise-AND of the two ranges. 11980 static IntRange bit_and(IntRange L, IntRange R) { 11981 unsigned Bits = std::max(L.Width, R.Width); 11982 bool NonNegative = false; 11983 if (L.NonNegative) { 11984 Bits = std::min(Bits, L.Width); 11985 NonNegative = true; 11986 } 11987 if (R.NonNegative) { 11988 Bits = std::min(Bits, R.Width); 11989 NonNegative = true; 11990 } 11991 return IntRange(Bits, NonNegative); 11992 } 11993 11994 /// Return the range of a sum of the two ranges. 11995 static IntRange sum(IntRange L, IntRange R) { 11996 bool Unsigned = L.NonNegative && R.NonNegative; 11997 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11998 Unsigned); 11999 } 12000 12001 /// Return the range of a difference of the two ranges. 12002 static IntRange difference(IntRange L, IntRange R) { 12003 // We need a 1-bit-wider range if: 12004 // 1) LHS can be negative: least value can be reduced. 12005 // 2) RHS can be negative: greatest value can be increased. 12006 bool CanWiden = !L.NonNegative || !R.NonNegative; 12007 bool Unsigned = L.NonNegative && R.Width == 0; 12008 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 12009 !Unsigned, 12010 Unsigned); 12011 } 12012 12013 /// Return the range of a product of the two ranges. 12014 static IntRange product(IntRange L, IntRange R) { 12015 // If both LHS and RHS can be negative, we can form 12016 // -2^L * -2^R = 2^(L + R) 12017 // which requires L + R + 1 value bits to represent. 12018 bool CanWiden = !L.NonNegative && !R.NonNegative; 12019 bool Unsigned = L.NonNegative && R.NonNegative; 12020 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 12021 Unsigned); 12022 } 12023 12024 /// Return the range of a remainder operation between the two ranges. 12025 static IntRange rem(IntRange L, IntRange R) { 12026 // The result of a remainder can't be larger than the result of 12027 // either side. The sign of the result is the sign of the LHS. 12028 bool Unsigned = L.NonNegative; 12029 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 12030 Unsigned); 12031 } 12032 }; 12033 12034 } // namespace 12035 12036 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 12037 unsigned MaxWidth) { 12038 if (value.isSigned() && value.isNegative()) 12039 return IntRange(value.getMinSignedBits(), false); 12040 12041 if (value.getBitWidth() > MaxWidth) 12042 value = value.trunc(MaxWidth); 12043 12044 // isNonNegative() just checks the sign bit without considering 12045 // signedness. 12046 return IntRange(value.getActiveBits(), true); 12047 } 12048 12049 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 12050 unsigned MaxWidth) { 12051 if (result.isInt()) 12052 return GetValueRange(C, result.getInt(), MaxWidth); 12053 12054 if (result.isVector()) { 12055 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 12056 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 12057 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 12058 R = IntRange::join(R, El); 12059 } 12060 return R; 12061 } 12062 12063 if (result.isComplexInt()) { 12064 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 12065 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 12066 return IntRange::join(R, I); 12067 } 12068 12069 // This can happen with lossless casts to intptr_t of "based" lvalues. 12070 // Assume it might use arbitrary bits. 12071 // FIXME: The only reason we need to pass the type in here is to get 12072 // the sign right on this one case. It would be nice if APValue 12073 // preserved this. 12074 assert(result.isLValue() || result.isAddrLabelDiff()); 12075 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 12076 } 12077 12078 static QualType GetExprType(const Expr *E) { 12079 QualType Ty = E->getType(); 12080 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 12081 Ty = AtomicRHS->getValueType(); 12082 return Ty; 12083 } 12084 12085 /// Pseudo-evaluate the given integer expression, estimating the 12086 /// range of values it might take. 12087 /// 12088 /// \param MaxWidth The width to which the value will be truncated. 12089 /// \param Approximate If \c true, return a likely range for the result: in 12090 /// particular, assume that arithmetic on narrower types doesn't leave 12091 /// those types. If \c false, return a range including all possible 12092 /// result values. 12093 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 12094 bool InConstantContext, bool Approximate) { 12095 E = E->IgnoreParens(); 12096 12097 // Try a full evaluation first. 12098 Expr::EvalResult result; 12099 if (E->EvaluateAsRValue(result, C, InConstantContext)) 12100 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 12101 12102 // I think we only want to look through implicit casts here; if the 12103 // user has an explicit widening cast, we should treat the value as 12104 // being of the new, wider type. 12105 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 12106 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 12107 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 12108 Approximate); 12109 12110 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 12111 12112 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 12113 CE->getCastKind() == CK_BooleanToSignedIntegral; 12114 12115 // Assume that non-integer casts can span the full range of the type. 12116 if (!isIntegerCast) 12117 return OutputTypeRange; 12118 12119 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 12120 std::min(MaxWidth, OutputTypeRange.Width), 12121 InConstantContext, Approximate); 12122 12123 // Bail out if the subexpr's range is as wide as the cast type. 12124 if (SubRange.Width >= OutputTypeRange.Width) 12125 return OutputTypeRange; 12126 12127 // Otherwise, we take the smaller width, and we're non-negative if 12128 // either the output type or the subexpr is. 12129 return IntRange(SubRange.Width, 12130 SubRange.NonNegative || OutputTypeRange.NonNegative); 12131 } 12132 12133 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12134 // If we can fold the condition, just take that operand. 12135 bool CondResult; 12136 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 12137 return GetExprRange(C, 12138 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 12139 MaxWidth, InConstantContext, Approximate); 12140 12141 // Otherwise, conservatively merge. 12142 // GetExprRange requires an integer expression, but a throw expression 12143 // results in a void type. 12144 Expr *E = CO->getTrueExpr(); 12145 IntRange L = E->getType()->isVoidType() 12146 ? IntRange{0, true} 12147 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 12148 E = CO->getFalseExpr(); 12149 IntRange R = E->getType()->isVoidType() 12150 ? IntRange{0, true} 12151 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 12152 return IntRange::join(L, R); 12153 } 12154 12155 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12156 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 12157 12158 switch (BO->getOpcode()) { 12159 case BO_Cmp: 12160 llvm_unreachable("builtin <=> should have class type"); 12161 12162 // Boolean-valued operations are single-bit and positive. 12163 case BO_LAnd: 12164 case BO_LOr: 12165 case BO_LT: 12166 case BO_GT: 12167 case BO_LE: 12168 case BO_GE: 12169 case BO_EQ: 12170 case BO_NE: 12171 return IntRange::forBoolType(); 12172 12173 // The type of the assignments is the type of the LHS, so the RHS 12174 // is not necessarily the same type. 12175 case BO_MulAssign: 12176 case BO_DivAssign: 12177 case BO_RemAssign: 12178 case BO_AddAssign: 12179 case BO_SubAssign: 12180 case BO_XorAssign: 12181 case BO_OrAssign: 12182 // TODO: bitfields? 12183 return IntRange::forValueOfType(C, GetExprType(E)); 12184 12185 // Simple assignments just pass through the RHS, which will have 12186 // been coerced to the LHS type. 12187 case BO_Assign: 12188 // TODO: bitfields? 12189 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 12190 Approximate); 12191 12192 // Operations with opaque sources are black-listed. 12193 case BO_PtrMemD: 12194 case BO_PtrMemI: 12195 return IntRange::forValueOfType(C, GetExprType(E)); 12196 12197 // Bitwise-and uses the *infinum* of the two source ranges. 12198 case BO_And: 12199 case BO_AndAssign: 12200 Combine = IntRange::bit_and; 12201 break; 12202 12203 // Left shift gets black-listed based on a judgement call. 12204 case BO_Shl: 12205 // ...except that we want to treat '1 << (blah)' as logically 12206 // positive. It's an important idiom. 12207 if (IntegerLiteral *I 12208 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 12209 if (I->getValue() == 1) { 12210 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 12211 return IntRange(R.Width, /*NonNegative*/ true); 12212 } 12213 } 12214 LLVM_FALLTHROUGH; 12215 12216 case BO_ShlAssign: 12217 return IntRange::forValueOfType(C, GetExprType(E)); 12218 12219 // Right shift by a constant can narrow its left argument. 12220 case BO_Shr: 12221 case BO_ShrAssign: { 12222 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 12223 Approximate); 12224 12225 // If the shift amount is a positive constant, drop the width by 12226 // that much. 12227 if (Optional<llvm::APSInt> shift = 12228 BO->getRHS()->getIntegerConstantExpr(C)) { 12229 if (shift->isNonNegative()) { 12230 unsigned zext = shift->getZExtValue(); 12231 if (zext >= L.Width) 12232 L.Width = (L.NonNegative ? 0 : 1); 12233 else 12234 L.Width -= zext; 12235 } 12236 } 12237 12238 return L; 12239 } 12240 12241 // Comma acts as its right operand. 12242 case BO_Comma: 12243 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 12244 Approximate); 12245 12246 case BO_Add: 12247 if (!Approximate) 12248 Combine = IntRange::sum; 12249 break; 12250 12251 case BO_Sub: 12252 if (BO->getLHS()->getType()->isPointerType()) 12253 return IntRange::forValueOfType(C, GetExprType(E)); 12254 if (!Approximate) 12255 Combine = IntRange::difference; 12256 break; 12257 12258 case BO_Mul: 12259 if (!Approximate) 12260 Combine = IntRange::product; 12261 break; 12262 12263 // The width of a division result is mostly determined by the size 12264 // of the LHS. 12265 case BO_Div: { 12266 // Don't 'pre-truncate' the operands. 12267 unsigned opWidth = C.getIntWidth(GetExprType(E)); 12268 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 12269 Approximate); 12270 12271 // If the divisor is constant, use that. 12272 if (Optional<llvm::APSInt> divisor = 12273 BO->getRHS()->getIntegerConstantExpr(C)) { 12274 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 12275 if (log2 >= L.Width) 12276 L.Width = (L.NonNegative ? 0 : 1); 12277 else 12278 L.Width = std::min(L.Width - log2, MaxWidth); 12279 return L; 12280 } 12281 12282 // Otherwise, just use the LHS's width. 12283 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 12284 // could be -1. 12285 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 12286 Approximate); 12287 return IntRange(L.Width, L.NonNegative && R.NonNegative); 12288 } 12289 12290 case BO_Rem: 12291 Combine = IntRange::rem; 12292 break; 12293 12294 // The default behavior is okay for these. 12295 case BO_Xor: 12296 case BO_Or: 12297 break; 12298 } 12299 12300 // Combine the two ranges, but limit the result to the type in which we 12301 // performed the computation. 12302 QualType T = GetExprType(E); 12303 unsigned opWidth = C.getIntWidth(T); 12304 IntRange L = 12305 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 12306 IntRange R = 12307 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 12308 IntRange C = Combine(L, R); 12309 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 12310 C.Width = std::min(C.Width, MaxWidth); 12311 return C; 12312 } 12313 12314 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 12315 switch (UO->getOpcode()) { 12316 // Boolean-valued operations are white-listed. 12317 case UO_LNot: 12318 return IntRange::forBoolType(); 12319 12320 // Operations with opaque sources are black-listed. 12321 case UO_Deref: 12322 case UO_AddrOf: // should be impossible 12323 return IntRange::forValueOfType(C, GetExprType(E)); 12324 12325 default: 12326 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 12327 Approximate); 12328 } 12329 } 12330 12331 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12332 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 12333 Approximate); 12334 12335 if (const auto *BitField = E->getSourceBitField()) 12336 return IntRange(BitField->getBitWidthValue(C), 12337 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 12338 12339 return IntRange::forValueOfType(C, GetExprType(E)); 12340 } 12341 12342 static IntRange GetExprRange(ASTContext &C, const Expr *E, 12343 bool InConstantContext, bool Approximate) { 12344 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 12345 Approximate); 12346 } 12347 12348 /// Checks whether the given value, which currently has the given 12349 /// source semantics, has the same value when coerced through the 12350 /// target semantics. 12351 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 12352 const llvm::fltSemantics &Src, 12353 const llvm::fltSemantics &Tgt) { 12354 llvm::APFloat truncated = value; 12355 12356 bool ignored; 12357 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 12358 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 12359 12360 return truncated.bitwiseIsEqual(value); 12361 } 12362 12363 /// Checks whether the given value, which currently has the given 12364 /// source semantics, has the same value when coerced through the 12365 /// target semantics. 12366 /// 12367 /// The value might be a vector of floats (or a complex number). 12368 static bool IsSameFloatAfterCast(const APValue &value, 12369 const llvm::fltSemantics &Src, 12370 const llvm::fltSemantics &Tgt) { 12371 if (value.isFloat()) 12372 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 12373 12374 if (value.isVector()) { 12375 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 12376 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 12377 return false; 12378 return true; 12379 } 12380 12381 assert(value.isComplexFloat()); 12382 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 12383 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 12384 } 12385 12386 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 12387 bool IsListInit = false); 12388 12389 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 12390 // Suppress cases where we are comparing against an enum constant. 12391 if (const DeclRefExpr *DR = 12392 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 12393 if (isa<EnumConstantDecl>(DR->getDecl())) 12394 return true; 12395 12396 // Suppress cases where the value is expanded from a macro, unless that macro 12397 // is how a language represents a boolean literal. This is the case in both C 12398 // and Objective-C. 12399 SourceLocation BeginLoc = E->getBeginLoc(); 12400 if (BeginLoc.isMacroID()) { 12401 StringRef MacroName = Lexer::getImmediateMacroName( 12402 BeginLoc, S.getSourceManager(), S.getLangOpts()); 12403 return MacroName != "YES" && MacroName != "NO" && 12404 MacroName != "true" && MacroName != "false"; 12405 } 12406 12407 return false; 12408 } 12409 12410 static bool isKnownToHaveUnsignedValue(Expr *E) { 12411 return E->getType()->isIntegerType() && 12412 (!E->getType()->isSignedIntegerType() || 12413 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 12414 } 12415 12416 namespace { 12417 /// The promoted range of values of a type. In general this has the 12418 /// following structure: 12419 /// 12420 /// |-----------| . . . |-----------| 12421 /// ^ ^ ^ ^ 12422 /// Min HoleMin HoleMax Max 12423 /// 12424 /// ... where there is only a hole if a signed type is promoted to unsigned 12425 /// (in which case Min and Max are the smallest and largest representable 12426 /// values). 12427 struct PromotedRange { 12428 // Min, or HoleMax if there is a hole. 12429 llvm::APSInt PromotedMin; 12430 // Max, or HoleMin if there is a hole. 12431 llvm::APSInt PromotedMax; 12432 12433 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 12434 if (R.Width == 0) 12435 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 12436 else if (R.Width >= BitWidth && !Unsigned) { 12437 // Promotion made the type *narrower*. This happens when promoting 12438 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 12439 // Treat all values of 'signed int' as being in range for now. 12440 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 12441 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 12442 } else { 12443 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 12444 .extOrTrunc(BitWidth); 12445 PromotedMin.setIsUnsigned(Unsigned); 12446 12447 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 12448 .extOrTrunc(BitWidth); 12449 PromotedMax.setIsUnsigned(Unsigned); 12450 } 12451 } 12452 12453 // Determine whether this range is contiguous (has no hole). 12454 bool isContiguous() const { return PromotedMin <= PromotedMax; } 12455 12456 // Where a constant value is within the range. 12457 enum ComparisonResult { 12458 LT = 0x1, 12459 LE = 0x2, 12460 GT = 0x4, 12461 GE = 0x8, 12462 EQ = 0x10, 12463 NE = 0x20, 12464 InRangeFlag = 0x40, 12465 12466 Less = LE | LT | NE, 12467 Min = LE | InRangeFlag, 12468 InRange = InRangeFlag, 12469 Max = GE | InRangeFlag, 12470 Greater = GE | GT | NE, 12471 12472 OnlyValue = LE | GE | EQ | InRangeFlag, 12473 InHole = NE 12474 }; 12475 12476 ComparisonResult compare(const llvm::APSInt &Value) const { 12477 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 12478 Value.isUnsigned() == PromotedMin.isUnsigned()); 12479 if (!isContiguous()) { 12480 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 12481 if (Value.isMinValue()) return Min; 12482 if (Value.isMaxValue()) return Max; 12483 if (Value >= PromotedMin) return InRange; 12484 if (Value <= PromotedMax) return InRange; 12485 return InHole; 12486 } 12487 12488 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 12489 case -1: return Less; 12490 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 12491 case 1: 12492 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 12493 case -1: return InRange; 12494 case 0: return Max; 12495 case 1: return Greater; 12496 } 12497 } 12498 12499 llvm_unreachable("impossible compare result"); 12500 } 12501 12502 static llvm::Optional<StringRef> 12503 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 12504 if (Op == BO_Cmp) { 12505 ComparisonResult LTFlag = LT, GTFlag = GT; 12506 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 12507 12508 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 12509 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 12510 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 12511 return llvm::None; 12512 } 12513 12514 ComparisonResult TrueFlag, FalseFlag; 12515 if (Op == BO_EQ) { 12516 TrueFlag = EQ; 12517 FalseFlag = NE; 12518 } else if (Op == BO_NE) { 12519 TrueFlag = NE; 12520 FalseFlag = EQ; 12521 } else { 12522 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 12523 TrueFlag = LT; 12524 FalseFlag = GE; 12525 } else { 12526 TrueFlag = GT; 12527 FalseFlag = LE; 12528 } 12529 if (Op == BO_GE || Op == BO_LE) 12530 std::swap(TrueFlag, FalseFlag); 12531 } 12532 if (R & TrueFlag) 12533 return StringRef("true"); 12534 if (R & FalseFlag) 12535 return StringRef("false"); 12536 return llvm::None; 12537 } 12538 }; 12539 } 12540 12541 static bool HasEnumType(Expr *E) { 12542 // Strip off implicit integral promotions. 12543 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12544 if (ICE->getCastKind() != CK_IntegralCast && 12545 ICE->getCastKind() != CK_NoOp) 12546 break; 12547 E = ICE->getSubExpr(); 12548 } 12549 12550 return E->getType()->isEnumeralType(); 12551 } 12552 12553 static int classifyConstantValue(Expr *Constant) { 12554 // The values of this enumeration are used in the diagnostics 12555 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 12556 enum ConstantValueKind { 12557 Miscellaneous = 0, 12558 LiteralTrue, 12559 LiteralFalse 12560 }; 12561 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 12562 return BL->getValue() ? ConstantValueKind::LiteralTrue 12563 : ConstantValueKind::LiteralFalse; 12564 return ConstantValueKind::Miscellaneous; 12565 } 12566 12567 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 12568 Expr *Constant, Expr *Other, 12569 const llvm::APSInt &Value, 12570 bool RhsConstant) { 12571 if (S.inTemplateInstantiation()) 12572 return false; 12573 12574 Expr *OriginalOther = Other; 12575 12576 Constant = Constant->IgnoreParenImpCasts(); 12577 Other = Other->IgnoreParenImpCasts(); 12578 12579 // Suppress warnings on tautological comparisons between values of the same 12580 // enumeration type. There are only two ways we could warn on this: 12581 // - If the constant is outside the range of representable values of 12582 // the enumeration. In such a case, we should warn about the cast 12583 // to enumeration type, not about the comparison. 12584 // - If the constant is the maximum / minimum in-range value. For an 12585 // enumeratin type, such comparisons can be meaningful and useful. 12586 if (Constant->getType()->isEnumeralType() && 12587 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 12588 return false; 12589 12590 IntRange OtherValueRange = GetExprRange( 12591 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 12592 12593 QualType OtherT = Other->getType(); 12594 if (const auto *AT = OtherT->getAs<AtomicType>()) 12595 OtherT = AT->getValueType(); 12596 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 12597 12598 // Special case for ObjC BOOL on targets where its a typedef for a signed char 12599 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 12600 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 12601 S.NSAPIObj->isObjCBOOLType(OtherT) && 12602 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 12603 12604 // Whether we're treating Other as being a bool because of the form of 12605 // expression despite it having another type (typically 'int' in C). 12606 bool OtherIsBooleanDespiteType = 12607 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 12608 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 12609 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 12610 12611 // Check if all values in the range of possible values of this expression 12612 // lead to the same comparison outcome. 12613 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 12614 Value.isUnsigned()); 12615 auto Cmp = OtherPromotedValueRange.compare(Value); 12616 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 12617 if (!Result) 12618 return false; 12619 12620 // Also consider the range determined by the type alone. This allows us to 12621 // classify the warning under the proper diagnostic group. 12622 bool TautologicalTypeCompare = false; 12623 { 12624 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 12625 Value.isUnsigned()); 12626 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 12627 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 12628 RhsConstant)) { 12629 TautologicalTypeCompare = true; 12630 Cmp = TypeCmp; 12631 Result = TypeResult; 12632 } 12633 } 12634 12635 // Don't warn if the non-constant operand actually always evaluates to the 12636 // same value. 12637 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 12638 return false; 12639 12640 // Suppress the diagnostic for an in-range comparison if the constant comes 12641 // from a macro or enumerator. We don't want to diagnose 12642 // 12643 // some_long_value <= INT_MAX 12644 // 12645 // when sizeof(int) == sizeof(long). 12646 bool InRange = Cmp & PromotedRange::InRangeFlag; 12647 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 12648 return false; 12649 12650 // A comparison of an unsigned bit-field against 0 is really a type problem, 12651 // even though at the type level the bit-field might promote to 'signed int'. 12652 if (Other->refersToBitField() && InRange && Value == 0 && 12653 Other->getType()->isUnsignedIntegerOrEnumerationType()) 12654 TautologicalTypeCompare = true; 12655 12656 // If this is a comparison to an enum constant, include that 12657 // constant in the diagnostic. 12658 const EnumConstantDecl *ED = nullptr; 12659 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 12660 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 12661 12662 // Should be enough for uint128 (39 decimal digits) 12663 SmallString<64> PrettySourceValue; 12664 llvm::raw_svector_ostream OS(PrettySourceValue); 12665 if (ED) { 12666 OS << '\'' << *ED << "' (" << Value << ")"; 12667 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 12668 Constant->IgnoreParenImpCasts())) { 12669 OS << (BL->getValue() ? "YES" : "NO"); 12670 } else { 12671 OS << Value; 12672 } 12673 12674 if (!TautologicalTypeCompare) { 12675 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 12676 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 12677 << E->getOpcodeStr() << OS.str() << *Result 12678 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12679 return true; 12680 } 12681 12682 if (IsObjCSignedCharBool) { 12683 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12684 S.PDiag(diag::warn_tautological_compare_objc_bool) 12685 << OS.str() << *Result); 12686 return true; 12687 } 12688 12689 // FIXME: We use a somewhat different formatting for the in-range cases and 12690 // cases involving boolean values for historical reasons. We should pick a 12691 // consistent way of presenting these diagnostics. 12692 if (!InRange || Other->isKnownToHaveBooleanValue()) { 12693 12694 S.DiagRuntimeBehavior( 12695 E->getOperatorLoc(), E, 12696 S.PDiag(!InRange ? diag::warn_out_of_range_compare 12697 : diag::warn_tautological_bool_compare) 12698 << OS.str() << classifyConstantValue(Constant) << OtherT 12699 << OtherIsBooleanDespiteType << *Result 12700 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 12701 } else { 12702 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 12703 unsigned Diag = 12704 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 12705 ? (HasEnumType(OriginalOther) 12706 ? diag::warn_unsigned_enum_always_true_comparison 12707 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 12708 : diag::warn_unsigned_always_true_comparison) 12709 : diag::warn_tautological_constant_compare; 12710 12711 S.Diag(E->getOperatorLoc(), Diag) 12712 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 12713 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12714 } 12715 12716 return true; 12717 } 12718 12719 /// Analyze the operands of the given comparison. Implements the 12720 /// fallback case from AnalyzeComparison. 12721 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 12722 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12723 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12724 } 12725 12726 /// Implements -Wsign-compare. 12727 /// 12728 /// \param E the binary operator to check for warnings 12729 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 12730 // The type the comparison is being performed in. 12731 QualType T = E->getLHS()->getType(); 12732 12733 // Only analyze comparison operators where both sides have been converted to 12734 // the same type. 12735 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 12736 return AnalyzeImpConvsInComparison(S, E); 12737 12738 // Don't analyze value-dependent comparisons directly. 12739 if (E->isValueDependent()) 12740 return AnalyzeImpConvsInComparison(S, E); 12741 12742 Expr *LHS = E->getLHS(); 12743 Expr *RHS = E->getRHS(); 12744 12745 if (T->isIntegralType(S.Context)) { 12746 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 12747 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 12748 12749 // We don't care about expressions whose result is a constant. 12750 if (RHSValue && LHSValue) 12751 return AnalyzeImpConvsInComparison(S, E); 12752 12753 // We only care about expressions where just one side is literal 12754 if ((bool)RHSValue ^ (bool)LHSValue) { 12755 // Is the constant on the RHS or LHS? 12756 const bool RhsConstant = (bool)RHSValue; 12757 Expr *Const = RhsConstant ? RHS : LHS; 12758 Expr *Other = RhsConstant ? LHS : RHS; 12759 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 12760 12761 // Check whether an integer constant comparison results in a value 12762 // of 'true' or 'false'. 12763 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12764 return AnalyzeImpConvsInComparison(S, E); 12765 } 12766 } 12767 12768 if (!T->hasUnsignedIntegerRepresentation()) { 12769 // We don't do anything special if this isn't an unsigned integral 12770 // comparison: we're only interested in integral comparisons, and 12771 // signed comparisons only happen in cases we don't care to warn about. 12772 return AnalyzeImpConvsInComparison(S, E); 12773 } 12774 12775 LHS = LHS->IgnoreParenImpCasts(); 12776 RHS = RHS->IgnoreParenImpCasts(); 12777 12778 if (!S.getLangOpts().CPlusPlus) { 12779 // Avoid warning about comparison of integers with different signs when 12780 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12781 // the type of `E`. 12782 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12783 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12784 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12785 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12786 } 12787 12788 // Check to see if one of the (unmodified) operands is of different 12789 // signedness. 12790 Expr *signedOperand, *unsignedOperand; 12791 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12792 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12793 "unsigned comparison between two signed integer expressions?"); 12794 signedOperand = LHS; 12795 unsignedOperand = RHS; 12796 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12797 signedOperand = RHS; 12798 unsignedOperand = LHS; 12799 } else { 12800 return AnalyzeImpConvsInComparison(S, E); 12801 } 12802 12803 // Otherwise, calculate the effective range of the signed operand. 12804 IntRange signedRange = GetExprRange( 12805 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12806 12807 // Go ahead and analyze implicit conversions in the operands. Note 12808 // that we skip the implicit conversions on both sides. 12809 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12810 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12811 12812 // If the signed range is non-negative, -Wsign-compare won't fire. 12813 if (signedRange.NonNegative) 12814 return; 12815 12816 // For (in)equality comparisons, if the unsigned operand is a 12817 // constant which cannot collide with a overflowed signed operand, 12818 // then reinterpreting the signed operand as unsigned will not 12819 // change the result of the comparison. 12820 if (E->isEqualityOp()) { 12821 unsigned comparisonWidth = S.Context.getIntWidth(T); 12822 IntRange unsignedRange = 12823 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12824 /*Approximate*/ true); 12825 12826 // We should never be unable to prove that the unsigned operand is 12827 // non-negative. 12828 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12829 12830 if (unsignedRange.Width < comparisonWidth) 12831 return; 12832 } 12833 12834 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12835 S.PDiag(diag::warn_mixed_sign_comparison) 12836 << LHS->getType() << RHS->getType() 12837 << LHS->getSourceRange() << RHS->getSourceRange()); 12838 } 12839 12840 /// Analyzes an attempt to assign the given value to a bitfield. 12841 /// 12842 /// Returns true if there was something fishy about the attempt. 12843 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12844 SourceLocation InitLoc) { 12845 assert(Bitfield->isBitField()); 12846 if (Bitfield->isInvalidDecl()) 12847 return false; 12848 12849 // White-list bool bitfields. 12850 QualType BitfieldType = Bitfield->getType(); 12851 if (BitfieldType->isBooleanType()) 12852 return false; 12853 12854 if (BitfieldType->isEnumeralType()) { 12855 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12856 // If the underlying enum type was not explicitly specified as an unsigned 12857 // type and the enum contain only positive values, MSVC++ will cause an 12858 // inconsistency by storing this as a signed type. 12859 if (S.getLangOpts().CPlusPlus11 && 12860 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12861 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12862 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12863 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12864 << BitfieldEnumDecl; 12865 } 12866 } 12867 12868 if (Bitfield->getType()->isBooleanType()) 12869 return false; 12870 12871 // Ignore value- or type-dependent expressions. 12872 if (Bitfield->getBitWidth()->isValueDependent() || 12873 Bitfield->getBitWidth()->isTypeDependent() || 12874 Init->isValueDependent() || 12875 Init->isTypeDependent()) 12876 return false; 12877 12878 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12879 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12880 12881 Expr::EvalResult Result; 12882 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12883 Expr::SE_AllowSideEffects)) { 12884 // The RHS is not constant. If the RHS has an enum type, make sure the 12885 // bitfield is wide enough to hold all the values of the enum without 12886 // truncation. 12887 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12888 EnumDecl *ED = EnumTy->getDecl(); 12889 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12890 12891 // Enum types are implicitly signed on Windows, so check if there are any 12892 // negative enumerators to see if the enum was intended to be signed or 12893 // not. 12894 bool SignedEnum = ED->getNumNegativeBits() > 0; 12895 12896 // Check for surprising sign changes when assigning enum values to a 12897 // bitfield of different signedness. If the bitfield is signed and we 12898 // have exactly the right number of bits to store this unsigned enum, 12899 // suggest changing the enum to an unsigned type. This typically happens 12900 // on Windows where unfixed enums always use an underlying type of 'int'. 12901 unsigned DiagID = 0; 12902 if (SignedEnum && !SignedBitfield) { 12903 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12904 } else if (SignedBitfield && !SignedEnum && 12905 ED->getNumPositiveBits() == FieldWidth) { 12906 DiagID = diag::warn_signed_bitfield_enum_conversion; 12907 } 12908 12909 if (DiagID) { 12910 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12911 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12912 SourceRange TypeRange = 12913 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12914 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12915 << SignedEnum << TypeRange; 12916 } 12917 12918 // Compute the required bitwidth. If the enum has negative values, we need 12919 // one more bit than the normal number of positive bits to represent the 12920 // sign bit. 12921 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12922 ED->getNumNegativeBits()) 12923 : ED->getNumPositiveBits(); 12924 12925 // Check the bitwidth. 12926 if (BitsNeeded > FieldWidth) { 12927 Expr *WidthExpr = Bitfield->getBitWidth(); 12928 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12929 << Bitfield << ED; 12930 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12931 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12932 } 12933 } 12934 12935 return false; 12936 } 12937 12938 llvm::APSInt Value = Result.Val.getInt(); 12939 12940 unsigned OriginalWidth = Value.getBitWidth(); 12941 12942 if (!Value.isSigned() || Value.isNegative()) 12943 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12944 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12945 OriginalWidth = Value.getMinSignedBits(); 12946 12947 if (OriginalWidth <= FieldWidth) 12948 return false; 12949 12950 // Compute the value which the bitfield will contain. 12951 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12952 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12953 12954 // Check whether the stored value is equal to the original value. 12955 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12956 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12957 return false; 12958 12959 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12960 // therefore don't strictly fit into a signed bitfield of width 1. 12961 if (FieldWidth == 1 && Value == 1) 12962 return false; 12963 12964 std::string PrettyValue = toString(Value, 10); 12965 std::string PrettyTrunc = toString(TruncatedValue, 10); 12966 12967 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12968 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12969 << Init->getSourceRange(); 12970 12971 return true; 12972 } 12973 12974 /// Analyze the given simple or compound assignment for warning-worthy 12975 /// operations. 12976 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12977 // Just recurse on the LHS. 12978 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12979 12980 // We want to recurse on the RHS as normal unless we're assigning to 12981 // a bitfield. 12982 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12983 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12984 E->getOperatorLoc())) { 12985 // Recurse, ignoring any implicit conversions on the RHS. 12986 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12987 E->getOperatorLoc()); 12988 } 12989 } 12990 12991 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12992 12993 // Diagnose implicitly sequentially-consistent atomic assignment. 12994 if (E->getLHS()->getType()->isAtomicType()) 12995 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12996 } 12997 12998 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12999 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 13000 SourceLocation CContext, unsigned diag, 13001 bool pruneControlFlow = false) { 13002 if (pruneControlFlow) { 13003 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13004 S.PDiag(diag) 13005 << SourceType << T << E->getSourceRange() 13006 << SourceRange(CContext)); 13007 return; 13008 } 13009 S.Diag(E->getExprLoc(), diag) 13010 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 13011 } 13012 13013 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 13014 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 13015 SourceLocation CContext, 13016 unsigned diag, bool pruneControlFlow = false) { 13017 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 13018 } 13019 13020 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 13021 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 13022 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 13023 } 13024 13025 static void adornObjCBoolConversionDiagWithTernaryFixit( 13026 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 13027 Expr *Ignored = SourceExpr->IgnoreImplicit(); 13028 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 13029 Ignored = OVE->getSourceExpr(); 13030 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 13031 isa<BinaryOperator>(Ignored) || 13032 isa<CXXOperatorCallExpr>(Ignored); 13033 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 13034 if (NeedsParens) 13035 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 13036 << FixItHint::CreateInsertion(EndLoc, ")"); 13037 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 13038 } 13039 13040 /// Diagnose an implicit cast from a floating point value to an integer value. 13041 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 13042 SourceLocation CContext) { 13043 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 13044 const bool PruneWarnings = S.inTemplateInstantiation(); 13045 13046 Expr *InnerE = E->IgnoreParenImpCasts(); 13047 // We also want to warn on, e.g., "int i = -1.234" 13048 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 13049 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 13050 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 13051 13052 const bool IsLiteral = 13053 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 13054 13055 llvm::APFloat Value(0.0); 13056 bool IsConstant = 13057 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 13058 if (!IsConstant) { 13059 if (isObjCSignedCharBool(S, T)) { 13060 return adornObjCBoolConversionDiagWithTernaryFixit( 13061 S, E, 13062 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 13063 << E->getType()); 13064 } 13065 13066 return DiagnoseImpCast(S, E, T, CContext, 13067 diag::warn_impcast_float_integer, PruneWarnings); 13068 } 13069 13070 bool isExact = false; 13071 13072 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 13073 T->hasUnsignedIntegerRepresentation()); 13074 llvm::APFloat::opStatus Result = Value.convertToInteger( 13075 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 13076 13077 // FIXME: Force the precision of the source value down so we don't print 13078 // digits which are usually useless (we don't really care here if we 13079 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 13080 // would automatically print the shortest representation, but it's a bit 13081 // tricky to implement. 13082 SmallString<16> PrettySourceValue; 13083 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 13084 precision = (precision * 59 + 195) / 196; 13085 Value.toString(PrettySourceValue, precision); 13086 13087 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 13088 return adornObjCBoolConversionDiagWithTernaryFixit( 13089 S, E, 13090 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 13091 << PrettySourceValue); 13092 } 13093 13094 if (Result == llvm::APFloat::opOK && isExact) { 13095 if (IsLiteral) return; 13096 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 13097 PruneWarnings); 13098 } 13099 13100 // Conversion of a floating-point value to a non-bool integer where the 13101 // integral part cannot be represented by the integer type is undefined. 13102 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 13103 return DiagnoseImpCast( 13104 S, E, T, CContext, 13105 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 13106 : diag::warn_impcast_float_to_integer_out_of_range, 13107 PruneWarnings); 13108 13109 unsigned DiagID = 0; 13110 if (IsLiteral) { 13111 // Warn on floating point literal to integer. 13112 DiagID = diag::warn_impcast_literal_float_to_integer; 13113 } else if (IntegerValue == 0) { 13114 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 13115 return DiagnoseImpCast(S, E, T, CContext, 13116 diag::warn_impcast_float_integer, PruneWarnings); 13117 } 13118 // Warn on non-zero to zero conversion. 13119 DiagID = diag::warn_impcast_float_to_integer_zero; 13120 } else { 13121 if (IntegerValue.isUnsigned()) { 13122 if (!IntegerValue.isMaxValue()) { 13123 return DiagnoseImpCast(S, E, T, CContext, 13124 diag::warn_impcast_float_integer, PruneWarnings); 13125 } 13126 } else { // IntegerValue.isSigned() 13127 if (!IntegerValue.isMaxSignedValue() && 13128 !IntegerValue.isMinSignedValue()) { 13129 return DiagnoseImpCast(S, E, T, CContext, 13130 diag::warn_impcast_float_integer, PruneWarnings); 13131 } 13132 } 13133 // Warn on evaluatable floating point expression to integer conversion. 13134 DiagID = diag::warn_impcast_float_to_integer; 13135 } 13136 13137 SmallString<16> PrettyTargetValue; 13138 if (IsBool) 13139 PrettyTargetValue = Value.isZero() ? "false" : "true"; 13140 else 13141 IntegerValue.toString(PrettyTargetValue); 13142 13143 if (PruneWarnings) { 13144 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13145 S.PDiag(DiagID) 13146 << E->getType() << T.getUnqualifiedType() 13147 << PrettySourceValue << PrettyTargetValue 13148 << E->getSourceRange() << SourceRange(CContext)); 13149 } else { 13150 S.Diag(E->getExprLoc(), DiagID) 13151 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 13152 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 13153 } 13154 } 13155 13156 /// Analyze the given compound assignment for the possible losing of 13157 /// floating-point precision. 13158 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 13159 assert(isa<CompoundAssignOperator>(E) && 13160 "Must be compound assignment operation"); 13161 // Recurse on the LHS and RHS in here 13162 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 13163 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 13164 13165 if (E->getLHS()->getType()->isAtomicType()) 13166 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 13167 13168 // Now check the outermost expression 13169 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 13170 const auto *RBT = cast<CompoundAssignOperator>(E) 13171 ->getComputationResultType() 13172 ->getAs<BuiltinType>(); 13173 13174 // The below checks assume source is floating point. 13175 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 13176 13177 // If source is floating point but target is an integer. 13178 if (ResultBT->isInteger()) 13179 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 13180 E->getExprLoc(), diag::warn_impcast_float_integer); 13181 13182 if (!ResultBT->isFloatingPoint()) 13183 return; 13184 13185 // If both source and target are floating points, warn about losing precision. 13186 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 13187 QualType(ResultBT, 0), QualType(RBT, 0)); 13188 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 13189 // warn about dropping FP rank. 13190 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 13191 diag::warn_impcast_float_result_precision); 13192 } 13193 13194 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 13195 IntRange Range) { 13196 if (!Range.Width) return "0"; 13197 13198 llvm::APSInt ValueInRange = Value; 13199 ValueInRange.setIsSigned(!Range.NonNegative); 13200 ValueInRange = ValueInRange.trunc(Range.Width); 13201 return toString(ValueInRange, 10); 13202 } 13203 13204 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 13205 if (!isa<ImplicitCastExpr>(Ex)) 13206 return false; 13207 13208 Expr *InnerE = Ex->IgnoreParenImpCasts(); 13209 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 13210 const Type *Source = 13211 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 13212 if (Target->isDependentType()) 13213 return false; 13214 13215 const BuiltinType *FloatCandidateBT = 13216 dyn_cast<BuiltinType>(ToBool ? Source : Target); 13217 const Type *BoolCandidateType = ToBool ? Target : Source; 13218 13219 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 13220 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 13221 } 13222 13223 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 13224 SourceLocation CC) { 13225 unsigned NumArgs = TheCall->getNumArgs(); 13226 for (unsigned i = 0; i < NumArgs; ++i) { 13227 Expr *CurrA = TheCall->getArg(i); 13228 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 13229 continue; 13230 13231 bool IsSwapped = ((i > 0) && 13232 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 13233 IsSwapped |= ((i < (NumArgs - 1)) && 13234 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 13235 if (IsSwapped) { 13236 // Warn on this floating-point to bool conversion. 13237 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 13238 CurrA->getType(), CC, 13239 diag::warn_impcast_floating_point_to_bool); 13240 } 13241 } 13242 } 13243 13244 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 13245 SourceLocation CC) { 13246 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 13247 E->getExprLoc())) 13248 return; 13249 13250 // Don't warn on functions which have return type nullptr_t. 13251 if (isa<CallExpr>(E)) 13252 return; 13253 13254 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 13255 const Expr::NullPointerConstantKind NullKind = 13256 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 13257 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 13258 return; 13259 13260 // Return if target type is a safe conversion. 13261 if (T->isAnyPointerType() || T->isBlockPointerType() || 13262 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 13263 return; 13264 13265 SourceLocation Loc = E->getSourceRange().getBegin(); 13266 13267 // Venture through the macro stacks to get to the source of macro arguments. 13268 // The new location is a better location than the complete location that was 13269 // passed in. 13270 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 13271 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 13272 13273 // __null is usually wrapped in a macro. Go up a macro if that is the case. 13274 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 13275 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 13276 Loc, S.SourceMgr, S.getLangOpts()); 13277 if (MacroName == "NULL") 13278 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 13279 } 13280 13281 // Only warn if the null and context location are in the same macro expansion. 13282 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 13283 return; 13284 13285 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 13286 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 13287 << FixItHint::CreateReplacement(Loc, 13288 S.getFixItZeroLiteralForType(T, Loc)); 13289 } 13290 13291 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 13292 ObjCArrayLiteral *ArrayLiteral); 13293 13294 static void 13295 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 13296 ObjCDictionaryLiteral *DictionaryLiteral); 13297 13298 /// Check a single element within a collection literal against the 13299 /// target element type. 13300 static void checkObjCCollectionLiteralElement(Sema &S, 13301 QualType TargetElementType, 13302 Expr *Element, 13303 unsigned ElementKind) { 13304 // Skip a bitcast to 'id' or qualified 'id'. 13305 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 13306 if (ICE->getCastKind() == CK_BitCast && 13307 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 13308 Element = ICE->getSubExpr(); 13309 } 13310 13311 QualType ElementType = Element->getType(); 13312 ExprResult ElementResult(Element); 13313 if (ElementType->getAs<ObjCObjectPointerType>() && 13314 S.CheckSingleAssignmentConstraints(TargetElementType, 13315 ElementResult, 13316 false, false) 13317 != Sema::Compatible) { 13318 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 13319 << ElementType << ElementKind << TargetElementType 13320 << Element->getSourceRange(); 13321 } 13322 13323 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 13324 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 13325 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 13326 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 13327 } 13328 13329 /// Check an Objective-C array literal being converted to the given 13330 /// target type. 13331 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 13332 ObjCArrayLiteral *ArrayLiteral) { 13333 if (!S.NSArrayDecl) 13334 return; 13335 13336 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 13337 if (!TargetObjCPtr) 13338 return; 13339 13340 if (TargetObjCPtr->isUnspecialized() || 13341 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 13342 != S.NSArrayDecl->getCanonicalDecl()) 13343 return; 13344 13345 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 13346 if (TypeArgs.size() != 1) 13347 return; 13348 13349 QualType TargetElementType = TypeArgs[0]; 13350 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 13351 checkObjCCollectionLiteralElement(S, TargetElementType, 13352 ArrayLiteral->getElement(I), 13353 0); 13354 } 13355 } 13356 13357 /// Check an Objective-C dictionary literal being converted to the given 13358 /// target type. 13359 static void 13360 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 13361 ObjCDictionaryLiteral *DictionaryLiteral) { 13362 if (!S.NSDictionaryDecl) 13363 return; 13364 13365 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 13366 if (!TargetObjCPtr) 13367 return; 13368 13369 if (TargetObjCPtr->isUnspecialized() || 13370 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 13371 != S.NSDictionaryDecl->getCanonicalDecl()) 13372 return; 13373 13374 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 13375 if (TypeArgs.size() != 2) 13376 return; 13377 13378 QualType TargetKeyType = TypeArgs[0]; 13379 QualType TargetObjectType = TypeArgs[1]; 13380 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 13381 auto Element = DictionaryLiteral->getKeyValueElement(I); 13382 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 13383 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 13384 } 13385 } 13386 13387 // Helper function to filter out cases for constant width constant conversion. 13388 // Don't warn on char array initialization or for non-decimal values. 13389 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 13390 SourceLocation CC) { 13391 // If initializing from a constant, and the constant starts with '0', 13392 // then it is a binary, octal, or hexadecimal. Allow these constants 13393 // to fill all the bits, even if there is a sign change. 13394 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 13395 const char FirstLiteralCharacter = 13396 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 13397 if (FirstLiteralCharacter == '0') 13398 return false; 13399 } 13400 13401 // If the CC location points to a '{', and the type is char, then assume 13402 // assume it is an array initialization. 13403 if (CC.isValid() && T->isCharType()) { 13404 const char FirstContextCharacter = 13405 S.getSourceManager().getCharacterData(CC)[0]; 13406 if (FirstContextCharacter == '{') 13407 return false; 13408 } 13409 13410 return true; 13411 } 13412 13413 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 13414 const auto *IL = dyn_cast<IntegerLiteral>(E); 13415 if (!IL) { 13416 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 13417 if (UO->getOpcode() == UO_Minus) 13418 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 13419 } 13420 } 13421 13422 return IL; 13423 } 13424 13425 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 13426 E = E->IgnoreParenImpCasts(); 13427 SourceLocation ExprLoc = E->getExprLoc(); 13428 13429 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 13430 BinaryOperator::Opcode Opc = BO->getOpcode(); 13431 Expr::EvalResult Result; 13432 // Do not diagnose unsigned shifts. 13433 if (Opc == BO_Shl) { 13434 const auto *LHS = getIntegerLiteral(BO->getLHS()); 13435 const auto *RHS = getIntegerLiteral(BO->getRHS()); 13436 if (LHS && LHS->getValue() == 0) 13437 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 13438 else if (!E->isValueDependent() && LHS && RHS && 13439 RHS->getValue().isNonNegative() && 13440 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 13441 S.Diag(ExprLoc, diag::warn_left_shift_always) 13442 << (Result.Val.getInt() != 0); 13443 else if (E->getType()->isSignedIntegerType()) 13444 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 13445 } 13446 } 13447 13448 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 13449 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 13450 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 13451 if (!LHS || !RHS) 13452 return; 13453 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 13454 (RHS->getValue() == 0 || RHS->getValue() == 1)) 13455 // Do not diagnose common idioms. 13456 return; 13457 if (LHS->getValue() != 0 && RHS->getValue() != 0) 13458 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 13459 } 13460 } 13461 13462 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 13463 SourceLocation CC, 13464 bool *ICContext = nullptr, 13465 bool IsListInit = false) { 13466 if (E->isTypeDependent() || E->isValueDependent()) return; 13467 13468 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 13469 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 13470 if (Source == Target) return; 13471 if (Target->isDependentType()) return; 13472 13473 // If the conversion context location is invalid don't complain. We also 13474 // don't want to emit a warning if the issue occurs from the expansion of 13475 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 13476 // delay this check as long as possible. Once we detect we are in that 13477 // scenario, we just return. 13478 if (CC.isInvalid()) 13479 return; 13480 13481 if (Source->isAtomicType()) 13482 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 13483 13484 // Diagnose implicit casts to bool. 13485 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 13486 if (isa<StringLiteral>(E)) 13487 // Warn on string literal to bool. Checks for string literals in logical 13488 // and expressions, for instance, assert(0 && "error here"), are 13489 // prevented by a check in AnalyzeImplicitConversions(). 13490 return DiagnoseImpCast(S, E, T, CC, 13491 diag::warn_impcast_string_literal_to_bool); 13492 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 13493 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 13494 // This covers the literal expressions that evaluate to Objective-C 13495 // objects. 13496 return DiagnoseImpCast(S, E, T, CC, 13497 diag::warn_impcast_objective_c_literal_to_bool); 13498 } 13499 if (Source->isPointerType() || Source->canDecayToPointerType()) { 13500 // Warn on pointer to bool conversion that is always true. 13501 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 13502 SourceRange(CC)); 13503 } 13504 } 13505 13506 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 13507 // is a typedef for signed char (macOS), then that constant value has to be 1 13508 // or 0. 13509 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 13510 Expr::EvalResult Result; 13511 if (E->EvaluateAsInt(Result, S.getASTContext(), 13512 Expr::SE_AllowSideEffects)) { 13513 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 13514 adornObjCBoolConversionDiagWithTernaryFixit( 13515 S, E, 13516 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 13517 << toString(Result.Val.getInt(), 10)); 13518 } 13519 return; 13520 } 13521 } 13522 13523 // Check implicit casts from Objective-C collection literals to specialized 13524 // collection types, e.g., NSArray<NSString *> *. 13525 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 13526 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 13527 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 13528 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 13529 13530 // Strip vector types. 13531 if (isa<VectorType>(Source)) { 13532 if (Target->isVLSTBuiltinType() && 13533 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 13534 QualType(Source, 0)) || 13535 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 13536 QualType(Source, 0)))) 13537 return; 13538 13539 if (!isa<VectorType>(Target)) { 13540 if (S.SourceMgr.isInSystemMacro(CC)) 13541 return; 13542 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 13543 } 13544 13545 // If the vector cast is cast between two vectors of the same size, it is 13546 // a bitcast, not a conversion. 13547 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 13548 return; 13549 13550 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 13551 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 13552 } 13553 if (auto VecTy = dyn_cast<VectorType>(Target)) 13554 Target = VecTy->getElementType().getTypePtr(); 13555 13556 // Strip complex types. 13557 if (isa<ComplexType>(Source)) { 13558 if (!isa<ComplexType>(Target)) { 13559 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 13560 return; 13561 13562 return DiagnoseImpCast(S, E, T, CC, 13563 S.getLangOpts().CPlusPlus 13564 ? diag::err_impcast_complex_scalar 13565 : diag::warn_impcast_complex_scalar); 13566 } 13567 13568 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 13569 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 13570 } 13571 13572 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 13573 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 13574 13575 // If the source is floating point... 13576 if (SourceBT && SourceBT->isFloatingPoint()) { 13577 // ...and the target is floating point... 13578 if (TargetBT && TargetBT->isFloatingPoint()) { 13579 // ...then warn if we're dropping FP rank. 13580 13581 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 13582 QualType(SourceBT, 0), QualType(TargetBT, 0)); 13583 if (Order > 0) { 13584 // Don't warn about float constants that are precisely 13585 // representable in the target type. 13586 Expr::EvalResult result; 13587 if (E->EvaluateAsRValue(result, S.Context)) { 13588 // Value might be a float, a float vector, or a float complex. 13589 if (IsSameFloatAfterCast(result.Val, 13590 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 13591 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 13592 return; 13593 } 13594 13595 if (S.SourceMgr.isInSystemMacro(CC)) 13596 return; 13597 13598 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 13599 } 13600 // ... or possibly if we're increasing rank, too 13601 else if (Order < 0) { 13602 if (S.SourceMgr.isInSystemMacro(CC)) 13603 return; 13604 13605 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 13606 } 13607 return; 13608 } 13609 13610 // If the target is integral, always warn. 13611 if (TargetBT && TargetBT->isInteger()) { 13612 if (S.SourceMgr.isInSystemMacro(CC)) 13613 return; 13614 13615 DiagnoseFloatingImpCast(S, E, T, CC); 13616 } 13617 13618 // Detect the case where a call result is converted from floating-point to 13619 // to bool, and the final argument to the call is converted from bool, to 13620 // discover this typo: 13621 // 13622 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 13623 // 13624 // FIXME: This is an incredibly special case; is there some more general 13625 // way to detect this class of misplaced-parentheses bug? 13626 if (Target->isBooleanType() && isa<CallExpr>(E)) { 13627 // Check last argument of function call to see if it is an 13628 // implicit cast from a type matching the type the result 13629 // is being cast to. 13630 CallExpr *CEx = cast<CallExpr>(E); 13631 if (unsigned NumArgs = CEx->getNumArgs()) { 13632 Expr *LastA = CEx->getArg(NumArgs - 1); 13633 Expr *InnerE = LastA->IgnoreParenImpCasts(); 13634 if (isa<ImplicitCastExpr>(LastA) && 13635 InnerE->getType()->isBooleanType()) { 13636 // Warn on this floating-point to bool conversion 13637 DiagnoseImpCast(S, E, T, CC, 13638 diag::warn_impcast_floating_point_to_bool); 13639 } 13640 } 13641 } 13642 return; 13643 } 13644 13645 // Valid casts involving fixed point types should be accounted for here. 13646 if (Source->isFixedPointType()) { 13647 if (Target->isUnsaturatedFixedPointType()) { 13648 Expr::EvalResult Result; 13649 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 13650 S.isConstantEvaluated())) { 13651 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 13652 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 13653 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 13654 if (Value > MaxVal || Value < MinVal) { 13655 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13656 S.PDiag(diag::warn_impcast_fixed_point_range) 13657 << Value.toString() << T 13658 << E->getSourceRange() 13659 << clang::SourceRange(CC)); 13660 return; 13661 } 13662 } 13663 } else if (Target->isIntegerType()) { 13664 Expr::EvalResult Result; 13665 if (!S.isConstantEvaluated() && 13666 E->EvaluateAsFixedPoint(Result, S.Context, 13667 Expr::SE_AllowSideEffects)) { 13668 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 13669 13670 bool Overflowed; 13671 llvm::APSInt IntResult = FXResult.convertToInt( 13672 S.Context.getIntWidth(T), 13673 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 13674 13675 if (Overflowed) { 13676 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13677 S.PDiag(diag::warn_impcast_fixed_point_range) 13678 << FXResult.toString() << T 13679 << E->getSourceRange() 13680 << clang::SourceRange(CC)); 13681 return; 13682 } 13683 } 13684 } 13685 } else if (Target->isUnsaturatedFixedPointType()) { 13686 if (Source->isIntegerType()) { 13687 Expr::EvalResult Result; 13688 if (!S.isConstantEvaluated() && 13689 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 13690 llvm::APSInt Value = Result.Val.getInt(); 13691 13692 bool Overflowed; 13693 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 13694 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 13695 13696 if (Overflowed) { 13697 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13698 S.PDiag(diag::warn_impcast_fixed_point_range) 13699 << toString(Value, /*Radix=*/10) << T 13700 << E->getSourceRange() 13701 << clang::SourceRange(CC)); 13702 return; 13703 } 13704 } 13705 } 13706 } 13707 13708 // If we are casting an integer type to a floating point type without 13709 // initialization-list syntax, we might lose accuracy if the floating 13710 // point type has a narrower significand than the integer type. 13711 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 13712 TargetBT->isFloatingType() && !IsListInit) { 13713 // Determine the number of precision bits in the source integer type. 13714 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 13715 /*Approximate*/ true); 13716 unsigned int SourcePrecision = SourceRange.Width; 13717 13718 // Determine the number of precision bits in the 13719 // target floating point type. 13720 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 13721 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13722 13723 if (SourcePrecision > 0 && TargetPrecision > 0 && 13724 SourcePrecision > TargetPrecision) { 13725 13726 if (Optional<llvm::APSInt> SourceInt = 13727 E->getIntegerConstantExpr(S.Context)) { 13728 // If the source integer is a constant, convert it to the target 13729 // floating point type. Issue a warning if the value changes 13730 // during the whole conversion. 13731 llvm::APFloat TargetFloatValue( 13732 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13733 llvm::APFloat::opStatus ConversionStatus = 13734 TargetFloatValue.convertFromAPInt( 13735 *SourceInt, SourceBT->isSignedInteger(), 13736 llvm::APFloat::rmNearestTiesToEven); 13737 13738 if (ConversionStatus != llvm::APFloat::opOK) { 13739 SmallString<32> PrettySourceValue; 13740 SourceInt->toString(PrettySourceValue, 10); 13741 SmallString<32> PrettyTargetValue; 13742 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 13743 13744 S.DiagRuntimeBehavior( 13745 E->getExprLoc(), E, 13746 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 13747 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13748 << E->getSourceRange() << clang::SourceRange(CC)); 13749 } 13750 } else { 13751 // Otherwise, the implicit conversion may lose precision. 13752 DiagnoseImpCast(S, E, T, CC, 13753 diag::warn_impcast_integer_float_precision); 13754 } 13755 } 13756 } 13757 13758 DiagnoseNullConversion(S, E, T, CC); 13759 13760 S.DiscardMisalignedMemberAddress(Target, E); 13761 13762 if (Target->isBooleanType()) 13763 DiagnoseIntInBoolContext(S, E); 13764 13765 if (!Source->isIntegerType() || !Target->isIntegerType()) 13766 return; 13767 13768 // TODO: remove this early return once the false positives for constant->bool 13769 // in templates, macros, etc, are reduced or removed. 13770 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13771 return; 13772 13773 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13774 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13775 return adornObjCBoolConversionDiagWithTernaryFixit( 13776 S, E, 13777 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13778 << E->getType()); 13779 } 13780 13781 IntRange SourceTypeRange = 13782 IntRange::forTargetOfCanonicalType(S.Context, Source); 13783 IntRange LikelySourceRange = 13784 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13785 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13786 13787 if (LikelySourceRange.Width > TargetRange.Width) { 13788 // If the source is a constant, use a default-on diagnostic. 13789 // TODO: this should happen for bitfield stores, too. 13790 Expr::EvalResult Result; 13791 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13792 S.isConstantEvaluated())) { 13793 llvm::APSInt Value(32); 13794 Value = Result.Val.getInt(); 13795 13796 if (S.SourceMgr.isInSystemMacro(CC)) 13797 return; 13798 13799 std::string PrettySourceValue = toString(Value, 10); 13800 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13801 13802 S.DiagRuntimeBehavior( 13803 E->getExprLoc(), E, 13804 S.PDiag(diag::warn_impcast_integer_precision_constant) 13805 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13806 << E->getSourceRange() << SourceRange(CC)); 13807 return; 13808 } 13809 13810 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13811 if (S.SourceMgr.isInSystemMacro(CC)) 13812 return; 13813 13814 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13815 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13816 /* pruneControlFlow */ true); 13817 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13818 } 13819 13820 if (TargetRange.Width > SourceTypeRange.Width) { 13821 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13822 if (UO->getOpcode() == UO_Minus) 13823 if (Source->isUnsignedIntegerType()) { 13824 if (Target->isUnsignedIntegerType()) 13825 return DiagnoseImpCast(S, E, T, CC, 13826 diag::warn_impcast_high_order_zero_bits); 13827 if (Target->isSignedIntegerType()) 13828 return DiagnoseImpCast(S, E, T, CC, 13829 diag::warn_impcast_nonnegative_result); 13830 } 13831 } 13832 13833 if (TargetRange.Width == LikelySourceRange.Width && 13834 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13835 Source->isSignedIntegerType()) { 13836 // Warn when doing a signed to signed conversion, warn if the positive 13837 // source value is exactly the width of the target type, which will 13838 // cause a negative value to be stored. 13839 13840 Expr::EvalResult Result; 13841 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13842 !S.SourceMgr.isInSystemMacro(CC)) { 13843 llvm::APSInt Value = Result.Val.getInt(); 13844 if (isSameWidthConstantConversion(S, E, T, CC)) { 13845 std::string PrettySourceValue = toString(Value, 10); 13846 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13847 13848 S.DiagRuntimeBehavior( 13849 E->getExprLoc(), E, 13850 S.PDiag(diag::warn_impcast_integer_precision_constant) 13851 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13852 << E->getSourceRange() << SourceRange(CC)); 13853 return; 13854 } 13855 } 13856 13857 // Fall through for non-constants to give a sign conversion warning. 13858 } 13859 13860 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13861 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13862 LikelySourceRange.Width == TargetRange.Width)) { 13863 if (S.SourceMgr.isInSystemMacro(CC)) 13864 return; 13865 13866 unsigned DiagID = diag::warn_impcast_integer_sign; 13867 13868 // Traditionally, gcc has warned about this under -Wsign-compare. 13869 // We also want to warn about it in -Wconversion. 13870 // So if -Wconversion is off, use a completely identical diagnostic 13871 // in the sign-compare group. 13872 // The conditional-checking code will 13873 if (ICContext) { 13874 DiagID = diag::warn_impcast_integer_sign_conditional; 13875 *ICContext = true; 13876 } 13877 13878 return DiagnoseImpCast(S, E, T, CC, DiagID); 13879 } 13880 13881 // Diagnose conversions between different enumeration types. 13882 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13883 // type, to give us better diagnostics. 13884 QualType SourceType = E->getType(); 13885 if (!S.getLangOpts().CPlusPlus) { 13886 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13887 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13888 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13889 SourceType = S.Context.getTypeDeclType(Enum); 13890 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13891 } 13892 } 13893 13894 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13895 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13896 if (SourceEnum->getDecl()->hasNameForLinkage() && 13897 TargetEnum->getDecl()->hasNameForLinkage() && 13898 SourceEnum != TargetEnum) { 13899 if (S.SourceMgr.isInSystemMacro(CC)) 13900 return; 13901 13902 return DiagnoseImpCast(S, E, SourceType, T, CC, 13903 diag::warn_impcast_different_enum_types); 13904 } 13905 } 13906 13907 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13908 SourceLocation CC, QualType T); 13909 13910 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13911 SourceLocation CC, bool &ICContext) { 13912 E = E->IgnoreParenImpCasts(); 13913 13914 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13915 return CheckConditionalOperator(S, CO, CC, T); 13916 13917 AnalyzeImplicitConversions(S, E, CC); 13918 if (E->getType() != T) 13919 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13920 } 13921 13922 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13923 SourceLocation CC, QualType T) { 13924 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13925 13926 Expr *TrueExpr = E->getTrueExpr(); 13927 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13928 TrueExpr = BCO->getCommon(); 13929 13930 bool Suspicious = false; 13931 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13932 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13933 13934 if (T->isBooleanType()) 13935 DiagnoseIntInBoolContext(S, E); 13936 13937 // If -Wconversion would have warned about either of the candidates 13938 // for a signedness conversion to the context type... 13939 if (!Suspicious) return; 13940 13941 // ...but it's currently ignored... 13942 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13943 return; 13944 13945 // ...then check whether it would have warned about either of the 13946 // candidates for a signedness conversion to the condition type. 13947 if (E->getType() == T) return; 13948 13949 Suspicious = false; 13950 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13951 E->getType(), CC, &Suspicious); 13952 if (!Suspicious) 13953 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13954 E->getType(), CC, &Suspicious); 13955 } 13956 13957 /// Check conversion of given expression to boolean. 13958 /// Input argument E is a logical expression. 13959 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13960 if (S.getLangOpts().Bool) 13961 return; 13962 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13963 return; 13964 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13965 } 13966 13967 namespace { 13968 struct AnalyzeImplicitConversionsWorkItem { 13969 Expr *E; 13970 SourceLocation CC; 13971 bool IsListInit; 13972 }; 13973 } 13974 13975 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13976 /// that should be visited are added to WorkList. 13977 static void AnalyzeImplicitConversions( 13978 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13979 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13980 Expr *OrigE = Item.E; 13981 SourceLocation CC = Item.CC; 13982 13983 QualType T = OrigE->getType(); 13984 Expr *E = OrigE->IgnoreParenImpCasts(); 13985 13986 // Propagate whether we are in a C++ list initialization expression. 13987 // If so, we do not issue warnings for implicit int-float conversion 13988 // precision loss, because C++11 narrowing already handles it. 13989 bool IsListInit = Item.IsListInit || 13990 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13991 13992 if (E->isTypeDependent() || E->isValueDependent()) 13993 return; 13994 13995 Expr *SourceExpr = E; 13996 // Examine, but don't traverse into the source expression of an 13997 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13998 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13999 // evaluate it in the context of checking the specific conversion to T though. 14000 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 14001 if (auto *Src = OVE->getSourceExpr()) 14002 SourceExpr = Src; 14003 14004 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 14005 if (UO->getOpcode() == UO_Not && 14006 UO->getSubExpr()->isKnownToHaveBooleanValue()) 14007 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 14008 << OrigE->getSourceRange() << T->isBooleanType() 14009 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 14010 14011 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 14012 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 14013 BO->getLHS()->isKnownToHaveBooleanValue() && 14014 BO->getRHS()->isKnownToHaveBooleanValue() && 14015 BO->getLHS()->HasSideEffects(S.Context) && 14016 BO->getRHS()->HasSideEffects(S.Context)) { 14017 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 14018 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 14019 << FixItHint::CreateReplacement( 14020 BO->getOperatorLoc(), 14021 (BO->getOpcode() == BO_And ? "&&" : "||")); 14022 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 14023 } 14024 14025 // For conditional operators, we analyze the arguments as if they 14026 // were being fed directly into the output. 14027 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 14028 CheckConditionalOperator(S, CO, CC, T); 14029 return; 14030 } 14031 14032 // Check implicit argument conversions for function calls. 14033 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 14034 CheckImplicitArgumentConversions(S, Call, CC); 14035 14036 // Go ahead and check any implicit conversions we might have skipped. 14037 // The non-canonical typecheck is just an optimization; 14038 // CheckImplicitConversion will filter out dead implicit conversions. 14039 if (SourceExpr->getType() != T) 14040 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 14041 14042 // Now continue drilling into this expression. 14043 14044 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 14045 // The bound subexpressions in a PseudoObjectExpr are not reachable 14046 // as transitive children. 14047 // FIXME: Use a more uniform representation for this. 14048 for (auto *SE : POE->semantics()) 14049 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 14050 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 14051 } 14052 14053 // Skip past explicit casts. 14054 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 14055 E = CE->getSubExpr()->IgnoreParenImpCasts(); 14056 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 14057 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 14058 WorkList.push_back({E, CC, IsListInit}); 14059 return; 14060 } 14061 14062 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 14063 // Do a somewhat different check with comparison operators. 14064 if (BO->isComparisonOp()) 14065 return AnalyzeComparison(S, BO); 14066 14067 // And with simple assignments. 14068 if (BO->getOpcode() == BO_Assign) 14069 return AnalyzeAssignment(S, BO); 14070 // And with compound assignments. 14071 if (BO->isAssignmentOp()) 14072 return AnalyzeCompoundAssignment(S, BO); 14073 } 14074 14075 // These break the otherwise-useful invariant below. Fortunately, 14076 // we don't really need to recurse into them, because any internal 14077 // expressions should have been analyzed already when they were 14078 // built into statements. 14079 if (isa<StmtExpr>(E)) return; 14080 14081 // Don't descend into unevaluated contexts. 14082 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 14083 14084 // Now just recurse over the expression's children. 14085 CC = E->getExprLoc(); 14086 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 14087 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 14088 for (Stmt *SubStmt : E->children()) { 14089 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 14090 if (!ChildExpr) 14091 continue; 14092 14093 if (IsLogicalAndOperator && 14094 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 14095 // Ignore checking string literals that are in logical and operators. 14096 // This is a common pattern for asserts. 14097 continue; 14098 WorkList.push_back({ChildExpr, CC, IsListInit}); 14099 } 14100 14101 if (BO && BO->isLogicalOp()) { 14102 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 14103 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 14104 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 14105 14106 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 14107 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 14108 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 14109 } 14110 14111 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 14112 if (U->getOpcode() == UO_LNot) { 14113 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 14114 } else if (U->getOpcode() != UO_AddrOf) { 14115 if (U->getSubExpr()->getType()->isAtomicType()) 14116 S.Diag(U->getSubExpr()->getBeginLoc(), 14117 diag::warn_atomic_implicit_seq_cst); 14118 } 14119 } 14120 } 14121 14122 /// AnalyzeImplicitConversions - Find and report any interesting 14123 /// implicit conversions in the given expression. There are a couple 14124 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 14125 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 14126 bool IsListInit/*= false*/) { 14127 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 14128 WorkList.push_back({OrigE, CC, IsListInit}); 14129 while (!WorkList.empty()) 14130 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 14131 } 14132 14133 /// Diagnose integer type and any valid implicit conversion to it. 14134 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 14135 // Taking into account implicit conversions, 14136 // allow any integer. 14137 if (!E->getType()->isIntegerType()) { 14138 S.Diag(E->getBeginLoc(), 14139 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 14140 return true; 14141 } 14142 // Potentially emit standard warnings for implicit conversions if enabled 14143 // using -Wconversion. 14144 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 14145 return false; 14146 } 14147 14148 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 14149 // Returns true when emitting a warning about taking the address of a reference. 14150 static bool CheckForReference(Sema &SemaRef, const Expr *E, 14151 const PartialDiagnostic &PD) { 14152 E = E->IgnoreParenImpCasts(); 14153 14154 const FunctionDecl *FD = nullptr; 14155 14156 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14157 if (!DRE->getDecl()->getType()->isReferenceType()) 14158 return false; 14159 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 14160 if (!M->getMemberDecl()->getType()->isReferenceType()) 14161 return false; 14162 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 14163 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 14164 return false; 14165 FD = Call->getDirectCallee(); 14166 } else { 14167 return false; 14168 } 14169 14170 SemaRef.Diag(E->getExprLoc(), PD); 14171 14172 // If possible, point to location of function. 14173 if (FD) { 14174 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 14175 } 14176 14177 return true; 14178 } 14179 14180 // Returns true if the SourceLocation is expanded from any macro body. 14181 // Returns false if the SourceLocation is invalid, is from not in a macro 14182 // expansion, or is from expanded from a top-level macro argument. 14183 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 14184 if (Loc.isInvalid()) 14185 return false; 14186 14187 while (Loc.isMacroID()) { 14188 if (SM.isMacroBodyExpansion(Loc)) 14189 return true; 14190 Loc = SM.getImmediateMacroCallerLoc(Loc); 14191 } 14192 14193 return false; 14194 } 14195 14196 /// Diagnose pointers that are always non-null. 14197 /// \param E the expression containing the pointer 14198 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 14199 /// compared to a null pointer 14200 /// \param IsEqual True when the comparison is equal to a null pointer 14201 /// \param Range Extra SourceRange to highlight in the diagnostic 14202 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 14203 Expr::NullPointerConstantKind NullKind, 14204 bool IsEqual, SourceRange Range) { 14205 if (!E) 14206 return; 14207 14208 // Don't warn inside macros. 14209 if (E->getExprLoc().isMacroID()) { 14210 const SourceManager &SM = getSourceManager(); 14211 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 14212 IsInAnyMacroBody(SM, Range.getBegin())) 14213 return; 14214 } 14215 E = E->IgnoreImpCasts(); 14216 14217 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 14218 14219 if (isa<CXXThisExpr>(E)) { 14220 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 14221 : diag::warn_this_bool_conversion; 14222 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 14223 return; 14224 } 14225 14226 bool IsAddressOf = false; 14227 14228 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 14229 if (UO->getOpcode() != UO_AddrOf) 14230 return; 14231 IsAddressOf = true; 14232 E = UO->getSubExpr(); 14233 } 14234 14235 if (IsAddressOf) { 14236 unsigned DiagID = IsCompare 14237 ? diag::warn_address_of_reference_null_compare 14238 : diag::warn_address_of_reference_bool_conversion; 14239 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 14240 << IsEqual; 14241 if (CheckForReference(*this, E, PD)) { 14242 return; 14243 } 14244 } 14245 14246 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 14247 bool IsParam = isa<NonNullAttr>(NonnullAttr); 14248 std::string Str; 14249 llvm::raw_string_ostream S(Str); 14250 E->printPretty(S, nullptr, getPrintingPolicy()); 14251 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 14252 : diag::warn_cast_nonnull_to_bool; 14253 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 14254 << E->getSourceRange() << Range << IsEqual; 14255 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 14256 }; 14257 14258 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 14259 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 14260 if (auto *Callee = Call->getDirectCallee()) { 14261 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 14262 ComplainAboutNonnullParamOrCall(A); 14263 return; 14264 } 14265 } 14266 } 14267 14268 // Expect to find a single Decl. Skip anything more complicated. 14269 ValueDecl *D = nullptr; 14270 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 14271 D = R->getDecl(); 14272 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 14273 D = M->getMemberDecl(); 14274 } 14275 14276 // Weak Decls can be null. 14277 if (!D || D->isWeak()) 14278 return; 14279 14280 // Check for parameter decl with nonnull attribute 14281 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 14282 if (getCurFunction() && 14283 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 14284 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 14285 ComplainAboutNonnullParamOrCall(A); 14286 return; 14287 } 14288 14289 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 14290 // Skip function template not specialized yet. 14291 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 14292 return; 14293 auto ParamIter = llvm::find(FD->parameters(), PV); 14294 assert(ParamIter != FD->param_end()); 14295 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 14296 14297 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 14298 if (!NonNull->args_size()) { 14299 ComplainAboutNonnullParamOrCall(NonNull); 14300 return; 14301 } 14302 14303 for (const ParamIdx &ArgNo : NonNull->args()) { 14304 if (ArgNo.getASTIndex() == ParamNo) { 14305 ComplainAboutNonnullParamOrCall(NonNull); 14306 return; 14307 } 14308 } 14309 } 14310 } 14311 } 14312 } 14313 14314 QualType T = D->getType(); 14315 const bool IsArray = T->isArrayType(); 14316 const bool IsFunction = T->isFunctionType(); 14317 14318 // Address of function is used to silence the function warning. 14319 if (IsAddressOf && IsFunction) { 14320 return; 14321 } 14322 14323 // Found nothing. 14324 if (!IsAddressOf && !IsFunction && !IsArray) 14325 return; 14326 14327 // Pretty print the expression for the diagnostic. 14328 std::string Str; 14329 llvm::raw_string_ostream S(Str); 14330 E->printPretty(S, nullptr, getPrintingPolicy()); 14331 14332 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 14333 : diag::warn_impcast_pointer_to_bool; 14334 enum { 14335 AddressOf, 14336 FunctionPointer, 14337 ArrayPointer 14338 } DiagType; 14339 if (IsAddressOf) 14340 DiagType = AddressOf; 14341 else if (IsFunction) 14342 DiagType = FunctionPointer; 14343 else if (IsArray) 14344 DiagType = ArrayPointer; 14345 else 14346 llvm_unreachable("Could not determine diagnostic."); 14347 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 14348 << Range << IsEqual; 14349 14350 if (!IsFunction) 14351 return; 14352 14353 // Suggest '&' to silence the function warning. 14354 Diag(E->getExprLoc(), diag::note_function_warning_silence) 14355 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 14356 14357 // Check to see if '()' fixit should be emitted. 14358 QualType ReturnType; 14359 UnresolvedSet<4> NonTemplateOverloads; 14360 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 14361 if (ReturnType.isNull()) 14362 return; 14363 14364 if (IsCompare) { 14365 // There are two cases here. If there is null constant, the only suggest 14366 // for a pointer return type. If the null is 0, then suggest if the return 14367 // type is a pointer or an integer type. 14368 if (!ReturnType->isPointerType()) { 14369 if (NullKind == Expr::NPCK_ZeroExpression || 14370 NullKind == Expr::NPCK_ZeroLiteral) { 14371 if (!ReturnType->isIntegerType()) 14372 return; 14373 } else { 14374 return; 14375 } 14376 } 14377 } else { // !IsCompare 14378 // For function to bool, only suggest if the function pointer has bool 14379 // return type. 14380 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 14381 return; 14382 } 14383 Diag(E->getExprLoc(), diag::note_function_to_function_call) 14384 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 14385 } 14386 14387 /// Diagnoses "dangerous" implicit conversions within the given 14388 /// expression (which is a full expression). Implements -Wconversion 14389 /// and -Wsign-compare. 14390 /// 14391 /// \param CC the "context" location of the implicit conversion, i.e. 14392 /// the most location of the syntactic entity requiring the implicit 14393 /// conversion 14394 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 14395 // Don't diagnose in unevaluated contexts. 14396 if (isUnevaluatedContext()) 14397 return; 14398 14399 // Don't diagnose for value- or type-dependent expressions. 14400 if (E->isTypeDependent() || E->isValueDependent()) 14401 return; 14402 14403 // Check for array bounds violations in cases where the check isn't triggered 14404 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 14405 // ArraySubscriptExpr is on the RHS of a variable initialization. 14406 CheckArrayAccess(E); 14407 14408 // This is not the right CC for (e.g.) a variable initialization. 14409 AnalyzeImplicitConversions(*this, E, CC); 14410 } 14411 14412 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 14413 /// Input argument E is a logical expression. 14414 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 14415 ::CheckBoolLikeConversion(*this, E, CC); 14416 } 14417 14418 /// Diagnose when expression is an integer constant expression and its evaluation 14419 /// results in integer overflow 14420 void Sema::CheckForIntOverflow (Expr *E) { 14421 // Use a work list to deal with nested struct initializers. 14422 SmallVector<Expr *, 2> Exprs(1, E); 14423 14424 do { 14425 Expr *OriginalE = Exprs.pop_back_val(); 14426 Expr *E = OriginalE->IgnoreParenCasts(); 14427 14428 if (isa<BinaryOperator>(E)) { 14429 E->EvaluateForOverflow(Context); 14430 continue; 14431 } 14432 14433 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 14434 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 14435 else if (isa<ObjCBoxedExpr>(OriginalE)) 14436 E->EvaluateForOverflow(Context); 14437 else if (auto Call = dyn_cast<CallExpr>(E)) 14438 Exprs.append(Call->arg_begin(), Call->arg_end()); 14439 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 14440 Exprs.append(Message->arg_begin(), Message->arg_end()); 14441 } while (!Exprs.empty()); 14442 } 14443 14444 namespace { 14445 14446 /// Visitor for expressions which looks for unsequenced operations on the 14447 /// same object. 14448 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 14449 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 14450 14451 /// A tree of sequenced regions within an expression. Two regions are 14452 /// unsequenced if one is an ancestor or a descendent of the other. When we 14453 /// finish processing an expression with sequencing, such as a comma 14454 /// expression, we fold its tree nodes into its parent, since they are 14455 /// unsequenced with respect to nodes we will visit later. 14456 class SequenceTree { 14457 struct Value { 14458 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 14459 unsigned Parent : 31; 14460 unsigned Merged : 1; 14461 }; 14462 SmallVector<Value, 8> Values; 14463 14464 public: 14465 /// A region within an expression which may be sequenced with respect 14466 /// to some other region. 14467 class Seq { 14468 friend class SequenceTree; 14469 14470 unsigned Index; 14471 14472 explicit Seq(unsigned N) : Index(N) {} 14473 14474 public: 14475 Seq() : Index(0) {} 14476 }; 14477 14478 SequenceTree() { Values.push_back(Value(0)); } 14479 Seq root() const { return Seq(0); } 14480 14481 /// Create a new sequence of operations, which is an unsequenced 14482 /// subset of \p Parent. This sequence of operations is sequenced with 14483 /// respect to other children of \p Parent. 14484 Seq allocate(Seq Parent) { 14485 Values.push_back(Value(Parent.Index)); 14486 return Seq(Values.size() - 1); 14487 } 14488 14489 /// Merge a sequence of operations into its parent. 14490 void merge(Seq S) { 14491 Values[S.Index].Merged = true; 14492 } 14493 14494 /// Determine whether two operations are unsequenced. This operation 14495 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 14496 /// should have been merged into its parent as appropriate. 14497 bool isUnsequenced(Seq Cur, Seq Old) { 14498 unsigned C = representative(Cur.Index); 14499 unsigned Target = representative(Old.Index); 14500 while (C >= Target) { 14501 if (C == Target) 14502 return true; 14503 C = Values[C].Parent; 14504 } 14505 return false; 14506 } 14507 14508 private: 14509 /// Pick a representative for a sequence. 14510 unsigned representative(unsigned K) { 14511 if (Values[K].Merged) 14512 // Perform path compression as we go. 14513 return Values[K].Parent = representative(Values[K].Parent); 14514 return K; 14515 } 14516 }; 14517 14518 /// An object for which we can track unsequenced uses. 14519 using Object = const NamedDecl *; 14520 14521 /// Different flavors of object usage which we track. We only track the 14522 /// least-sequenced usage of each kind. 14523 enum UsageKind { 14524 /// A read of an object. Multiple unsequenced reads are OK. 14525 UK_Use, 14526 14527 /// A modification of an object which is sequenced before the value 14528 /// computation of the expression, such as ++n in C++. 14529 UK_ModAsValue, 14530 14531 /// A modification of an object which is not sequenced before the value 14532 /// computation of the expression, such as n++. 14533 UK_ModAsSideEffect, 14534 14535 UK_Count = UK_ModAsSideEffect + 1 14536 }; 14537 14538 /// Bundle together a sequencing region and the expression corresponding 14539 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 14540 struct Usage { 14541 const Expr *UsageExpr; 14542 SequenceTree::Seq Seq; 14543 14544 Usage() : UsageExpr(nullptr) {} 14545 }; 14546 14547 struct UsageInfo { 14548 Usage Uses[UK_Count]; 14549 14550 /// Have we issued a diagnostic for this object already? 14551 bool Diagnosed; 14552 14553 UsageInfo() : Diagnosed(false) {} 14554 }; 14555 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 14556 14557 Sema &SemaRef; 14558 14559 /// Sequenced regions within the expression. 14560 SequenceTree Tree; 14561 14562 /// Declaration modifications and references which we have seen. 14563 UsageInfoMap UsageMap; 14564 14565 /// The region we are currently within. 14566 SequenceTree::Seq Region; 14567 14568 /// Filled in with declarations which were modified as a side-effect 14569 /// (that is, post-increment operations). 14570 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 14571 14572 /// Expressions to check later. We defer checking these to reduce 14573 /// stack usage. 14574 SmallVectorImpl<const Expr *> &WorkList; 14575 14576 /// RAII object wrapping the visitation of a sequenced subexpression of an 14577 /// expression. At the end of this process, the side-effects of the evaluation 14578 /// become sequenced with respect to the value computation of the result, so 14579 /// we downgrade any UK_ModAsSideEffect within the evaluation to 14580 /// UK_ModAsValue. 14581 struct SequencedSubexpression { 14582 SequencedSubexpression(SequenceChecker &Self) 14583 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 14584 Self.ModAsSideEffect = &ModAsSideEffect; 14585 } 14586 14587 ~SequencedSubexpression() { 14588 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 14589 // Add a new usage with usage kind UK_ModAsValue, and then restore 14590 // the previous usage with UK_ModAsSideEffect (thus clearing it if 14591 // the previous one was empty). 14592 UsageInfo &UI = Self.UsageMap[M.first]; 14593 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 14594 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 14595 SideEffectUsage = M.second; 14596 } 14597 Self.ModAsSideEffect = OldModAsSideEffect; 14598 } 14599 14600 SequenceChecker &Self; 14601 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 14602 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 14603 }; 14604 14605 /// RAII object wrapping the visitation of a subexpression which we might 14606 /// choose to evaluate as a constant. If any subexpression is evaluated and 14607 /// found to be non-constant, this allows us to suppress the evaluation of 14608 /// the outer expression. 14609 class EvaluationTracker { 14610 public: 14611 EvaluationTracker(SequenceChecker &Self) 14612 : Self(Self), Prev(Self.EvalTracker) { 14613 Self.EvalTracker = this; 14614 } 14615 14616 ~EvaluationTracker() { 14617 Self.EvalTracker = Prev; 14618 if (Prev) 14619 Prev->EvalOK &= EvalOK; 14620 } 14621 14622 bool evaluate(const Expr *E, bool &Result) { 14623 if (!EvalOK || E->isValueDependent()) 14624 return false; 14625 EvalOK = E->EvaluateAsBooleanCondition( 14626 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 14627 return EvalOK; 14628 } 14629 14630 private: 14631 SequenceChecker &Self; 14632 EvaluationTracker *Prev; 14633 bool EvalOK = true; 14634 } *EvalTracker = nullptr; 14635 14636 /// Find the object which is produced by the specified expression, 14637 /// if any. 14638 Object getObject(const Expr *E, bool Mod) const { 14639 E = E->IgnoreParenCasts(); 14640 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 14641 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 14642 return getObject(UO->getSubExpr(), Mod); 14643 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 14644 if (BO->getOpcode() == BO_Comma) 14645 return getObject(BO->getRHS(), Mod); 14646 if (Mod && BO->isAssignmentOp()) 14647 return getObject(BO->getLHS(), Mod); 14648 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14649 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 14650 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 14651 return ME->getMemberDecl(); 14652 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 14653 // FIXME: If this is a reference, map through to its value. 14654 return DRE->getDecl(); 14655 return nullptr; 14656 } 14657 14658 /// Note that an object \p O was modified or used by an expression 14659 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 14660 /// the object \p O as obtained via the \p UsageMap. 14661 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 14662 // Get the old usage for the given object and usage kind. 14663 Usage &U = UI.Uses[UK]; 14664 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 14665 // If we have a modification as side effect and are in a sequenced 14666 // subexpression, save the old Usage so that we can restore it later 14667 // in SequencedSubexpression::~SequencedSubexpression. 14668 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 14669 ModAsSideEffect->push_back(std::make_pair(O, U)); 14670 // Then record the new usage with the current sequencing region. 14671 U.UsageExpr = UsageExpr; 14672 U.Seq = Region; 14673 } 14674 } 14675 14676 /// Check whether a modification or use of an object \p O in an expression 14677 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 14678 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 14679 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 14680 /// usage and false we are checking for a mod-use unsequenced usage. 14681 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 14682 UsageKind OtherKind, bool IsModMod) { 14683 if (UI.Diagnosed) 14684 return; 14685 14686 const Usage &U = UI.Uses[OtherKind]; 14687 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 14688 return; 14689 14690 const Expr *Mod = U.UsageExpr; 14691 const Expr *ModOrUse = UsageExpr; 14692 if (OtherKind == UK_Use) 14693 std::swap(Mod, ModOrUse); 14694 14695 SemaRef.DiagRuntimeBehavior( 14696 Mod->getExprLoc(), {Mod, ModOrUse}, 14697 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 14698 : diag::warn_unsequenced_mod_use) 14699 << O << SourceRange(ModOrUse->getExprLoc())); 14700 UI.Diagnosed = true; 14701 } 14702 14703 // A note on note{Pre, Post}{Use, Mod}: 14704 // 14705 // (It helps to follow the algorithm with an expression such as 14706 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 14707 // operations before C++17 and both are well-defined in C++17). 14708 // 14709 // When visiting a node which uses/modify an object we first call notePreUse 14710 // or notePreMod before visiting its sub-expression(s). At this point the 14711 // children of the current node have not yet been visited and so the eventual 14712 // uses/modifications resulting from the children of the current node have not 14713 // been recorded yet. 14714 // 14715 // We then visit the children of the current node. After that notePostUse or 14716 // notePostMod is called. These will 1) detect an unsequenced modification 14717 // as side effect (as in "k++ + k") and 2) add a new usage with the 14718 // appropriate usage kind. 14719 // 14720 // We also have to be careful that some operation sequences modification as 14721 // side effect as well (for example: || or ,). To account for this we wrap 14722 // the visitation of such a sub-expression (for example: the LHS of || or ,) 14723 // with SequencedSubexpression. SequencedSubexpression is an RAII object 14724 // which record usages which are modifications as side effect, and then 14725 // downgrade them (or more accurately restore the previous usage which was a 14726 // modification as side effect) when exiting the scope of the sequenced 14727 // subexpression. 14728 14729 void notePreUse(Object O, const Expr *UseExpr) { 14730 UsageInfo &UI = UsageMap[O]; 14731 // Uses conflict with other modifications. 14732 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 14733 } 14734 14735 void notePostUse(Object O, const Expr *UseExpr) { 14736 UsageInfo &UI = UsageMap[O]; 14737 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 14738 /*IsModMod=*/false); 14739 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 14740 } 14741 14742 void notePreMod(Object O, const Expr *ModExpr) { 14743 UsageInfo &UI = UsageMap[O]; 14744 // Modifications conflict with other modifications and with uses. 14745 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 14746 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 14747 } 14748 14749 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 14750 UsageInfo &UI = UsageMap[O]; 14751 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 14752 /*IsModMod=*/true); 14753 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 14754 } 14755 14756 public: 14757 SequenceChecker(Sema &S, const Expr *E, 14758 SmallVectorImpl<const Expr *> &WorkList) 14759 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 14760 Visit(E); 14761 // Silence a -Wunused-private-field since WorkList is now unused. 14762 // TODO: Evaluate if it can be used, and if not remove it. 14763 (void)this->WorkList; 14764 } 14765 14766 void VisitStmt(const Stmt *S) { 14767 // Skip all statements which aren't expressions for now. 14768 } 14769 14770 void VisitExpr(const Expr *E) { 14771 // By default, just recurse to evaluated subexpressions. 14772 Base::VisitStmt(E); 14773 } 14774 14775 void VisitCastExpr(const CastExpr *E) { 14776 Object O = Object(); 14777 if (E->getCastKind() == CK_LValueToRValue) 14778 O = getObject(E->getSubExpr(), false); 14779 14780 if (O) 14781 notePreUse(O, E); 14782 VisitExpr(E); 14783 if (O) 14784 notePostUse(O, E); 14785 } 14786 14787 void VisitSequencedExpressions(const Expr *SequencedBefore, 14788 const Expr *SequencedAfter) { 14789 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14790 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14791 SequenceTree::Seq OldRegion = Region; 14792 14793 { 14794 SequencedSubexpression SeqBefore(*this); 14795 Region = BeforeRegion; 14796 Visit(SequencedBefore); 14797 } 14798 14799 Region = AfterRegion; 14800 Visit(SequencedAfter); 14801 14802 Region = OldRegion; 14803 14804 Tree.merge(BeforeRegion); 14805 Tree.merge(AfterRegion); 14806 } 14807 14808 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14809 // C++17 [expr.sub]p1: 14810 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14811 // expression E1 is sequenced before the expression E2. 14812 if (SemaRef.getLangOpts().CPlusPlus17) 14813 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14814 else { 14815 Visit(ASE->getLHS()); 14816 Visit(ASE->getRHS()); 14817 } 14818 } 14819 14820 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14821 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14822 void VisitBinPtrMem(const BinaryOperator *BO) { 14823 // C++17 [expr.mptr.oper]p4: 14824 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14825 // the expression E1 is sequenced before the expression E2. 14826 if (SemaRef.getLangOpts().CPlusPlus17) 14827 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14828 else { 14829 Visit(BO->getLHS()); 14830 Visit(BO->getRHS()); 14831 } 14832 } 14833 14834 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14835 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14836 void VisitBinShlShr(const BinaryOperator *BO) { 14837 // C++17 [expr.shift]p4: 14838 // The expression E1 is sequenced before the expression E2. 14839 if (SemaRef.getLangOpts().CPlusPlus17) 14840 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14841 else { 14842 Visit(BO->getLHS()); 14843 Visit(BO->getRHS()); 14844 } 14845 } 14846 14847 void VisitBinComma(const BinaryOperator *BO) { 14848 // C++11 [expr.comma]p1: 14849 // Every value computation and side effect associated with the left 14850 // expression is sequenced before every value computation and side 14851 // effect associated with the right expression. 14852 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14853 } 14854 14855 void VisitBinAssign(const BinaryOperator *BO) { 14856 SequenceTree::Seq RHSRegion; 14857 SequenceTree::Seq LHSRegion; 14858 if (SemaRef.getLangOpts().CPlusPlus17) { 14859 RHSRegion = Tree.allocate(Region); 14860 LHSRegion = Tree.allocate(Region); 14861 } else { 14862 RHSRegion = Region; 14863 LHSRegion = Region; 14864 } 14865 SequenceTree::Seq OldRegion = Region; 14866 14867 // C++11 [expr.ass]p1: 14868 // [...] the assignment is sequenced after the value computation 14869 // of the right and left operands, [...] 14870 // 14871 // so check it before inspecting the operands and update the 14872 // map afterwards. 14873 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14874 if (O) 14875 notePreMod(O, BO); 14876 14877 if (SemaRef.getLangOpts().CPlusPlus17) { 14878 // C++17 [expr.ass]p1: 14879 // [...] The right operand is sequenced before the left operand. [...] 14880 { 14881 SequencedSubexpression SeqBefore(*this); 14882 Region = RHSRegion; 14883 Visit(BO->getRHS()); 14884 } 14885 14886 Region = LHSRegion; 14887 Visit(BO->getLHS()); 14888 14889 if (O && isa<CompoundAssignOperator>(BO)) 14890 notePostUse(O, BO); 14891 14892 } else { 14893 // C++11 does not specify any sequencing between the LHS and RHS. 14894 Region = LHSRegion; 14895 Visit(BO->getLHS()); 14896 14897 if (O && isa<CompoundAssignOperator>(BO)) 14898 notePostUse(O, BO); 14899 14900 Region = RHSRegion; 14901 Visit(BO->getRHS()); 14902 } 14903 14904 // C++11 [expr.ass]p1: 14905 // the assignment is sequenced [...] before the value computation of the 14906 // assignment expression. 14907 // C11 6.5.16/3 has no such rule. 14908 Region = OldRegion; 14909 if (O) 14910 notePostMod(O, BO, 14911 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14912 : UK_ModAsSideEffect); 14913 if (SemaRef.getLangOpts().CPlusPlus17) { 14914 Tree.merge(RHSRegion); 14915 Tree.merge(LHSRegion); 14916 } 14917 } 14918 14919 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14920 VisitBinAssign(CAO); 14921 } 14922 14923 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14924 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14925 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14926 Object O = getObject(UO->getSubExpr(), true); 14927 if (!O) 14928 return VisitExpr(UO); 14929 14930 notePreMod(O, UO); 14931 Visit(UO->getSubExpr()); 14932 // C++11 [expr.pre.incr]p1: 14933 // the expression ++x is equivalent to x+=1 14934 notePostMod(O, UO, 14935 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14936 : UK_ModAsSideEffect); 14937 } 14938 14939 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14940 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14941 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14942 Object O = getObject(UO->getSubExpr(), true); 14943 if (!O) 14944 return VisitExpr(UO); 14945 14946 notePreMod(O, UO); 14947 Visit(UO->getSubExpr()); 14948 notePostMod(O, UO, UK_ModAsSideEffect); 14949 } 14950 14951 void VisitBinLOr(const BinaryOperator *BO) { 14952 // C++11 [expr.log.or]p2: 14953 // If the second expression is evaluated, every value computation and 14954 // side effect associated with the first expression is sequenced before 14955 // every value computation and side effect associated with the 14956 // second expression. 14957 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14958 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14959 SequenceTree::Seq OldRegion = Region; 14960 14961 EvaluationTracker Eval(*this); 14962 { 14963 SequencedSubexpression Sequenced(*this); 14964 Region = LHSRegion; 14965 Visit(BO->getLHS()); 14966 } 14967 14968 // C++11 [expr.log.or]p1: 14969 // [...] the second operand is not evaluated if the first operand 14970 // evaluates to true. 14971 bool EvalResult = false; 14972 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14973 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14974 if (ShouldVisitRHS) { 14975 Region = RHSRegion; 14976 Visit(BO->getRHS()); 14977 } 14978 14979 Region = OldRegion; 14980 Tree.merge(LHSRegion); 14981 Tree.merge(RHSRegion); 14982 } 14983 14984 void VisitBinLAnd(const BinaryOperator *BO) { 14985 // C++11 [expr.log.and]p2: 14986 // If the second expression is evaluated, every value computation and 14987 // side effect associated with the first expression is sequenced before 14988 // every value computation and side effect associated with the 14989 // second expression. 14990 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14991 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14992 SequenceTree::Seq OldRegion = Region; 14993 14994 EvaluationTracker Eval(*this); 14995 { 14996 SequencedSubexpression Sequenced(*this); 14997 Region = LHSRegion; 14998 Visit(BO->getLHS()); 14999 } 15000 15001 // C++11 [expr.log.and]p1: 15002 // [...] the second operand is not evaluated if the first operand is false. 15003 bool EvalResult = false; 15004 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 15005 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 15006 if (ShouldVisitRHS) { 15007 Region = RHSRegion; 15008 Visit(BO->getRHS()); 15009 } 15010 15011 Region = OldRegion; 15012 Tree.merge(LHSRegion); 15013 Tree.merge(RHSRegion); 15014 } 15015 15016 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 15017 // C++11 [expr.cond]p1: 15018 // [...] Every value computation and side effect associated with the first 15019 // expression is sequenced before every value computation and side effect 15020 // associated with the second or third expression. 15021 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 15022 15023 // No sequencing is specified between the true and false expression. 15024 // However since exactly one of both is going to be evaluated we can 15025 // consider them to be sequenced. This is needed to avoid warning on 15026 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 15027 // both the true and false expressions because we can't evaluate x. 15028 // This will still allow us to detect an expression like (pre C++17) 15029 // "(x ? y += 1 : y += 2) = y". 15030 // 15031 // We don't wrap the visitation of the true and false expression with 15032 // SequencedSubexpression because we don't want to downgrade modifications 15033 // as side effect in the true and false expressions after the visition 15034 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 15035 // not warn between the two "y++", but we should warn between the "y++" 15036 // and the "y". 15037 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 15038 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 15039 SequenceTree::Seq OldRegion = Region; 15040 15041 EvaluationTracker Eval(*this); 15042 { 15043 SequencedSubexpression Sequenced(*this); 15044 Region = ConditionRegion; 15045 Visit(CO->getCond()); 15046 } 15047 15048 // C++11 [expr.cond]p1: 15049 // [...] The first expression is contextually converted to bool (Clause 4). 15050 // It is evaluated and if it is true, the result of the conditional 15051 // expression is the value of the second expression, otherwise that of the 15052 // third expression. Only one of the second and third expressions is 15053 // evaluated. [...] 15054 bool EvalResult = false; 15055 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 15056 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 15057 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 15058 if (ShouldVisitTrueExpr) { 15059 Region = TrueRegion; 15060 Visit(CO->getTrueExpr()); 15061 } 15062 if (ShouldVisitFalseExpr) { 15063 Region = FalseRegion; 15064 Visit(CO->getFalseExpr()); 15065 } 15066 15067 Region = OldRegion; 15068 Tree.merge(ConditionRegion); 15069 Tree.merge(TrueRegion); 15070 Tree.merge(FalseRegion); 15071 } 15072 15073 void VisitCallExpr(const CallExpr *CE) { 15074 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 15075 15076 if (CE->isUnevaluatedBuiltinCall(Context)) 15077 return; 15078 15079 // C++11 [intro.execution]p15: 15080 // When calling a function [...], every value computation and side effect 15081 // associated with any argument expression, or with the postfix expression 15082 // designating the called function, is sequenced before execution of every 15083 // expression or statement in the body of the function [and thus before 15084 // the value computation of its result]. 15085 SequencedSubexpression Sequenced(*this); 15086 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 15087 // C++17 [expr.call]p5 15088 // The postfix-expression is sequenced before each expression in the 15089 // expression-list and any default argument. [...] 15090 SequenceTree::Seq CalleeRegion; 15091 SequenceTree::Seq OtherRegion; 15092 if (SemaRef.getLangOpts().CPlusPlus17) { 15093 CalleeRegion = Tree.allocate(Region); 15094 OtherRegion = Tree.allocate(Region); 15095 } else { 15096 CalleeRegion = Region; 15097 OtherRegion = Region; 15098 } 15099 SequenceTree::Seq OldRegion = Region; 15100 15101 // Visit the callee expression first. 15102 Region = CalleeRegion; 15103 if (SemaRef.getLangOpts().CPlusPlus17) { 15104 SequencedSubexpression Sequenced(*this); 15105 Visit(CE->getCallee()); 15106 } else { 15107 Visit(CE->getCallee()); 15108 } 15109 15110 // Then visit the argument expressions. 15111 Region = OtherRegion; 15112 for (const Expr *Argument : CE->arguments()) 15113 Visit(Argument); 15114 15115 Region = OldRegion; 15116 if (SemaRef.getLangOpts().CPlusPlus17) { 15117 Tree.merge(CalleeRegion); 15118 Tree.merge(OtherRegion); 15119 } 15120 }); 15121 } 15122 15123 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 15124 // C++17 [over.match.oper]p2: 15125 // [...] the operator notation is first transformed to the equivalent 15126 // function-call notation as summarized in Table 12 (where @ denotes one 15127 // of the operators covered in the specified subclause). However, the 15128 // operands are sequenced in the order prescribed for the built-in 15129 // operator (Clause 8). 15130 // 15131 // From the above only overloaded binary operators and overloaded call 15132 // operators have sequencing rules in C++17 that we need to handle 15133 // separately. 15134 if (!SemaRef.getLangOpts().CPlusPlus17 || 15135 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 15136 return VisitCallExpr(CXXOCE); 15137 15138 enum { 15139 NoSequencing, 15140 LHSBeforeRHS, 15141 RHSBeforeLHS, 15142 LHSBeforeRest 15143 } SequencingKind; 15144 switch (CXXOCE->getOperator()) { 15145 case OO_Equal: 15146 case OO_PlusEqual: 15147 case OO_MinusEqual: 15148 case OO_StarEqual: 15149 case OO_SlashEqual: 15150 case OO_PercentEqual: 15151 case OO_CaretEqual: 15152 case OO_AmpEqual: 15153 case OO_PipeEqual: 15154 case OO_LessLessEqual: 15155 case OO_GreaterGreaterEqual: 15156 SequencingKind = RHSBeforeLHS; 15157 break; 15158 15159 case OO_LessLess: 15160 case OO_GreaterGreater: 15161 case OO_AmpAmp: 15162 case OO_PipePipe: 15163 case OO_Comma: 15164 case OO_ArrowStar: 15165 case OO_Subscript: 15166 SequencingKind = LHSBeforeRHS; 15167 break; 15168 15169 case OO_Call: 15170 SequencingKind = LHSBeforeRest; 15171 break; 15172 15173 default: 15174 SequencingKind = NoSequencing; 15175 break; 15176 } 15177 15178 if (SequencingKind == NoSequencing) 15179 return VisitCallExpr(CXXOCE); 15180 15181 // This is a call, so all subexpressions are sequenced before the result. 15182 SequencedSubexpression Sequenced(*this); 15183 15184 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 15185 assert(SemaRef.getLangOpts().CPlusPlus17 && 15186 "Should only get there with C++17 and above!"); 15187 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 15188 "Should only get there with an overloaded binary operator" 15189 " or an overloaded call operator!"); 15190 15191 if (SequencingKind == LHSBeforeRest) { 15192 assert(CXXOCE->getOperator() == OO_Call && 15193 "We should only have an overloaded call operator here!"); 15194 15195 // This is very similar to VisitCallExpr, except that we only have the 15196 // C++17 case. The postfix-expression is the first argument of the 15197 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 15198 // are in the following arguments. 15199 // 15200 // Note that we intentionally do not visit the callee expression since 15201 // it is just a decayed reference to a function. 15202 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 15203 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 15204 SequenceTree::Seq OldRegion = Region; 15205 15206 assert(CXXOCE->getNumArgs() >= 1 && 15207 "An overloaded call operator must have at least one argument" 15208 " for the postfix-expression!"); 15209 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 15210 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 15211 CXXOCE->getNumArgs() - 1); 15212 15213 // Visit the postfix-expression first. 15214 { 15215 Region = PostfixExprRegion; 15216 SequencedSubexpression Sequenced(*this); 15217 Visit(PostfixExpr); 15218 } 15219 15220 // Then visit the argument expressions. 15221 Region = ArgsRegion; 15222 for (const Expr *Arg : Args) 15223 Visit(Arg); 15224 15225 Region = OldRegion; 15226 Tree.merge(PostfixExprRegion); 15227 Tree.merge(ArgsRegion); 15228 } else { 15229 assert(CXXOCE->getNumArgs() == 2 && 15230 "Should only have two arguments here!"); 15231 assert((SequencingKind == LHSBeforeRHS || 15232 SequencingKind == RHSBeforeLHS) && 15233 "Unexpected sequencing kind!"); 15234 15235 // We do not visit the callee expression since it is just a decayed 15236 // reference to a function. 15237 const Expr *E1 = CXXOCE->getArg(0); 15238 const Expr *E2 = CXXOCE->getArg(1); 15239 if (SequencingKind == RHSBeforeLHS) 15240 std::swap(E1, E2); 15241 15242 return VisitSequencedExpressions(E1, E2); 15243 } 15244 }); 15245 } 15246 15247 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 15248 // This is a call, so all subexpressions are sequenced before the result. 15249 SequencedSubexpression Sequenced(*this); 15250 15251 if (!CCE->isListInitialization()) 15252 return VisitExpr(CCE); 15253 15254 // In C++11, list initializations are sequenced. 15255 SmallVector<SequenceTree::Seq, 32> Elts; 15256 SequenceTree::Seq Parent = Region; 15257 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 15258 E = CCE->arg_end(); 15259 I != E; ++I) { 15260 Region = Tree.allocate(Parent); 15261 Elts.push_back(Region); 15262 Visit(*I); 15263 } 15264 15265 // Forget that the initializers are sequenced. 15266 Region = Parent; 15267 for (unsigned I = 0; I < Elts.size(); ++I) 15268 Tree.merge(Elts[I]); 15269 } 15270 15271 void VisitInitListExpr(const InitListExpr *ILE) { 15272 if (!SemaRef.getLangOpts().CPlusPlus11) 15273 return VisitExpr(ILE); 15274 15275 // In C++11, list initializations are sequenced. 15276 SmallVector<SequenceTree::Seq, 32> Elts; 15277 SequenceTree::Seq Parent = Region; 15278 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 15279 const Expr *E = ILE->getInit(I); 15280 if (!E) 15281 continue; 15282 Region = Tree.allocate(Parent); 15283 Elts.push_back(Region); 15284 Visit(E); 15285 } 15286 15287 // Forget that the initializers are sequenced. 15288 Region = Parent; 15289 for (unsigned I = 0; I < Elts.size(); ++I) 15290 Tree.merge(Elts[I]); 15291 } 15292 }; 15293 15294 } // namespace 15295 15296 void Sema::CheckUnsequencedOperations(const Expr *E) { 15297 SmallVector<const Expr *, 8> WorkList; 15298 WorkList.push_back(E); 15299 while (!WorkList.empty()) { 15300 const Expr *Item = WorkList.pop_back_val(); 15301 SequenceChecker(*this, Item, WorkList); 15302 } 15303 } 15304 15305 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 15306 bool IsConstexpr) { 15307 llvm::SaveAndRestore<bool> ConstantContext( 15308 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 15309 CheckImplicitConversions(E, CheckLoc); 15310 if (!E->isInstantiationDependent()) 15311 CheckUnsequencedOperations(E); 15312 if (!IsConstexpr && !E->isValueDependent()) 15313 CheckForIntOverflow(E); 15314 DiagnoseMisalignedMembers(); 15315 } 15316 15317 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 15318 FieldDecl *BitField, 15319 Expr *Init) { 15320 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 15321 } 15322 15323 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 15324 SourceLocation Loc) { 15325 if (!PType->isVariablyModifiedType()) 15326 return; 15327 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 15328 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 15329 return; 15330 } 15331 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 15332 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 15333 return; 15334 } 15335 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 15336 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 15337 return; 15338 } 15339 15340 const ArrayType *AT = S.Context.getAsArrayType(PType); 15341 if (!AT) 15342 return; 15343 15344 if (AT->getSizeModifier() != ArrayType::Star) { 15345 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 15346 return; 15347 } 15348 15349 S.Diag(Loc, diag::err_array_star_in_function_definition); 15350 } 15351 15352 /// CheckParmsForFunctionDef - Check that the parameters of the given 15353 /// function are appropriate for the definition of a function. This 15354 /// takes care of any checks that cannot be performed on the 15355 /// declaration itself, e.g., that the types of each of the function 15356 /// parameters are complete. 15357 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 15358 bool CheckParameterNames) { 15359 bool HasInvalidParm = false; 15360 for (ParmVarDecl *Param : Parameters) { 15361 // C99 6.7.5.3p4: the parameters in a parameter type list in a 15362 // function declarator that is part of a function definition of 15363 // that function shall not have incomplete type. 15364 // 15365 // This is also C++ [dcl.fct]p6. 15366 if (!Param->isInvalidDecl() && 15367 RequireCompleteType(Param->getLocation(), Param->getType(), 15368 diag::err_typecheck_decl_incomplete_type)) { 15369 Param->setInvalidDecl(); 15370 HasInvalidParm = true; 15371 } 15372 15373 // C99 6.9.1p5: If the declarator includes a parameter type list, the 15374 // declaration of each parameter shall include an identifier. 15375 if (CheckParameterNames && Param->getIdentifier() == nullptr && 15376 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 15377 // Diagnose this as an extension in C17 and earlier. 15378 if (!getLangOpts().C2x) 15379 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15380 } 15381 15382 // C99 6.7.5.3p12: 15383 // If the function declarator is not part of a definition of that 15384 // function, parameters may have incomplete type and may use the [*] 15385 // notation in their sequences of declarator specifiers to specify 15386 // variable length array types. 15387 QualType PType = Param->getOriginalType(); 15388 // FIXME: This diagnostic should point the '[*]' if source-location 15389 // information is added for it. 15390 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 15391 15392 // If the parameter is a c++ class type and it has to be destructed in the 15393 // callee function, declare the destructor so that it can be called by the 15394 // callee function. Do not perform any direct access check on the dtor here. 15395 if (!Param->isInvalidDecl()) { 15396 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 15397 if (!ClassDecl->isInvalidDecl() && 15398 !ClassDecl->hasIrrelevantDestructor() && 15399 !ClassDecl->isDependentContext() && 15400 ClassDecl->isParamDestroyedInCallee()) { 15401 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15402 MarkFunctionReferenced(Param->getLocation(), Destructor); 15403 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 15404 } 15405 } 15406 } 15407 15408 // Parameters with the pass_object_size attribute only need to be marked 15409 // constant at function definitions. Because we lack information about 15410 // whether we're on a declaration or definition when we're instantiating the 15411 // attribute, we need to check for constness here. 15412 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 15413 if (!Param->getType().isConstQualified()) 15414 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 15415 << Attr->getSpelling() << 1; 15416 15417 // Check for parameter names shadowing fields from the class. 15418 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 15419 // The owning context for the parameter should be the function, but we 15420 // want to see if this function's declaration context is a record. 15421 DeclContext *DC = Param->getDeclContext(); 15422 if (DC && DC->isFunctionOrMethod()) { 15423 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 15424 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 15425 RD, /*DeclIsField*/ false); 15426 } 15427 } 15428 } 15429 15430 return HasInvalidParm; 15431 } 15432 15433 Optional<std::pair<CharUnits, CharUnits>> 15434 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 15435 15436 /// Compute the alignment and offset of the base class object given the 15437 /// derived-to-base cast expression and the alignment and offset of the derived 15438 /// class object. 15439 static std::pair<CharUnits, CharUnits> 15440 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 15441 CharUnits BaseAlignment, CharUnits Offset, 15442 ASTContext &Ctx) { 15443 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 15444 ++PathI) { 15445 const CXXBaseSpecifier *Base = *PathI; 15446 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 15447 if (Base->isVirtual()) { 15448 // The complete object may have a lower alignment than the non-virtual 15449 // alignment of the base, in which case the base may be misaligned. Choose 15450 // the smaller of the non-virtual alignment and BaseAlignment, which is a 15451 // conservative lower bound of the complete object alignment. 15452 CharUnits NonVirtualAlignment = 15453 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 15454 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 15455 Offset = CharUnits::Zero(); 15456 } else { 15457 const ASTRecordLayout &RL = 15458 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 15459 Offset += RL.getBaseClassOffset(BaseDecl); 15460 } 15461 DerivedType = Base->getType(); 15462 } 15463 15464 return std::make_pair(BaseAlignment, Offset); 15465 } 15466 15467 /// Compute the alignment and offset of a binary additive operator. 15468 static Optional<std::pair<CharUnits, CharUnits>> 15469 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 15470 bool IsSub, ASTContext &Ctx) { 15471 QualType PointeeType = PtrE->getType()->getPointeeType(); 15472 15473 if (!PointeeType->isConstantSizeType()) 15474 return llvm::None; 15475 15476 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 15477 15478 if (!P) 15479 return llvm::None; 15480 15481 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 15482 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 15483 CharUnits Offset = EltSize * IdxRes->getExtValue(); 15484 if (IsSub) 15485 Offset = -Offset; 15486 return std::make_pair(P->first, P->second + Offset); 15487 } 15488 15489 // If the integer expression isn't a constant expression, compute the lower 15490 // bound of the alignment using the alignment and offset of the pointer 15491 // expression and the element size. 15492 return std::make_pair( 15493 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 15494 CharUnits::Zero()); 15495 } 15496 15497 /// This helper function takes an lvalue expression and returns the alignment of 15498 /// a VarDecl and a constant offset from the VarDecl. 15499 Optional<std::pair<CharUnits, CharUnits>> 15500 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 15501 E = E->IgnoreParens(); 15502 switch (E->getStmtClass()) { 15503 default: 15504 break; 15505 case Stmt::CStyleCastExprClass: 15506 case Stmt::CXXStaticCastExprClass: 15507 case Stmt::ImplicitCastExprClass: { 15508 auto *CE = cast<CastExpr>(E); 15509 const Expr *From = CE->getSubExpr(); 15510 switch (CE->getCastKind()) { 15511 default: 15512 break; 15513 case CK_NoOp: 15514 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15515 case CK_UncheckedDerivedToBase: 15516 case CK_DerivedToBase: { 15517 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15518 if (!P) 15519 break; 15520 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 15521 P->second, Ctx); 15522 } 15523 } 15524 break; 15525 } 15526 case Stmt::ArraySubscriptExprClass: { 15527 auto *ASE = cast<ArraySubscriptExpr>(E); 15528 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 15529 false, Ctx); 15530 } 15531 case Stmt::DeclRefExprClass: { 15532 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 15533 // FIXME: If VD is captured by copy or is an escaping __block variable, 15534 // use the alignment of VD's type. 15535 if (!VD->getType()->isReferenceType()) 15536 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 15537 if (VD->hasInit()) 15538 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 15539 } 15540 break; 15541 } 15542 case Stmt::MemberExprClass: { 15543 auto *ME = cast<MemberExpr>(E); 15544 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 15545 if (!FD || FD->getType()->isReferenceType() || 15546 FD->getParent()->isInvalidDecl()) 15547 break; 15548 Optional<std::pair<CharUnits, CharUnits>> P; 15549 if (ME->isArrow()) 15550 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 15551 else 15552 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 15553 if (!P) 15554 break; 15555 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 15556 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 15557 return std::make_pair(P->first, 15558 P->second + CharUnits::fromQuantity(Offset)); 15559 } 15560 case Stmt::UnaryOperatorClass: { 15561 auto *UO = cast<UnaryOperator>(E); 15562 switch (UO->getOpcode()) { 15563 default: 15564 break; 15565 case UO_Deref: 15566 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 15567 } 15568 break; 15569 } 15570 case Stmt::BinaryOperatorClass: { 15571 auto *BO = cast<BinaryOperator>(E); 15572 auto Opcode = BO->getOpcode(); 15573 switch (Opcode) { 15574 default: 15575 break; 15576 case BO_Comma: 15577 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 15578 } 15579 break; 15580 } 15581 } 15582 return llvm::None; 15583 } 15584 15585 /// This helper function takes a pointer expression and returns the alignment of 15586 /// a VarDecl and a constant offset from the VarDecl. 15587 Optional<std::pair<CharUnits, CharUnits>> 15588 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 15589 E = E->IgnoreParens(); 15590 switch (E->getStmtClass()) { 15591 default: 15592 break; 15593 case Stmt::CStyleCastExprClass: 15594 case Stmt::CXXStaticCastExprClass: 15595 case Stmt::ImplicitCastExprClass: { 15596 auto *CE = cast<CastExpr>(E); 15597 const Expr *From = CE->getSubExpr(); 15598 switch (CE->getCastKind()) { 15599 default: 15600 break; 15601 case CK_NoOp: 15602 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 15603 case CK_ArrayToPointerDecay: 15604 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15605 case CK_UncheckedDerivedToBase: 15606 case CK_DerivedToBase: { 15607 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 15608 if (!P) 15609 break; 15610 return getDerivedToBaseAlignmentAndOffset( 15611 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 15612 } 15613 } 15614 break; 15615 } 15616 case Stmt::CXXThisExprClass: { 15617 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 15618 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 15619 return std::make_pair(Alignment, CharUnits::Zero()); 15620 } 15621 case Stmt::UnaryOperatorClass: { 15622 auto *UO = cast<UnaryOperator>(E); 15623 if (UO->getOpcode() == UO_AddrOf) 15624 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 15625 break; 15626 } 15627 case Stmt::BinaryOperatorClass: { 15628 auto *BO = cast<BinaryOperator>(E); 15629 auto Opcode = BO->getOpcode(); 15630 switch (Opcode) { 15631 default: 15632 break; 15633 case BO_Add: 15634 case BO_Sub: { 15635 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 15636 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 15637 std::swap(LHS, RHS); 15638 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 15639 Ctx); 15640 } 15641 case BO_Comma: 15642 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 15643 } 15644 break; 15645 } 15646 } 15647 return llvm::None; 15648 } 15649 15650 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 15651 // See if we can compute the alignment of a VarDecl and an offset from it. 15652 Optional<std::pair<CharUnits, CharUnits>> P = 15653 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 15654 15655 if (P) 15656 return P->first.alignmentAtOffset(P->second); 15657 15658 // If that failed, return the type's alignment. 15659 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 15660 } 15661 15662 /// CheckCastAlign - Implements -Wcast-align, which warns when a 15663 /// pointer cast increases the alignment requirements. 15664 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 15665 // This is actually a lot of work to potentially be doing on every 15666 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 15667 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 15668 return; 15669 15670 // Ignore dependent types. 15671 if (T->isDependentType() || Op->getType()->isDependentType()) 15672 return; 15673 15674 // Require that the destination be a pointer type. 15675 const PointerType *DestPtr = T->getAs<PointerType>(); 15676 if (!DestPtr) return; 15677 15678 // If the destination has alignment 1, we're done. 15679 QualType DestPointee = DestPtr->getPointeeType(); 15680 if (DestPointee->isIncompleteType()) return; 15681 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 15682 if (DestAlign.isOne()) return; 15683 15684 // Require that the source be a pointer type. 15685 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 15686 if (!SrcPtr) return; 15687 QualType SrcPointee = SrcPtr->getPointeeType(); 15688 15689 // Explicitly allow casts from cv void*. We already implicitly 15690 // allowed casts to cv void*, since they have alignment 1. 15691 // Also allow casts involving incomplete types, which implicitly 15692 // includes 'void'. 15693 if (SrcPointee->isIncompleteType()) return; 15694 15695 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 15696 15697 if (SrcAlign >= DestAlign) return; 15698 15699 Diag(TRange.getBegin(), diag::warn_cast_align) 15700 << Op->getType() << T 15701 << static_cast<unsigned>(SrcAlign.getQuantity()) 15702 << static_cast<unsigned>(DestAlign.getQuantity()) 15703 << TRange << Op->getSourceRange(); 15704 } 15705 15706 /// Check whether this array fits the idiom of a size-one tail padded 15707 /// array member of a struct. 15708 /// 15709 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 15710 /// commonly used to emulate flexible arrays in C89 code. 15711 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 15712 const NamedDecl *ND) { 15713 if (Size != 1 || !ND) return false; 15714 15715 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 15716 if (!FD) return false; 15717 15718 // Don't consider sizes resulting from macro expansions or template argument 15719 // substitution to form C89 tail-padded arrays. 15720 15721 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 15722 while (TInfo) { 15723 TypeLoc TL = TInfo->getTypeLoc(); 15724 // Look through typedefs. 15725 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 15726 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 15727 TInfo = TDL->getTypeSourceInfo(); 15728 continue; 15729 } 15730 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 15731 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 15732 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 15733 return false; 15734 } 15735 break; 15736 } 15737 15738 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 15739 if (!RD) return false; 15740 if (RD->isUnion()) return false; 15741 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15742 if (!CRD->isStandardLayout()) return false; 15743 } 15744 15745 // See if this is the last field decl in the record. 15746 const Decl *D = FD; 15747 while ((D = D->getNextDeclInContext())) 15748 if (isa<FieldDecl>(D)) 15749 return false; 15750 return true; 15751 } 15752 15753 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 15754 const ArraySubscriptExpr *ASE, 15755 bool AllowOnePastEnd, bool IndexNegated) { 15756 // Already diagnosed by the constant evaluator. 15757 if (isConstantEvaluated()) 15758 return; 15759 15760 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 15761 if (IndexExpr->isValueDependent()) 15762 return; 15763 15764 const Type *EffectiveType = 15765 BaseExpr->getType()->getPointeeOrArrayElementType(); 15766 BaseExpr = BaseExpr->IgnoreParenCasts(); 15767 const ConstantArrayType *ArrayTy = 15768 Context.getAsConstantArrayType(BaseExpr->getType()); 15769 15770 const Type *BaseType = 15771 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 15772 bool IsUnboundedArray = (BaseType == nullptr); 15773 if (EffectiveType->isDependentType() || 15774 (!IsUnboundedArray && BaseType->isDependentType())) 15775 return; 15776 15777 Expr::EvalResult Result; 15778 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15779 return; 15780 15781 llvm::APSInt index = Result.Val.getInt(); 15782 if (IndexNegated) { 15783 index.setIsUnsigned(false); 15784 index = -index; 15785 } 15786 15787 const NamedDecl *ND = nullptr; 15788 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15789 ND = DRE->getDecl(); 15790 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15791 ND = ME->getMemberDecl(); 15792 15793 if (IsUnboundedArray) { 15794 if (EffectiveType->isFunctionType()) 15795 return; 15796 if (index.isUnsigned() || !index.isNegative()) { 15797 const auto &ASTC = getASTContext(); 15798 unsigned AddrBits = 15799 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15800 EffectiveType->getCanonicalTypeInternal())); 15801 if (index.getBitWidth() < AddrBits) 15802 index = index.zext(AddrBits); 15803 Optional<CharUnits> ElemCharUnits = 15804 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15805 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15806 // pointer) bounds-checking isn't meaningful. 15807 if (!ElemCharUnits) 15808 return; 15809 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15810 // If index has more active bits than address space, we already know 15811 // we have a bounds violation to warn about. Otherwise, compute 15812 // address of (index + 1)th element, and warn about bounds violation 15813 // only if that address exceeds address space. 15814 if (index.getActiveBits() <= AddrBits) { 15815 bool Overflow; 15816 llvm::APInt Product(index); 15817 Product += 1; 15818 Product = Product.umul_ov(ElemBytes, Overflow); 15819 if (!Overflow && Product.getActiveBits() <= AddrBits) 15820 return; 15821 } 15822 15823 // Need to compute max possible elements in address space, since that 15824 // is included in diag message. 15825 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15826 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15827 MaxElems += 1; 15828 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15829 MaxElems = MaxElems.udiv(ElemBytes); 15830 15831 unsigned DiagID = 15832 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15833 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15834 15835 // Diag message shows element size in bits and in "bytes" (platform- 15836 // dependent CharUnits) 15837 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15838 PDiag(DiagID) 15839 << toString(index, 10, true) << AddrBits 15840 << (unsigned)ASTC.toBits(*ElemCharUnits) 15841 << toString(ElemBytes, 10, false) 15842 << toString(MaxElems, 10, false) 15843 << (unsigned)MaxElems.getLimitedValue(~0U) 15844 << IndexExpr->getSourceRange()); 15845 15846 if (!ND) { 15847 // Try harder to find a NamedDecl to point at in the note. 15848 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15849 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15850 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15851 ND = DRE->getDecl(); 15852 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15853 ND = ME->getMemberDecl(); 15854 } 15855 15856 if (ND) 15857 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15858 PDiag(diag::note_array_declared_here) << ND); 15859 } 15860 return; 15861 } 15862 15863 if (index.isUnsigned() || !index.isNegative()) { 15864 // It is possible that the type of the base expression after 15865 // IgnoreParenCasts is incomplete, even though the type of the base 15866 // expression before IgnoreParenCasts is complete (see PR39746 for an 15867 // example). In this case we have no information about whether the array 15868 // access exceeds the array bounds. However we can still diagnose an array 15869 // access which precedes the array bounds. 15870 if (BaseType->isIncompleteType()) 15871 return; 15872 15873 llvm::APInt size = ArrayTy->getSize(); 15874 if (!size.isStrictlyPositive()) 15875 return; 15876 15877 if (BaseType != EffectiveType) { 15878 // Make sure we're comparing apples to apples when comparing index to size 15879 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15880 uint64_t array_typesize = Context.getTypeSize(BaseType); 15881 // Handle ptrarith_typesize being zero, such as when casting to void* 15882 if (!ptrarith_typesize) ptrarith_typesize = 1; 15883 if (ptrarith_typesize != array_typesize) { 15884 // There's a cast to a different size type involved 15885 uint64_t ratio = array_typesize / ptrarith_typesize; 15886 // TODO: Be smarter about handling cases where array_typesize is not a 15887 // multiple of ptrarith_typesize 15888 if (ptrarith_typesize * ratio == array_typesize) 15889 size *= llvm::APInt(size.getBitWidth(), ratio); 15890 } 15891 } 15892 15893 if (size.getBitWidth() > index.getBitWidth()) 15894 index = index.zext(size.getBitWidth()); 15895 else if (size.getBitWidth() < index.getBitWidth()) 15896 size = size.zext(index.getBitWidth()); 15897 15898 // For array subscripting the index must be less than size, but for pointer 15899 // arithmetic also allow the index (offset) to be equal to size since 15900 // computing the next address after the end of the array is legal and 15901 // commonly done e.g. in C++ iterators and range-based for loops. 15902 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15903 return; 15904 15905 // Also don't warn for arrays of size 1 which are members of some 15906 // structure. These are often used to approximate flexible arrays in C89 15907 // code. 15908 if (IsTailPaddedMemberArray(*this, size, ND)) 15909 return; 15910 15911 // Suppress the warning if the subscript expression (as identified by the 15912 // ']' location) and the index expression are both from macro expansions 15913 // within a system header. 15914 if (ASE) { 15915 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15916 ASE->getRBracketLoc()); 15917 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15918 SourceLocation IndexLoc = 15919 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15920 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15921 return; 15922 } 15923 } 15924 15925 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15926 : diag::warn_ptr_arith_exceeds_bounds; 15927 15928 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15929 PDiag(DiagID) << toString(index, 10, true) 15930 << toString(size, 10, true) 15931 << (unsigned)size.getLimitedValue(~0U) 15932 << IndexExpr->getSourceRange()); 15933 } else { 15934 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15935 if (!ASE) { 15936 DiagID = diag::warn_ptr_arith_precedes_bounds; 15937 if (index.isNegative()) index = -index; 15938 } 15939 15940 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15941 PDiag(DiagID) << toString(index, 10, true) 15942 << IndexExpr->getSourceRange()); 15943 } 15944 15945 if (!ND) { 15946 // Try harder to find a NamedDecl to point at in the note. 15947 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15948 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15949 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15950 ND = DRE->getDecl(); 15951 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15952 ND = ME->getMemberDecl(); 15953 } 15954 15955 if (ND) 15956 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15957 PDiag(diag::note_array_declared_here) << ND); 15958 } 15959 15960 void Sema::CheckArrayAccess(const Expr *expr) { 15961 int AllowOnePastEnd = 0; 15962 while (expr) { 15963 expr = expr->IgnoreParenImpCasts(); 15964 switch (expr->getStmtClass()) { 15965 case Stmt::ArraySubscriptExprClass: { 15966 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15967 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15968 AllowOnePastEnd > 0); 15969 expr = ASE->getBase(); 15970 break; 15971 } 15972 case Stmt::MemberExprClass: { 15973 expr = cast<MemberExpr>(expr)->getBase(); 15974 break; 15975 } 15976 case Stmt::OMPArraySectionExprClass: { 15977 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15978 if (ASE->getLowerBound()) 15979 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15980 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15981 return; 15982 } 15983 case Stmt::UnaryOperatorClass: { 15984 // Only unwrap the * and & unary operators 15985 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15986 expr = UO->getSubExpr(); 15987 switch (UO->getOpcode()) { 15988 case UO_AddrOf: 15989 AllowOnePastEnd++; 15990 break; 15991 case UO_Deref: 15992 AllowOnePastEnd--; 15993 break; 15994 default: 15995 return; 15996 } 15997 break; 15998 } 15999 case Stmt::ConditionalOperatorClass: { 16000 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 16001 if (const Expr *lhs = cond->getLHS()) 16002 CheckArrayAccess(lhs); 16003 if (const Expr *rhs = cond->getRHS()) 16004 CheckArrayAccess(rhs); 16005 return; 16006 } 16007 case Stmt::CXXOperatorCallExprClass: { 16008 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 16009 for (const auto *Arg : OCE->arguments()) 16010 CheckArrayAccess(Arg); 16011 return; 16012 } 16013 default: 16014 return; 16015 } 16016 } 16017 } 16018 16019 //===--- CHECK: Objective-C retain cycles ----------------------------------// 16020 16021 namespace { 16022 16023 struct RetainCycleOwner { 16024 VarDecl *Variable = nullptr; 16025 SourceRange Range; 16026 SourceLocation Loc; 16027 bool Indirect = false; 16028 16029 RetainCycleOwner() = default; 16030 16031 void setLocsFrom(Expr *e) { 16032 Loc = e->getExprLoc(); 16033 Range = e->getSourceRange(); 16034 } 16035 }; 16036 16037 } // namespace 16038 16039 /// Consider whether capturing the given variable can possibly lead to 16040 /// a retain cycle. 16041 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 16042 // In ARC, it's captured strongly iff the variable has __strong 16043 // lifetime. In MRR, it's captured strongly if the variable is 16044 // __block and has an appropriate type. 16045 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 16046 return false; 16047 16048 owner.Variable = var; 16049 if (ref) 16050 owner.setLocsFrom(ref); 16051 return true; 16052 } 16053 16054 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 16055 while (true) { 16056 e = e->IgnoreParens(); 16057 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 16058 switch (cast->getCastKind()) { 16059 case CK_BitCast: 16060 case CK_LValueBitCast: 16061 case CK_LValueToRValue: 16062 case CK_ARCReclaimReturnedObject: 16063 e = cast->getSubExpr(); 16064 continue; 16065 16066 default: 16067 return false; 16068 } 16069 } 16070 16071 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 16072 ObjCIvarDecl *ivar = ref->getDecl(); 16073 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 16074 return false; 16075 16076 // Try to find a retain cycle in the base. 16077 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 16078 return false; 16079 16080 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 16081 owner.Indirect = true; 16082 return true; 16083 } 16084 16085 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 16086 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 16087 if (!var) return false; 16088 return considerVariable(var, ref, owner); 16089 } 16090 16091 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 16092 if (member->isArrow()) return false; 16093 16094 // Don't count this as an indirect ownership. 16095 e = member->getBase(); 16096 continue; 16097 } 16098 16099 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 16100 // Only pay attention to pseudo-objects on property references. 16101 ObjCPropertyRefExpr *pre 16102 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 16103 ->IgnoreParens()); 16104 if (!pre) return false; 16105 if (pre->isImplicitProperty()) return false; 16106 ObjCPropertyDecl *property = pre->getExplicitProperty(); 16107 if (!property->isRetaining() && 16108 !(property->getPropertyIvarDecl() && 16109 property->getPropertyIvarDecl()->getType() 16110 .getObjCLifetime() == Qualifiers::OCL_Strong)) 16111 return false; 16112 16113 owner.Indirect = true; 16114 if (pre->isSuperReceiver()) { 16115 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 16116 if (!owner.Variable) 16117 return false; 16118 owner.Loc = pre->getLocation(); 16119 owner.Range = pre->getSourceRange(); 16120 return true; 16121 } 16122 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 16123 ->getSourceExpr()); 16124 continue; 16125 } 16126 16127 // Array ivars? 16128 16129 return false; 16130 } 16131 } 16132 16133 namespace { 16134 16135 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 16136 ASTContext &Context; 16137 VarDecl *Variable; 16138 Expr *Capturer = nullptr; 16139 bool VarWillBeReased = false; 16140 16141 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 16142 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 16143 Context(Context), Variable(variable) {} 16144 16145 void VisitDeclRefExpr(DeclRefExpr *ref) { 16146 if (ref->getDecl() == Variable && !Capturer) 16147 Capturer = ref; 16148 } 16149 16150 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 16151 if (Capturer) return; 16152 Visit(ref->getBase()); 16153 if (Capturer && ref->isFreeIvar()) 16154 Capturer = ref; 16155 } 16156 16157 void VisitBlockExpr(BlockExpr *block) { 16158 // Look inside nested blocks 16159 if (block->getBlockDecl()->capturesVariable(Variable)) 16160 Visit(block->getBlockDecl()->getBody()); 16161 } 16162 16163 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 16164 if (Capturer) return; 16165 if (OVE->getSourceExpr()) 16166 Visit(OVE->getSourceExpr()); 16167 } 16168 16169 void VisitBinaryOperator(BinaryOperator *BinOp) { 16170 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 16171 return; 16172 Expr *LHS = BinOp->getLHS(); 16173 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 16174 if (DRE->getDecl() != Variable) 16175 return; 16176 if (Expr *RHS = BinOp->getRHS()) { 16177 RHS = RHS->IgnoreParenCasts(); 16178 Optional<llvm::APSInt> Value; 16179 VarWillBeReased = 16180 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 16181 *Value == 0); 16182 } 16183 } 16184 } 16185 }; 16186 16187 } // namespace 16188 16189 /// Check whether the given argument is a block which captures a 16190 /// variable. 16191 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 16192 assert(owner.Variable && owner.Loc.isValid()); 16193 16194 e = e->IgnoreParenCasts(); 16195 16196 // Look through [^{...} copy] and Block_copy(^{...}). 16197 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 16198 Selector Cmd = ME->getSelector(); 16199 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 16200 e = ME->getInstanceReceiver(); 16201 if (!e) 16202 return nullptr; 16203 e = e->IgnoreParenCasts(); 16204 } 16205 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 16206 if (CE->getNumArgs() == 1) { 16207 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 16208 if (Fn) { 16209 const IdentifierInfo *FnI = Fn->getIdentifier(); 16210 if (FnI && FnI->isStr("_Block_copy")) { 16211 e = CE->getArg(0)->IgnoreParenCasts(); 16212 } 16213 } 16214 } 16215 } 16216 16217 BlockExpr *block = dyn_cast<BlockExpr>(e); 16218 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 16219 return nullptr; 16220 16221 FindCaptureVisitor visitor(S.Context, owner.Variable); 16222 visitor.Visit(block->getBlockDecl()->getBody()); 16223 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 16224 } 16225 16226 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 16227 RetainCycleOwner &owner) { 16228 assert(capturer); 16229 assert(owner.Variable && owner.Loc.isValid()); 16230 16231 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 16232 << owner.Variable << capturer->getSourceRange(); 16233 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 16234 << owner.Indirect << owner.Range; 16235 } 16236 16237 /// Check for a keyword selector that starts with the word 'add' or 16238 /// 'set'. 16239 static bool isSetterLikeSelector(Selector sel) { 16240 if (sel.isUnarySelector()) return false; 16241 16242 StringRef str = sel.getNameForSlot(0); 16243 while (!str.empty() && str.front() == '_') str = str.substr(1); 16244 if (str.startswith("set")) 16245 str = str.substr(3); 16246 else if (str.startswith("add")) { 16247 // Specially allow 'addOperationWithBlock:'. 16248 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 16249 return false; 16250 str = str.substr(3); 16251 } 16252 else 16253 return false; 16254 16255 if (str.empty()) return true; 16256 return !isLowercase(str.front()); 16257 } 16258 16259 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 16260 ObjCMessageExpr *Message) { 16261 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 16262 Message->getReceiverInterface(), 16263 NSAPI::ClassId_NSMutableArray); 16264 if (!IsMutableArray) { 16265 return None; 16266 } 16267 16268 Selector Sel = Message->getSelector(); 16269 16270 Optional<NSAPI::NSArrayMethodKind> MKOpt = 16271 S.NSAPIObj->getNSArrayMethodKind(Sel); 16272 if (!MKOpt) { 16273 return None; 16274 } 16275 16276 NSAPI::NSArrayMethodKind MK = *MKOpt; 16277 16278 switch (MK) { 16279 case NSAPI::NSMutableArr_addObject: 16280 case NSAPI::NSMutableArr_insertObjectAtIndex: 16281 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 16282 return 0; 16283 case NSAPI::NSMutableArr_replaceObjectAtIndex: 16284 return 1; 16285 16286 default: 16287 return None; 16288 } 16289 16290 return None; 16291 } 16292 16293 static 16294 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 16295 ObjCMessageExpr *Message) { 16296 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 16297 Message->getReceiverInterface(), 16298 NSAPI::ClassId_NSMutableDictionary); 16299 if (!IsMutableDictionary) { 16300 return None; 16301 } 16302 16303 Selector Sel = Message->getSelector(); 16304 16305 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 16306 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 16307 if (!MKOpt) { 16308 return None; 16309 } 16310 16311 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 16312 16313 switch (MK) { 16314 case NSAPI::NSMutableDict_setObjectForKey: 16315 case NSAPI::NSMutableDict_setValueForKey: 16316 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 16317 return 0; 16318 16319 default: 16320 return None; 16321 } 16322 16323 return None; 16324 } 16325 16326 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 16327 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 16328 Message->getReceiverInterface(), 16329 NSAPI::ClassId_NSMutableSet); 16330 16331 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 16332 Message->getReceiverInterface(), 16333 NSAPI::ClassId_NSMutableOrderedSet); 16334 if (!IsMutableSet && !IsMutableOrderedSet) { 16335 return None; 16336 } 16337 16338 Selector Sel = Message->getSelector(); 16339 16340 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 16341 if (!MKOpt) { 16342 return None; 16343 } 16344 16345 NSAPI::NSSetMethodKind MK = *MKOpt; 16346 16347 switch (MK) { 16348 case NSAPI::NSMutableSet_addObject: 16349 case NSAPI::NSOrderedSet_setObjectAtIndex: 16350 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 16351 case NSAPI::NSOrderedSet_insertObjectAtIndex: 16352 return 0; 16353 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 16354 return 1; 16355 } 16356 16357 return None; 16358 } 16359 16360 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 16361 if (!Message->isInstanceMessage()) { 16362 return; 16363 } 16364 16365 Optional<int> ArgOpt; 16366 16367 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 16368 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 16369 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 16370 return; 16371 } 16372 16373 int ArgIndex = *ArgOpt; 16374 16375 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 16376 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 16377 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 16378 } 16379 16380 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 16381 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 16382 if (ArgRE->isObjCSelfExpr()) { 16383 Diag(Message->getSourceRange().getBegin(), 16384 diag::warn_objc_circular_container) 16385 << ArgRE->getDecl() << StringRef("'super'"); 16386 } 16387 } 16388 } else { 16389 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 16390 16391 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 16392 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 16393 } 16394 16395 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 16396 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 16397 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 16398 ValueDecl *Decl = ReceiverRE->getDecl(); 16399 Diag(Message->getSourceRange().getBegin(), 16400 diag::warn_objc_circular_container) 16401 << Decl << Decl; 16402 if (!ArgRE->isObjCSelfExpr()) { 16403 Diag(Decl->getLocation(), 16404 diag::note_objc_circular_container_declared_here) 16405 << Decl; 16406 } 16407 } 16408 } 16409 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 16410 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 16411 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 16412 ObjCIvarDecl *Decl = IvarRE->getDecl(); 16413 Diag(Message->getSourceRange().getBegin(), 16414 diag::warn_objc_circular_container) 16415 << Decl << Decl; 16416 Diag(Decl->getLocation(), 16417 diag::note_objc_circular_container_declared_here) 16418 << Decl; 16419 } 16420 } 16421 } 16422 } 16423 } 16424 16425 /// Check a message send to see if it's likely to cause a retain cycle. 16426 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 16427 // Only check instance methods whose selector looks like a setter. 16428 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 16429 return; 16430 16431 // Try to find a variable that the receiver is strongly owned by. 16432 RetainCycleOwner owner; 16433 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 16434 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 16435 return; 16436 } else { 16437 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 16438 owner.Variable = getCurMethodDecl()->getSelfDecl(); 16439 owner.Loc = msg->getSuperLoc(); 16440 owner.Range = msg->getSuperLoc(); 16441 } 16442 16443 // Check whether the receiver is captured by any of the arguments. 16444 const ObjCMethodDecl *MD = msg->getMethodDecl(); 16445 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 16446 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 16447 // noescape blocks should not be retained by the method. 16448 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 16449 continue; 16450 return diagnoseRetainCycle(*this, capturer, owner); 16451 } 16452 } 16453 } 16454 16455 /// Check a property assign to see if it's likely to cause a retain cycle. 16456 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 16457 RetainCycleOwner owner; 16458 if (!findRetainCycleOwner(*this, receiver, owner)) 16459 return; 16460 16461 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 16462 diagnoseRetainCycle(*this, capturer, owner); 16463 } 16464 16465 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 16466 RetainCycleOwner Owner; 16467 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 16468 return; 16469 16470 // Because we don't have an expression for the variable, we have to set the 16471 // location explicitly here. 16472 Owner.Loc = Var->getLocation(); 16473 Owner.Range = Var->getSourceRange(); 16474 16475 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 16476 diagnoseRetainCycle(*this, Capturer, Owner); 16477 } 16478 16479 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 16480 Expr *RHS, bool isProperty) { 16481 // Check if RHS is an Objective-C object literal, which also can get 16482 // immediately zapped in a weak reference. Note that we explicitly 16483 // allow ObjCStringLiterals, since those are designed to never really die. 16484 RHS = RHS->IgnoreParenImpCasts(); 16485 16486 // This enum needs to match with the 'select' in 16487 // warn_objc_arc_literal_assign (off-by-1). 16488 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 16489 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 16490 return false; 16491 16492 S.Diag(Loc, diag::warn_arc_literal_assign) 16493 << (unsigned) Kind 16494 << (isProperty ? 0 : 1) 16495 << RHS->getSourceRange(); 16496 16497 return true; 16498 } 16499 16500 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 16501 Qualifiers::ObjCLifetime LT, 16502 Expr *RHS, bool isProperty) { 16503 // Strip off any implicit cast added to get to the one ARC-specific. 16504 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 16505 if (cast->getCastKind() == CK_ARCConsumeObject) { 16506 S.Diag(Loc, diag::warn_arc_retained_assign) 16507 << (LT == Qualifiers::OCL_ExplicitNone) 16508 << (isProperty ? 0 : 1) 16509 << RHS->getSourceRange(); 16510 return true; 16511 } 16512 RHS = cast->getSubExpr(); 16513 } 16514 16515 if (LT == Qualifiers::OCL_Weak && 16516 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 16517 return true; 16518 16519 return false; 16520 } 16521 16522 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 16523 QualType LHS, Expr *RHS) { 16524 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 16525 16526 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 16527 return false; 16528 16529 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 16530 return true; 16531 16532 return false; 16533 } 16534 16535 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 16536 Expr *LHS, Expr *RHS) { 16537 QualType LHSType; 16538 // PropertyRef on LHS type need be directly obtained from 16539 // its declaration as it has a PseudoType. 16540 ObjCPropertyRefExpr *PRE 16541 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 16542 if (PRE && !PRE->isImplicitProperty()) { 16543 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 16544 if (PD) 16545 LHSType = PD->getType(); 16546 } 16547 16548 if (LHSType.isNull()) 16549 LHSType = LHS->getType(); 16550 16551 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 16552 16553 if (LT == Qualifiers::OCL_Weak) { 16554 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 16555 getCurFunction()->markSafeWeakUse(LHS); 16556 } 16557 16558 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 16559 return; 16560 16561 // FIXME. Check for other life times. 16562 if (LT != Qualifiers::OCL_None) 16563 return; 16564 16565 if (PRE) { 16566 if (PRE->isImplicitProperty()) 16567 return; 16568 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 16569 if (!PD) 16570 return; 16571 16572 unsigned Attributes = PD->getPropertyAttributes(); 16573 if (Attributes & ObjCPropertyAttribute::kind_assign) { 16574 // when 'assign' attribute was not explicitly specified 16575 // by user, ignore it and rely on property type itself 16576 // for lifetime info. 16577 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 16578 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 16579 LHSType->isObjCRetainableType()) 16580 return; 16581 16582 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 16583 if (cast->getCastKind() == CK_ARCConsumeObject) { 16584 Diag(Loc, diag::warn_arc_retained_property_assign) 16585 << RHS->getSourceRange(); 16586 return; 16587 } 16588 RHS = cast->getSubExpr(); 16589 } 16590 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 16591 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 16592 return; 16593 } 16594 } 16595 } 16596 16597 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 16598 16599 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 16600 SourceLocation StmtLoc, 16601 const NullStmt *Body) { 16602 // Do not warn if the body is a macro that expands to nothing, e.g: 16603 // 16604 // #define CALL(x) 16605 // if (condition) 16606 // CALL(0); 16607 if (Body->hasLeadingEmptyMacro()) 16608 return false; 16609 16610 // Get line numbers of statement and body. 16611 bool StmtLineInvalid; 16612 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 16613 &StmtLineInvalid); 16614 if (StmtLineInvalid) 16615 return false; 16616 16617 bool BodyLineInvalid; 16618 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 16619 &BodyLineInvalid); 16620 if (BodyLineInvalid) 16621 return false; 16622 16623 // Warn if null statement and body are on the same line. 16624 if (StmtLine != BodyLine) 16625 return false; 16626 16627 return true; 16628 } 16629 16630 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 16631 const Stmt *Body, 16632 unsigned DiagID) { 16633 // Since this is a syntactic check, don't emit diagnostic for template 16634 // instantiations, this just adds noise. 16635 if (CurrentInstantiationScope) 16636 return; 16637 16638 // The body should be a null statement. 16639 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16640 if (!NBody) 16641 return; 16642 16643 // Do the usual checks. 16644 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16645 return; 16646 16647 Diag(NBody->getSemiLoc(), DiagID); 16648 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16649 } 16650 16651 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 16652 const Stmt *PossibleBody) { 16653 assert(!CurrentInstantiationScope); // Ensured by caller 16654 16655 SourceLocation StmtLoc; 16656 const Stmt *Body; 16657 unsigned DiagID; 16658 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 16659 StmtLoc = FS->getRParenLoc(); 16660 Body = FS->getBody(); 16661 DiagID = diag::warn_empty_for_body; 16662 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 16663 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 16664 Body = WS->getBody(); 16665 DiagID = diag::warn_empty_while_body; 16666 } else 16667 return; // Neither `for' nor `while'. 16668 16669 // The body should be a null statement. 16670 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16671 if (!NBody) 16672 return; 16673 16674 // Skip expensive checks if diagnostic is disabled. 16675 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 16676 return; 16677 16678 // Do the usual checks. 16679 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16680 return; 16681 16682 // `for(...);' and `while(...);' are popular idioms, so in order to keep 16683 // noise level low, emit diagnostics only if for/while is followed by a 16684 // CompoundStmt, e.g.: 16685 // for (int i = 0; i < n; i++); 16686 // { 16687 // a(i); 16688 // } 16689 // or if for/while is followed by a statement with more indentation 16690 // than for/while itself: 16691 // for (int i = 0; i < n; i++); 16692 // a(i); 16693 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 16694 if (!ProbableTypo) { 16695 bool BodyColInvalid; 16696 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 16697 PossibleBody->getBeginLoc(), &BodyColInvalid); 16698 if (BodyColInvalid) 16699 return; 16700 16701 bool StmtColInvalid; 16702 unsigned StmtCol = 16703 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 16704 if (StmtColInvalid) 16705 return; 16706 16707 if (BodyCol > StmtCol) 16708 ProbableTypo = true; 16709 } 16710 16711 if (ProbableTypo) { 16712 Diag(NBody->getSemiLoc(), DiagID); 16713 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16714 } 16715 } 16716 16717 //===--- CHECK: Warn on self move with std::move. -------------------------===// 16718 16719 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 16720 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 16721 SourceLocation OpLoc) { 16722 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 16723 return; 16724 16725 if (inTemplateInstantiation()) 16726 return; 16727 16728 // Strip parens and casts away. 16729 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 16730 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 16731 16732 // Check for a call expression 16733 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 16734 if (!CE || CE->getNumArgs() != 1) 16735 return; 16736 16737 // Check for a call to std::move 16738 if (!CE->isCallToStdMove()) 16739 return; 16740 16741 // Get argument from std::move 16742 RHSExpr = CE->getArg(0); 16743 16744 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 16745 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 16746 16747 // Two DeclRefExpr's, check that the decls are the same. 16748 if (LHSDeclRef && RHSDeclRef) { 16749 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16750 return; 16751 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16752 RHSDeclRef->getDecl()->getCanonicalDecl()) 16753 return; 16754 16755 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16756 << LHSExpr->getSourceRange() 16757 << RHSExpr->getSourceRange(); 16758 return; 16759 } 16760 16761 // Member variables require a different approach to check for self moves. 16762 // MemberExpr's are the same if every nested MemberExpr refers to the same 16763 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 16764 // the base Expr's are CXXThisExpr's. 16765 const Expr *LHSBase = LHSExpr; 16766 const Expr *RHSBase = RHSExpr; 16767 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 16768 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 16769 if (!LHSME || !RHSME) 16770 return; 16771 16772 while (LHSME && RHSME) { 16773 if (LHSME->getMemberDecl()->getCanonicalDecl() != 16774 RHSME->getMemberDecl()->getCanonicalDecl()) 16775 return; 16776 16777 LHSBase = LHSME->getBase(); 16778 RHSBase = RHSME->getBase(); 16779 LHSME = dyn_cast<MemberExpr>(LHSBase); 16780 RHSME = dyn_cast<MemberExpr>(RHSBase); 16781 } 16782 16783 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16784 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16785 if (LHSDeclRef && RHSDeclRef) { 16786 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16787 return; 16788 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16789 RHSDeclRef->getDecl()->getCanonicalDecl()) 16790 return; 16791 16792 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16793 << LHSExpr->getSourceRange() 16794 << RHSExpr->getSourceRange(); 16795 return; 16796 } 16797 16798 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16799 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16800 << LHSExpr->getSourceRange() 16801 << RHSExpr->getSourceRange(); 16802 } 16803 16804 //===--- Layout compatibility ----------------------------------------------// 16805 16806 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16807 16808 /// Check if two enumeration types are layout-compatible. 16809 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16810 // C++11 [dcl.enum] p8: 16811 // Two enumeration types are layout-compatible if they have the same 16812 // underlying type. 16813 return ED1->isComplete() && ED2->isComplete() && 16814 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16815 } 16816 16817 /// Check if two fields are layout-compatible. 16818 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16819 FieldDecl *Field2) { 16820 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16821 return false; 16822 16823 if (Field1->isBitField() != Field2->isBitField()) 16824 return false; 16825 16826 if (Field1->isBitField()) { 16827 // Make sure that the bit-fields are the same length. 16828 unsigned Bits1 = Field1->getBitWidthValue(C); 16829 unsigned Bits2 = Field2->getBitWidthValue(C); 16830 16831 if (Bits1 != Bits2) 16832 return false; 16833 } 16834 16835 return true; 16836 } 16837 16838 /// Check if two standard-layout structs are layout-compatible. 16839 /// (C++11 [class.mem] p17) 16840 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16841 RecordDecl *RD2) { 16842 // If both records are C++ classes, check that base classes match. 16843 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16844 // If one of records is a CXXRecordDecl we are in C++ mode, 16845 // thus the other one is a CXXRecordDecl, too. 16846 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16847 // Check number of base classes. 16848 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16849 return false; 16850 16851 // Check the base classes. 16852 for (CXXRecordDecl::base_class_const_iterator 16853 Base1 = D1CXX->bases_begin(), 16854 BaseEnd1 = D1CXX->bases_end(), 16855 Base2 = D2CXX->bases_begin(); 16856 Base1 != BaseEnd1; 16857 ++Base1, ++Base2) { 16858 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16859 return false; 16860 } 16861 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16862 // If only RD2 is a C++ class, it should have zero base classes. 16863 if (D2CXX->getNumBases() > 0) 16864 return false; 16865 } 16866 16867 // Check the fields. 16868 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16869 Field2End = RD2->field_end(), 16870 Field1 = RD1->field_begin(), 16871 Field1End = RD1->field_end(); 16872 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16873 if (!isLayoutCompatible(C, *Field1, *Field2)) 16874 return false; 16875 } 16876 if (Field1 != Field1End || Field2 != Field2End) 16877 return false; 16878 16879 return true; 16880 } 16881 16882 /// Check if two standard-layout unions are layout-compatible. 16883 /// (C++11 [class.mem] p18) 16884 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16885 RecordDecl *RD2) { 16886 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16887 for (auto *Field2 : RD2->fields()) 16888 UnmatchedFields.insert(Field2); 16889 16890 for (auto *Field1 : RD1->fields()) { 16891 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16892 I = UnmatchedFields.begin(), 16893 E = UnmatchedFields.end(); 16894 16895 for ( ; I != E; ++I) { 16896 if (isLayoutCompatible(C, Field1, *I)) { 16897 bool Result = UnmatchedFields.erase(*I); 16898 (void) Result; 16899 assert(Result); 16900 break; 16901 } 16902 } 16903 if (I == E) 16904 return false; 16905 } 16906 16907 return UnmatchedFields.empty(); 16908 } 16909 16910 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16911 RecordDecl *RD2) { 16912 if (RD1->isUnion() != RD2->isUnion()) 16913 return false; 16914 16915 if (RD1->isUnion()) 16916 return isLayoutCompatibleUnion(C, RD1, RD2); 16917 else 16918 return isLayoutCompatibleStruct(C, RD1, RD2); 16919 } 16920 16921 /// Check if two types are layout-compatible in C++11 sense. 16922 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16923 if (T1.isNull() || T2.isNull()) 16924 return false; 16925 16926 // C++11 [basic.types] p11: 16927 // If two types T1 and T2 are the same type, then T1 and T2 are 16928 // layout-compatible types. 16929 if (C.hasSameType(T1, T2)) 16930 return true; 16931 16932 T1 = T1.getCanonicalType().getUnqualifiedType(); 16933 T2 = T2.getCanonicalType().getUnqualifiedType(); 16934 16935 const Type::TypeClass TC1 = T1->getTypeClass(); 16936 const Type::TypeClass TC2 = T2->getTypeClass(); 16937 16938 if (TC1 != TC2) 16939 return false; 16940 16941 if (TC1 == Type::Enum) { 16942 return isLayoutCompatible(C, 16943 cast<EnumType>(T1)->getDecl(), 16944 cast<EnumType>(T2)->getDecl()); 16945 } else if (TC1 == Type::Record) { 16946 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16947 return false; 16948 16949 return isLayoutCompatible(C, 16950 cast<RecordType>(T1)->getDecl(), 16951 cast<RecordType>(T2)->getDecl()); 16952 } 16953 16954 return false; 16955 } 16956 16957 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16958 16959 /// Given a type tag expression find the type tag itself. 16960 /// 16961 /// \param TypeExpr Type tag expression, as it appears in user's code. 16962 /// 16963 /// \param VD Declaration of an identifier that appears in a type tag. 16964 /// 16965 /// \param MagicValue Type tag magic value. 16966 /// 16967 /// \param isConstantEvaluated whether the evalaution should be performed in 16968 16969 /// constant context. 16970 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16971 const ValueDecl **VD, uint64_t *MagicValue, 16972 bool isConstantEvaluated) { 16973 while(true) { 16974 if (!TypeExpr) 16975 return false; 16976 16977 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16978 16979 switch (TypeExpr->getStmtClass()) { 16980 case Stmt::UnaryOperatorClass: { 16981 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16982 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16983 TypeExpr = UO->getSubExpr(); 16984 continue; 16985 } 16986 return false; 16987 } 16988 16989 case Stmt::DeclRefExprClass: { 16990 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16991 *VD = DRE->getDecl(); 16992 return true; 16993 } 16994 16995 case Stmt::IntegerLiteralClass: { 16996 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16997 llvm::APInt MagicValueAPInt = IL->getValue(); 16998 if (MagicValueAPInt.getActiveBits() <= 64) { 16999 *MagicValue = MagicValueAPInt.getZExtValue(); 17000 return true; 17001 } else 17002 return false; 17003 } 17004 17005 case Stmt::BinaryConditionalOperatorClass: 17006 case Stmt::ConditionalOperatorClass: { 17007 const AbstractConditionalOperator *ACO = 17008 cast<AbstractConditionalOperator>(TypeExpr); 17009 bool Result; 17010 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 17011 isConstantEvaluated)) { 17012 if (Result) 17013 TypeExpr = ACO->getTrueExpr(); 17014 else 17015 TypeExpr = ACO->getFalseExpr(); 17016 continue; 17017 } 17018 return false; 17019 } 17020 17021 case Stmt::BinaryOperatorClass: { 17022 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 17023 if (BO->getOpcode() == BO_Comma) { 17024 TypeExpr = BO->getRHS(); 17025 continue; 17026 } 17027 return false; 17028 } 17029 17030 default: 17031 return false; 17032 } 17033 } 17034 } 17035 17036 /// Retrieve the C type corresponding to type tag TypeExpr. 17037 /// 17038 /// \param TypeExpr Expression that specifies a type tag. 17039 /// 17040 /// \param MagicValues Registered magic values. 17041 /// 17042 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 17043 /// kind. 17044 /// 17045 /// \param TypeInfo Information about the corresponding C type. 17046 /// 17047 /// \param isConstantEvaluated whether the evalaution should be performed in 17048 /// constant context. 17049 /// 17050 /// \returns true if the corresponding C type was found. 17051 static bool GetMatchingCType( 17052 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 17053 const ASTContext &Ctx, 17054 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 17055 *MagicValues, 17056 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 17057 bool isConstantEvaluated) { 17058 FoundWrongKind = false; 17059 17060 // Variable declaration that has type_tag_for_datatype attribute. 17061 const ValueDecl *VD = nullptr; 17062 17063 uint64_t MagicValue; 17064 17065 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 17066 return false; 17067 17068 if (VD) { 17069 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 17070 if (I->getArgumentKind() != ArgumentKind) { 17071 FoundWrongKind = true; 17072 return false; 17073 } 17074 TypeInfo.Type = I->getMatchingCType(); 17075 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 17076 TypeInfo.MustBeNull = I->getMustBeNull(); 17077 return true; 17078 } 17079 return false; 17080 } 17081 17082 if (!MagicValues) 17083 return false; 17084 17085 llvm::DenseMap<Sema::TypeTagMagicValue, 17086 Sema::TypeTagData>::const_iterator I = 17087 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 17088 if (I == MagicValues->end()) 17089 return false; 17090 17091 TypeInfo = I->second; 17092 return true; 17093 } 17094 17095 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 17096 uint64_t MagicValue, QualType Type, 17097 bool LayoutCompatible, 17098 bool MustBeNull) { 17099 if (!TypeTagForDatatypeMagicValues) 17100 TypeTagForDatatypeMagicValues.reset( 17101 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 17102 17103 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 17104 (*TypeTagForDatatypeMagicValues)[Magic] = 17105 TypeTagData(Type, LayoutCompatible, MustBeNull); 17106 } 17107 17108 static bool IsSameCharType(QualType T1, QualType T2) { 17109 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 17110 if (!BT1) 17111 return false; 17112 17113 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 17114 if (!BT2) 17115 return false; 17116 17117 BuiltinType::Kind T1Kind = BT1->getKind(); 17118 BuiltinType::Kind T2Kind = BT2->getKind(); 17119 17120 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 17121 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 17122 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 17123 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 17124 } 17125 17126 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 17127 const ArrayRef<const Expr *> ExprArgs, 17128 SourceLocation CallSiteLoc) { 17129 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 17130 bool IsPointerAttr = Attr->getIsPointer(); 17131 17132 // Retrieve the argument representing the 'type_tag'. 17133 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 17134 if (TypeTagIdxAST >= ExprArgs.size()) { 17135 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 17136 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 17137 return; 17138 } 17139 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 17140 bool FoundWrongKind; 17141 TypeTagData TypeInfo; 17142 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 17143 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 17144 TypeInfo, isConstantEvaluated())) { 17145 if (FoundWrongKind) 17146 Diag(TypeTagExpr->getExprLoc(), 17147 diag::warn_type_tag_for_datatype_wrong_kind) 17148 << TypeTagExpr->getSourceRange(); 17149 return; 17150 } 17151 17152 // Retrieve the argument representing the 'arg_idx'. 17153 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 17154 if (ArgumentIdxAST >= ExprArgs.size()) { 17155 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 17156 << 1 << Attr->getArgumentIdx().getSourceIndex(); 17157 return; 17158 } 17159 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 17160 if (IsPointerAttr) { 17161 // Skip implicit cast of pointer to `void *' (as a function argument). 17162 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 17163 if (ICE->getType()->isVoidPointerType() && 17164 ICE->getCastKind() == CK_BitCast) 17165 ArgumentExpr = ICE->getSubExpr(); 17166 } 17167 QualType ArgumentType = ArgumentExpr->getType(); 17168 17169 // Passing a `void*' pointer shouldn't trigger a warning. 17170 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 17171 return; 17172 17173 if (TypeInfo.MustBeNull) { 17174 // Type tag with matching void type requires a null pointer. 17175 if (!ArgumentExpr->isNullPointerConstant(Context, 17176 Expr::NPC_ValueDependentIsNotNull)) { 17177 Diag(ArgumentExpr->getExprLoc(), 17178 diag::warn_type_safety_null_pointer_required) 17179 << ArgumentKind->getName() 17180 << ArgumentExpr->getSourceRange() 17181 << TypeTagExpr->getSourceRange(); 17182 } 17183 return; 17184 } 17185 17186 QualType RequiredType = TypeInfo.Type; 17187 if (IsPointerAttr) 17188 RequiredType = Context.getPointerType(RequiredType); 17189 17190 bool mismatch = false; 17191 if (!TypeInfo.LayoutCompatible) { 17192 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 17193 17194 // C++11 [basic.fundamental] p1: 17195 // Plain char, signed char, and unsigned char are three distinct types. 17196 // 17197 // But we treat plain `char' as equivalent to `signed char' or `unsigned 17198 // char' depending on the current char signedness mode. 17199 if (mismatch) 17200 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 17201 RequiredType->getPointeeType())) || 17202 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 17203 mismatch = false; 17204 } else 17205 if (IsPointerAttr) 17206 mismatch = !isLayoutCompatible(Context, 17207 ArgumentType->getPointeeType(), 17208 RequiredType->getPointeeType()); 17209 else 17210 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 17211 17212 if (mismatch) 17213 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 17214 << ArgumentType << ArgumentKind 17215 << TypeInfo.LayoutCompatible << RequiredType 17216 << ArgumentExpr->getSourceRange() 17217 << TypeTagExpr->getSourceRange(); 17218 } 17219 17220 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 17221 CharUnits Alignment) { 17222 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 17223 } 17224 17225 void Sema::DiagnoseMisalignedMembers() { 17226 for (MisalignedMember &m : MisalignedMembers) { 17227 const NamedDecl *ND = m.RD; 17228 if (ND->getName().empty()) { 17229 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 17230 ND = TD; 17231 } 17232 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 17233 << m.MD << ND << m.E->getSourceRange(); 17234 } 17235 MisalignedMembers.clear(); 17236 } 17237 17238 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 17239 E = E->IgnoreParens(); 17240 if (!T->isPointerType() && !T->isIntegerType()) 17241 return; 17242 if (isa<UnaryOperator>(E) && 17243 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 17244 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 17245 if (isa<MemberExpr>(Op)) { 17246 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 17247 if (MA != MisalignedMembers.end() && 17248 (T->isIntegerType() || 17249 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 17250 Context.getTypeAlignInChars( 17251 T->getPointeeType()) <= MA->Alignment)))) 17252 MisalignedMembers.erase(MA); 17253 } 17254 } 17255 } 17256 17257 void Sema::RefersToMemberWithReducedAlignment( 17258 Expr *E, 17259 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 17260 Action) { 17261 const auto *ME = dyn_cast<MemberExpr>(E); 17262 if (!ME) 17263 return; 17264 17265 // No need to check expressions with an __unaligned-qualified type. 17266 if (E->getType().getQualifiers().hasUnaligned()) 17267 return; 17268 17269 // For a chain of MemberExpr like "a.b.c.d" this list 17270 // will keep FieldDecl's like [d, c, b]. 17271 SmallVector<FieldDecl *, 4> ReverseMemberChain; 17272 const MemberExpr *TopME = nullptr; 17273 bool AnyIsPacked = false; 17274 do { 17275 QualType BaseType = ME->getBase()->getType(); 17276 if (BaseType->isDependentType()) 17277 return; 17278 if (ME->isArrow()) 17279 BaseType = BaseType->getPointeeType(); 17280 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 17281 if (RD->isInvalidDecl()) 17282 return; 17283 17284 ValueDecl *MD = ME->getMemberDecl(); 17285 auto *FD = dyn_cast<FieldDecl>(MD); 17286 // We do not care about non-data members. 17287 if (!FD || FD->isInvalidDecl()) 17288 return; 17289 17290 AnyIsPacked = 17291 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 17292 ReverseMemberChain.push_back(FD); 17293 17294 TopME = ME; 17295 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 17296 } while (ME); 17297 assert(TopME && "We did not compute a topmost MemberExpr!"); 17298 17299 // Not the scope of this diagnostic. 17300 if (!AnyIsPacked) 17301 return; 17302 17303 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 17304 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 17305 // TODO: The innermost base of the member expression may be too complicated. 17306 // For now, just disregard these cases. This is left for future 17307 // improvement. 17308 if (!DRE && !isa<CXXThisExpr>(TopBase)) 17309 return; 17310 17311 // Alignment expected by the whole expression. 17312 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 17313 17314 // No need to do anything else with this case. 17315 if (ExpectedAlignment.isOne()) 17316 return; 17317 17318 // Synthesize offset of the whole access. 17319 CharUnits Offset; 17320 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain)) 17321 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD)); 17322 17323 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 17324 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 17325 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 17326 17327 // The base expression of the innermost MemberExpr may give 17328 // stronger guarantees than the class containing the member. 17329 if (DRE && !TopME->isArrow()) { 17330 const ValueDecl *VD = DRE->getDecl(); 17331 if (!VD->getType()->isReferenceType()) 17332 CompleteObjectAlignment = 17333 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 17334 } 17335 17336 // Check if the synthesized offset fulfills the alignment. 17337 if (Offset % ExpectedAlignment != 0 || 17338 // It may fulfill the offset it but the effective alignment may still be 17339 // lower than the expected expression alignment. 17340 CompleteObjectAlignment < ExpectedAlignment) { 17341 // If this happens, we want to determine a sensible culprit of this. 17342 // Intuitively, watching the chain of member expressions from right to 17343 // left, we start with the required alignment (as required by the field 17344 // type) but some packed attribute in that chain has reduced the alignment. 17345 // It may happen that another packed structure increases it again. But if 17346 // we are here such increase has not been enough. So pointing the first 17347 // FieldDecl that either is packed or else its RecordDecl is, 17348 // seems reasonable. 17349 FieldDecl *FD = nullptr; 17350 CharUnits Alignment; 17351 for (FieldDecl *FDI : ReverseMemberChain) { 17352 if (FDI->hasAttr<PackedAttr>() || 17353 FDI->getParent()->hasAttr<PackedAttr>()) { 17354 FD = FDI; 17355 Alignment = std::min( 17356 Context.getTypeAlignInChars(FD->getType()), 17357 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 17358 break; 17359 } 17360 } 17361 assert(FD && "We did not find a packed FieldDecl!"); 17362 Action(E, FD->getParent(), FD, Alignment); 17363 } 17364 } 17365 17366 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 17367 using namespace std::placeholders; 17368 17369 RefersToMemberWithReducedAlignment( 17370 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 17371 _2, _3, _4)); 17372 } 17373 17374 // Check if \p Ty is a valid type for the elementwise math builtins. If it is 17375 // not a valid type, emit an error message and return true. Otherwise return 17376 // false. 17377 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, 17378 QualType Ty) { 17379 if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) { 17380 S.Diag(Loc, diag::err_builtin_invalid_arg_type) 17381 << 1 << /* vector, integer or float ty*/ 0 << Ty; 17382 return true; 17383 } 17384 return false; 17385 } 17386 17387 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) { 17388 if (checkArgCount(*this, TheCall, 1)) 17389 return true; 17390 17391 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 17392 if (A.isInvalid()) 17393 return true; 17394 17395 TheCall->setArg(0, A.get()); 17396 QualType TyA = A.get()->getType(); 17397 17398 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 17399 return true; 17400 17401 TheCall->setType(TyA); 17402 return false; 17403 } 17404 17405 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) { 17406 if (checkArgCount(*this, TheCall, 2)) 17407 return true; 17408 17409 ExprResult A = TheCall->getArg(0); 17410 ExprResult B = TheCall->getArg(1); 17411 // Do standard promotions between the two arguments, returning their common 17412 // type. 17413 QualType Res = 17414 UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison); 17415 if (A.isInvalid() || B.isInvalid()) 17416 return true; 17417 17418 QualType TyA = A.get()->getType(); 17419 QualType TyB = B.get()->getType(); 17420 17421 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType()) 17422 return Diag(A.get()->getBeginLoc(), 17423 diag::err_typecheck_call_different_arg_types) 17424 << TyA << TyB; 17425 17426 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 17427 return true; 17428 17429 TheCall->setArg(0, A.get()); 17430 TheCall->setArg(1, B.get()); 17431 TheCall->setType(Res); 17432 return false; 17433 } 17434 17435 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) { 17436 if (checkArgCount(*this, TheCall, 1)) 17437 return true; 17438 17439 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 17440 if (A.isInvalid()) 17441 return true; 17442 17443 TheCall->setArg(0, A.get()); 17444 return false; 17445 } 17446 17447 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 17448 ExprResult CallResult) { 17449 if (checkArgCount(*this, TheCall, 1)) 17450 return ExprError(); 17451 17452 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 17453 if (MatrixArg.isInvalid()) 17454 return MatrixArg; 17455 Expr *Matrix = MatrixArg.get(); 17456 17457 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 17458 if (!MType) { 17459 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17460 << 1 << /* matrix ty*/ 1 << Matrix->getType(); 17461 return ExprError(); 17462 } 17463 17464 // Create returned matrix type by swapping rows and columns of the argument 17465 // matrix type. 17466 QualType ResultType = Context.getConstantMatrixType( 17467 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 17468 17469 // Change the return type to the type of the returned matrix. 17470 TheCall->setType(ResultType); 17471 17472 // Update call argument to use the possibly converted matrix argument. 17473 TheCall->setArg(0, Matrix); 17474 return CallResult; 17475 } 17476 17477 // Get and verify the matrix dimensions. 17478 static llvm::Optional<unsigned> 17479 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 17480 SourceLocation ErrorPos; 17481 Optional<llvm::APSInt> Value = 17482 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 17483 if (!Value) { 17484 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 17485 << Name; 17486 return {}; 17487 } 17488 uint64_t Dim = Value->getZExtValue(); 17489 if (!ConstantMatrixType::isDimensionValid(Dim)) { 17490 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 17491 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 17492 return {}; 17493 } 17494 return Dim; 17495 } 17496 17497 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 17498 ExprResult CallResult) { 17499 if (!getLangOpts().MatrixTypes) { 17500 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 17501 return ExprError(); 17502 } 17503 17504 if (checkArgCount(*this, TheCall, 4)) 17505 return ExprError(); 17506 17507 unsigned PtrArgIdx = 0; 17508 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 17509 Expr *RowsExpr = TheCall->getArg(1); 17510 Expr *ColumnsExpr = TheCall->getArg(2); 17511 Expr *StrideExpr = TheCall->getArg(3); 17512 17513 bool ArgError = false; 17514 17515 // Check pointer argument. 17516 { 17517 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 17518 if (PtrConv.isInvalid()) 17519 return PtrConv; 17520 PtrExpr = PtrConv.get(); 17521 TheCall->setArg(0, PtrExpr); 17522 if (PtrExpr->isTypeDependent()) { 17523 TheCall->setType(Context.DependentTy); 17524 return TheCall; 17525 } 17526 } 17527 17528 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 17529 QualType ElementTy; 17530 if (!PtrTy) { 17531 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17532 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 17533 ArgError = true; 17534 } else { 17535 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 17536 17537 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 17538 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17539 << PtrArgIdx + 1 << /* pointer to element ty*/ 2 17540 << PtrExpr->getType(); 17541 ArgError = true; 17542 } 17543 } 17544 17545 // Apply default Lvalue conversions and convert the expression to size_t. 17546 auto ApplyArgumentConversions = [this](Expr *E) { 17547 ExprResult Conv = DefaultLvalueConversion(E); 17548 if (Conv.isInvalid()) 17549 return Conv; 17550 17551 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 17552 }; 17553 17554 // Apply conversion to row and column expressions. 17555 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 17556 if (!RowsConv.isInvalid()) { 17557 RowsExpr = RowsConv.get(); 17558 TheCall->setArg(1, RowsExpr); 17559 } else 17560 RowsExpr = nullptr; 17561 17562 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 17563 if (!ColumnsConv.isInvalid()) { 17564 ColumnsExpr = ColumnsConv.get(); 17565 TheCall->setArg(2, ColumnsExpr); 17566 } else 17567 ColumnsExpr = nullptr; 17568 17569 // If any any part of the result matrix type is still pending, just use 17570 // Context.DependentTy, until all parts are resolved. 17571 if ((RowsExpr && RowsExpr->isTypeDependent()) || 17572 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 17573 TheCall->setType(Context.DependentTy); 17574 return CallResult; 17575 } 17576 17577 // Check row and column dimensions. 17578 llvm::Optional<unsigned> MaybeRows; 17579 if (RowsExpr) 17580 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 17581 17582 llvm::Optional<unsigned> MaybeColumns; 17583 if (ColumnsExpr) 17584 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 17585 17586 // Check stride argument. 17587 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 17588 if (StrideConv.isInvalid()) 17589 return ExprError(); 17590 StrideExpr = StrideConv.get(); 17591 TheCall->setArg(3, StrideExpr); 17592 17593 if (MaybeRows) { 17594 if (Optional<llvm::APSInt> Value = 17595 StrideExpr->getIntegerConstantExpr(Context)) { 17596 uint64_t Stride = Value->getZExtValue(); 17597 if (Stride < *MaybeRows) { 17598 Diag(StrideExpr->getBeginLoc(), 17599 diag::err_builtin_matrix_stride_too_small); 17600 ArgError = true; 17601 } 17602 } 17603 } 17604 17605 if (ArgError || !MaybeRows || !MaybeColumns) 17606 return ExprError(); 17607 17608 TheCall->setType( 17609 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 17610 return CallResult; 17611 } 17612 17613 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 17614 ExprResult CallResult) { 17615 if (checkArgCount(*this, TheCall, 3)) 17616 return ExprError(); 17617 17618 unsigned PtrArgIdx = 1; 17619 Expr *MatrixExpr = TheCall->getArg(0); 17620 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 17621 Expr *StrideExpr = TheCall->getArg(2); 17622 17623 bool ArgError = false; 17624 17625 { 17626 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 17627 if (MatrixConv.isInvalid()) 17628 return MatrixConv; 17629 MatrixExpr = MatrixConv.get(); 17630 TheCall->setArg(0, MatrixExpr); 17631 } 17632 if (MatrixExpr->isTypeDependent()) { 17633 TheCall->setType(Context.DependentTy); 17634 return TheCall; 17635 } 17636 17637 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 17638 if (!MatrixTy) { 17639 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17640 << 1 << /*matrix ty */ 1 << MatrixExpr->getType(); 17641 ArgError = true; 17642 } 17643 17644 { 17645 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 17646 if (PtrConv.isInvalid()) 17647 return PtrConv; 17648 PtrExpr = PtrConv.get(); 17649 TheCall->setArg(1, PtrExpr); 17650 if (PtrExpr->isTypeDependent()) { 17651 TheCall->setType(Context.DependentTy); 17652 return TheCall; 17653 } 17654 } 17655 17656 // Check pointer argument. 17657 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 17658 if (!PtrTy) { 17659 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17660 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 17661 ArgError = true; 17662 } else { 17663 QualType ElementTy = PtrTy->getPointeeType(); 17664 if (ElementTy.isConstQualified()) { 17665 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 17666 ArgError = true; 17667 } 17668 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 17669 if (MatrixTy && 17670 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 17671 Diag(PtrExpr->getBeginLoc(), 17672 diag::err_builtin_matrix_pointer_arg_mismatch) 17673 << ElementTy << MatrixTy->getElementType(); 17674 ArgError = true; 17675 } 17676 } 17677 17678 // Apply default Lvalue conversions and convert the stride expression to 17679 // size_t. 17680 { 17681 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 17682 if (StrideConv.isInvalid()) 17683 return StrideConv; 17684 17685 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 17686 if (StrideConv.isInvalid()) 17687 return StrideConv; 17688 StrideExpr = StrideConv.get(); 17689 TheCall->setArg(2, StrideExpr); 17690 } 17691 17692 // Check stride argument. 17693 if (MatrixTy) { 17694 if (Optional<llvm::APSInt> Value = 17695 StrideExpr->getIntegerConstantExpr(Context)) { 17696 uint64_t Stride = Value->getZExtValue(); 17697 if (Stride < MatrixTy->getNumRows()) { 17698 Diag(StrideExpr->getBeginLoc(), 17699 diag::err_builtin_matrix_stride_too_small); 17700 ArgError = true; 17701 } 17702 } 17703 } 17704 17705 if (ArgError) 17706 return ExprError(); 17707 17708 return CallResult; 17709 } 17710 17711 /// \brief Enforce the bounds of a TCB 17712 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 17713 /// directly calls other functions in the same TCB as marked by the enforce_tcb 17714 /// and enforce_tcb_leaf attributes. 17715 void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc, 17716 const NamedDecl *Callee) { 17717 const NamedDecl *Caller = getCurFunctionOrMethodDecl(); 17718 17719 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>()) 17720 return; 17721 17722 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 17723 // all TCBs the callee is a part of. 17724 llvm::StringSet<> CalleeTCBs; 17725 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 17726 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17727 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 17728 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17729 17730 // Go through the TCBs the caller is a part of and emit warnings if Caller 17731 // is in a TCB that the Callee is not. 17732 for_each( 17733 Caller->specific_attrs<EnforceTCBAttr>(), 17734 [&](const auto *A) { 17735 StringRef CallerTCB = A->getTCBName(); 17736 if (CalleeTCBs.count(CallerTCB) == 0) { 17737 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation) 17738 << Callee << CallerTCB; 17739 } 17740 }); 17741 } 17742