1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements extra semantic analysis beyond what is enforced 11 // by the C type system. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/AST/APValue.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/AttrIterator.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclBase.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclarationName.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/Expr.h" 27 #include "clang/AST/ExprCXX.h" 28 #include "clang/AST/ExprObjC.h" 29 #include "clang/AST/ExprOpenMP.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/OperationKinds.h" 32 #include "clang/AST/Stmt.h" 33 #include "clang/AST/TemplateBase.h" 34 #include "clang/AST/Type.h" 35 #include "clang/AST/TypeLoc.h" 36 #include "clang/AST/UnresolvedSet.h" 37 #include "clang/Analysis/Analyses/FormatString.h" 38 #include "clang/Basic/AddressSpaces.h" 39 #include "clang/Basic/CharInfo.h" 40 #include "clang/Basic/Diagnostic.h" 41 #include "clang/Basic/IdentifierTable.h" 42 #include "clang/Basic/LLVM.h" 43 #include "clang/Basic/LangOptions.h" 44 #include "clang/Basic/OpenCLOptions.h" 45 #include "clang/Basic/OperatorKinds.h" 46 #include "clang/Basic/PartialDiagnostic.h" 47 #include "clang/Basic/SourceLocation.h" 48 #include "clang/Basic/SourceManager.h" 49 #include "clang/Basic/Specifiers.h" 50 #include "clang/Basic/SyncScope.h" 51 #include "clang/Basic/TargetBuiltins.h" 52 #include "clang/Basic/TargetCXXABI.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "clang/Basic/TypeTraits.h" 55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 56 #include "clang/Sema/Initialization.h" 57 #include "clang/Sema/Lookup.h" 58 #include "clang/Sema/Ownership.h" 59 #include "clang/Sema/Scope.h" 60 #include "clang/Sema/ScopeInfo.h" 61 #include "clang/Sema/Sema.h" 62 #include "clang/Sema/SemaInternal.h" 63 #include "llvm/ADT/APFloat.h" 64 #include "llvm/ADT/APInt.h" 65 #include "llvm/ADT/APSInt.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/FoldingSet.h" 69 #include "llvm/ADT/None.h" 70 #include "llvm/ADT/Optional.h" 71 #include "llvm/ADT/STLExtras.h" 72 #include "llvm/ADT/SmallBitVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallString.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/StringRef.h" 77 #include "llvm/ADT/StringSwitch.h" 78 #include "llvm/ADT/Triple.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/ConvertUTF.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/Format.h" 85 #include "llvm/Support/Locale.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include <algorithm> 89 #include <cassert> 90 #include <cstddef> 91 #include <cstdint> 92 #include <functional> 93 #include <limits> 94 #include <string> 95 #include <tuple> 96 #include <utility> 97 98 using namespace clang; 99 using namespace sema; 100 101 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 102 unsigned ByteNo) const { 103 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 104 Context.getTargetInfo()); 105 } 106 107 /// Checks that a call expression's argument count is the desired number. 108 /// This is useful when doing custom type-checking. Returns true on error. 109 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 110 unsigned argCount = call->getNumArgs(); 111 if (argCount == desiredArgCount) return false; 112 113 if (argCount < desiredArgCount) 114 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 115 << 0 /*function call*/ << desiredArgCount << argCount 116 << call->getSourceRange(); 117 118 // Highlight all the excess arguments. 119 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 120 call->getArg(argCount - 1)->getLocEnd()); 121 122 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 123 << 0 /*function call*/ << desiredArgCount << argCount 124 << call->getArg(1)->getSourceRange(); 125 } 126 127 /// Check that the first argument to __builtin_annotation is an integer 128 /// and the second argument is a non-wide string literal. 129 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 130 if (checkArgCount(S, TheCall, 2)) 131 return true; 132 133 // First argument should be an integer. 134 Expr *ValArg = TheCall->getArg(0); 135 QualType Ty = ValArg->getType(); 136 if (!Ty->isIntegerType()) { 137 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 138 << ValArg->getSourceRange(); 139 return true; 140 } 141 142 // Second argument should be a constant string. 143 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 144 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 145 if (!Literal || !Literal->isAscii()) { 146 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 147 << StrArg->getSourceRange(); 148 return true; 149 } 150 151 TheCall->setType(Ty); 152 return false; 153 } 154 155 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 156 // We need at least one argument. 157 if (TheCall->getNumArgs() < 1) { 158 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 159 << 0 << 1 << TheCall->getNumArgs() 160 << TheCall->getCallee()->getSourceRange(); 161 return true; 162 } 163 164 // All arguments should be wide string literals. 165 for (Expr *Arg : TheCall->arguments()) { 166 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 167 if (!Literal || !Literal->isWide()) { 168 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str) 169 << Arg->getSourceRange(); 170 return true; 171 } 172 } 173 174 return false; 175 } 176 177 /// Check that the argument to __builtin_addressof is a glvalue, and set the 178 /// result type to the corresponding pointer type. 179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 180 if (checkArgCount(S, TheCall, 1)) 181 return true; 182 183 ExprResult Arg(TheCall->getArg(0)); 184 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 185 if (ResultType.isNull()) 186 return true; 187 188 TheCall->setArg(0, Arg.get()); 189 TheCall->setType(ResultType); 190 return false; 191 } 192 193 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 194 if (checkArgCount(S, TheCall, 3)) 195 return true; 196 197 // First two arguments should be integers. 198 for (unsigned I = 0; I < 2; ++I) { 199 Expr *Arg = TheCall->getArg(I); 200 QualType Ty = Arg->getType(); 201 if (!Ty->isIntegerType()) { 202 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 203 << Ty << Arg->getSourceRange(); 204 return true; 205 } 206 } 207 208 // Third argument should be a pointer to a non-const integer. 209 // IRGen correctly handles volatile, restrict, and address spaces, and 210 // the other qualifiers aren't possible. 211 { 212 Expr *Arg = TheCall->getArg(2); 213 QualType Ty = Arg->getType(); 214 const auto *PtrTy = Ty->getAs<PointerType>(); 215 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 216 !PtrTy->getPointeeType().isConstQualified())) { 217 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 218 << Ty << Arg->getSourceRange(); 219 return true; 220 } 221 } 222 223 return false; 224 } 225 226 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 227 CallExpr *TheCall, unsigned SizeIdx, 228 unsigned DstSizeIdx) { 229 if (TheCall->getNumArgs() <= SizeIdx || 230 TheCall->getNumArgs() <= DstSizeIdx) 231 return; 232 233 const Expr *SizeArg = TheCall->getArg(SizeIdx); 234 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 235 236 llvm::APSInt Size, DstSize; 237 238 // find out if both sizes are known at compile time 239 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 240 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 241 return; 242 243 if (Size.ule(DstSize)) 244 return; 245 246 // confirmed overflow so generate the diagnostic. 247 IdentifierInfo *FnName = FDecl->getIdentifier(); 248 SourceLocation SL = TheCall->getLocStart(); 249 SourceRange SR = TheCall->getSourceRange(); 250 251 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 252 } 253 254 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 255 if (checkArgCount(S, BuiltinCall, 2)) 256 return true; 257 258 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 259 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 260 Expr *Call = BuiltinCall->getArg(0); 261 Expr *Chain = BuiltinCall->getArg(1); 262 263 if (Call->getStmtClass() != Stmt::CallExprClass) { 264 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 265 << Call->getSourceRange(); 266 return true; 267 } 268 269 auto CE = cast<CallExpr>(Call); 270 if (CE->getCallee()->getType()->isBlockPointerType()) { 271 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 272 << Call->getSourceRange(); 273 return true; 274 } 275 276 const Decl *TargetDecl = CE->getCalleeDecl(); 277 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 278 if (FD->getBuiltinID()) { 279 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 280 << Call->getSourceRange(); 281 return true; 282 } 283 284 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 285 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 286 << Call->getSourceRange(); 287 return true; 288 } 289 290 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 291 if (ChainResult.isInvalid()) 292 return true; 293 if (!ChainResult.get()->getType()->isPointerType()) { 294 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 295 << Chain->getSourceRange(); 296 return true; 297 } 298 299 QualType ReturnTy = CE->getCallReturnType(S.Context); 300 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 301 QualType BuiltinTy = S.Context.getFunctionType( 302 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 303 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 304 305 Builtin = 306 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 307 308 BuiltinCall->setType(CE->getType()); 309 BuiltinCall->setValueKind(CE->getValueKind()); 310 BuiltinCall->setObjectKind(CE->getObjectKind()); 311 BuiltinCall->setCallee(Builtin); 312 BuiltinCall->setArg(1, ChainResult.get()); 313 314 return false; 315 } 316 317 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 318 Scope::ScopeFlags NeededScopeFlags, 319 unsigned DiagID) { 320 // Scopes aren't available during instantiation. Fortunately, builtin 321 // functions cannot be template args so they cannot be formed through template 322 // instantiation. Therefore checking once during the parse is sufficient. 323 if (SemaRef.inTemplateInstantiation()) 324 return false; 325 326 Scope *S = SemaRef.getCurScope(); 327 while (S && !S->isSEHExceptScope()) 328 S = S->getParent(); 329 if (!S || !(S->getFlags() & NeededScopeFlags)) { 330 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 331 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 332 << DRE->getDecl()->getIdentifier(); 333 return true; 334 } 335 336 return false; 337 } 338 339 static inline bool isBlockPointer(Expr *Arg) { 340 return Arg->getType()->isBlockPointerType(); 341 } 342 343 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 344 /// void*, which is a requirement of device side enqueue. 345 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 346 const BlockPointerType *BPT = 347 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 348 ArrayRef<QualType> Params = 349 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 350 unsigned ArgCounter = 0; 351 bool IllegalParams = false; 352 // Iterate through the block parameters until either one is found that is not 353 // a local void*, or the block is valid. 354 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 355 I != E; ++I, ++ArgCounter) { 356 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 357 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 358 LangAS::opencl_local) { 359 // Get the location of the error. If a block literal has been passed 360 // (BlockExpr) then we can point straight to the offending argument, 361 // else we just point to the variable reference. 362 SourceLocation ErrorLoc; 363 if (isa<BlockExpr>(BlockArg)) { 364 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 365 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 366 } else if (isa<DeclRefExpr>(BlockArg)) { 367 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 368 } 369 S.Diag(ErrorLoc, 370 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 371 IllegalParams = true; 372 } 373 } 374 375 return IllegalParams; 376 } 377 378 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 379 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 380 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension) 381 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 382 return true; 383 } 384 return false; 385 } 386 387 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 388 if (checkArgCount(S, TheCall, 2)) 389 return true; 390 391 if (checkOpenCLSubgroupExt(S, TheCall)) 392 return true; 393 394 // First argument is an ndrange_t type. 395 Expr *NDRangeArg = TheCall->getArg(0); 396 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 397 S.Diag(NDRangeArg->getLocStart(), 398 diag::err_opencl_builtin_expected_type) 399 << TheCall->getDirectCallee() << "'ndrange_t'"; 400 return true; 401 } 402 403 Expr *BlockArg = TheCall->getArg(1); 404 if (!isBlockPointer(BlockArg)) { 405 S.Diag(BlockArg->getLocStart(), 406 diag::err_opencl_builtin_expected_type) 407 << TheCall->getDirectCallee() << "block"; 408 return true; 409 } 410 return checkOpenCLBlockArgs(S, BlockArg); 411 } 412 413 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 414 /// get_kernel_work_group_size 415 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 416 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 417 if (checkArgCount(S, TheCall, 1)) 418 return true; 419 420 Expr *BlockArg = TheCall->getArg(0); 421 if (!isBlockPointer(BlockArg)) { 422 S.Diag(BlockArg->getLocStart(), 423 diag::err_opencl_builtin_expected_type) 424 << TheCall->getDirectCallee() << "block"; 425 return true; 426 } 427 return checkOpenCLBlockArgs(S, BlockArg); 428 } 429 430 /// Diagnose integer type and any valid implicit conversion to it. 431 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 432 const QualType &IntType); 433 434 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 435 unsigned Start, unsigned End) { 436 bool IllegalParams = false; 437 for (unsigned I = Start; I <= End; ++I) 438 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 439 S.Context.getSizeType()); 440 return IllegalParams; 441 } 442 443 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 444 /// 'local void*' parameter of passed block. 445 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 446 Expr *BlockArg, 447 unsigned NumNonVarArgs) { 448 const BlockPointerType *BPT = 449 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 450 unsigned NumBlockParams = 451 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 452 unsigned TotalNumArgs = TheCall->getNumArgs(); 453 454 // For each argument passed to the block, a corresponding uint needs to 455 // be passed to describe the size of the local memory. 456 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 457 S.Diag(TheCall->getLocStart(), 458 diag::err_opencl_enqueue_kernel_local_size_args); 459 return true; 460 } 461 462 // Check that the sizes of the local memory are specified by integers. 463 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 464 TotalNumArgs - 1); 465 } 466 467 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 468 /// overload formats specified in Table 6.13.17.1. 469 /// int enqueue_kernel(queue_t queue, 470 /// kernel_enqueue_flags_t flags, 471 /// const ndrange_t ndrange, 472 /// void (^block)(void)) 473 /// int enqueue_kernel(queue_t queue, 474 /// kernel_enqueue_flags_t flags, 475 /// const ndrange_t ndrange, 476 /// uint num_events_in_wait_list, 477 /// clk_event_t *event_wait_list, 478 /// clk_event_t *event_ret, 479 /// void (^block)(void)) 480 /// int enqueue_kernel(queue_t queue, 481 /// kernel_enqueue_flags_t flags, 482 /// const ndrange_t ndrange, 483 /// void (^block)(local void*, ...), 484 /// uint size0, ...) 485 /// int enqueue_kernel(queue_t queue, 486 /// kernel_enqueue_flags_t flags, 487 /// const ndrange_t ndrange, 488 /// uint num_events_in_wait_list, 489 /// clk_event_t *event_wait_list, 490 /// clk_event_t *event_ret, 491 /// void (^block)(local void*, ...), 492 /// uint size0, ...) 493 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 494 unsigned NumArgs = TheCall->getNumArgs(); 495 496 if (NumArgs < 4) { 497 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 498 return true; 499 } 500 501 Expr *Arg0 = TheCall->getArg(0); 502 Expr *Arg1 = TheCall->getArg(1); 503 Expr *Arg2 = TheCall->getArg(2); 504 Expr *Arg3 = TheCall->getArg(3); 505 506 // First argument always needs to be a queue_t type. 507 if (!Arg0->getType()->isQueueT()) { 508 S.Diag(TheCall->getArg(0)->getLocStart(), 509 diag::err_opencl_builtin_expected_type) 510 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 511 return true; 512 } 513 514 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 515 if (!Arg1->getType()->isIntegerType()) { 516 S.Diag(TheCall->getArg(1)->getLocStart(), 517 diag::err_opencl_builtin_expected_type) 518 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 519 return true; 520 } 521 522 // Third argument is always an ndrange_t type. 523 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 524 S.Diag(TheCall->getArg(2)->getLocStart(), 525 diag::err_opencl_builtin_expected_type) 526 << TheCall->getDirectCallee() << "'ndrange_t'"; 527 return true; 528 } 529 530 // With four arguments, there is only one form that the function could be 531 // called in: no events and no variable arguments. 532 if (NumArgs == 4) { 533 // check that the last argument is the right block type. 534 if (!isBlockPointer(Arg3)) { 535 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type) 536 << TheCall->getDirectCallee() << "block"; 537 return true; 538 } 539 // we have a block type, check the prototype 540 const BlockPointerType *BPT = 541 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 542 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 543 S.Diag(Arg3->getLocStart(), 544 diag::err_opencl_enqueue_kernel_blocks_no_args); 545 return true; 546 } 547 return false; 548 } 549 // we can have block + varargs. 550 if (isBlockPointer(Arg3)) 551 return (checkOpenCLBlockArgs(S, Arg3) || 552 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 553 // last two cases with either exactly 7 args or 7 args and varargs. 554 if (NumArgs >= 7) { 555 // check common block argument. 556 Expr *Arg6 = TheCall->getArg(6); 557 if (!isBlockPointer(Arg6)) { 558 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type) 559 << TheCall->getDirectCallee() << "block"; 560 return true; 561 } 562 if (checkOpenCLBlockArgs(S, Arg6)) 563 return true; 564 565 // Forth argument has to be any integer type. 566 if (!Arg3->getType()->isIntegerType()) { 567 S.Diag(TheCall->getArg(3)->getLocStart(), 568 diag::err_opencl_builtin_expected_type) 569 << TheCall->getDirectCallee() << "integer"; 570 return true; 571 } 572 // check remaining common arguments. 573 Expr *Arg4 = TheCall->getArg(4); 574 Expr *Arg5 = TheCall->getArg(5); 575 576 // Fifth argument is always passed as a pointer to clk_event_t. 577 if (!Arg4->isNullPointerConstant(S.Context, 578 Expr::NPC_ValueDependentIsNotNull) && 579 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 580 S.Diag(TheCall->getArg(4)->getLocStart(), 581 diag::err_opencl_builtin_expected_type) 582 << TheCall->getDirectCallee() 583 << S.Context.getPointerType(S.Context.OCLClkEventTy); 584 return true; 585 } 586 587 // Sixth argument is always passed as a pointer to clk_event_t. 588 if (!Arg5->isNullPointerConstant(S.Context, 589 Expr::NPC_ValueDependentIsNotNull) && 590 !(Arg5->getType()->isPointerType() && 591 Arg5->getType()->getPointeeType()->isClkEventT())) { 592 S.Diag(TheCall->getArg(5)->getLocStart(), 593 diag::err_opencl_builtin_expected_type) 594 << TheCall->getDirectCallee() 595 << S.Context.getPointerType(S.Context.OCLClkEventTy); 596 return true; 597 } 598 599 if (NumArgs == 7) 600 return false; 601 602 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 603 } 604 605 // None of the specific case has been detected, give generic error 606 S.Diag(TheCall->getLocStart(), 607 diag::err_opencl_enqueue_kernel_incorrect_args); 608 return true; 609 } 610 611 /// Returns OpenCL access qual. 612 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 613 return D->getAttr<OpenCLAccessAttr>(); 614 } 615 616 /// Returns true if pipe element type is different from the pointer. 617 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 618 const Expr *Arg0 = Call->getArg(0); 619 // First argument type should always be pipe. 620 if (!Arg0->getType()->isPipeType()) { 621 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 622 << Call->getDirectCallee() << Arg0->getSourceRange(); 623 return true; 624 } 625 OpenCLAccessAttr *AccessQual = 626 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 627 // Validates the access qualifier is compatible with the call. 628 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 629 // read_only and write_only, and assumed to be read_only if no qualifier is 630 // specified. 631 switch (Call->getDirectCallee()->getBuiltinID()) { 632 case Builtin::BIread_pipe: 633 case Builtin::BIreserve_read_pipe: 634 case Builtin::BIcommit_read_pipe: 635 case Builtin::BIwork_group_reserve_read_pipe: 636 case Builtin::BIsub_group_reserve_read_pipe: 637 case Builtin::BIwork_group_commit_read_pipe: 638 case Builtin::BIsub_group_commit_read_pipe: 639 if (!(!AccessQual || AccessQual->isReadOnly())) { 640 S.Diag(Arg0->getLocStart(), 641 diag::err_opencl_builtin_pipe_invalid_access_modifier) 642 << "read_only" << Arg0->getSourceRange(); 643 return true; 644 } 645 break; 646 case Builtin::BIwrite_pipe: 647 case Builtin::BIreserve_write_pipe: 648 case Builtin::BIcommit_write_pipe: 649 case Builtin::BIwork_group_reserve_write_pipe: 650 case Builtin::BIsub_group_reserve_write_pipe: 651 case Builtin::BIwork_group_commit_write_pipe: 652 case Builtin::BIsub_group_commit_write_pipe: 653 if (!(AccessQual && AccessQual->isWriteOnly())) { 654 S.Diag(Arg0->getLocStart(), 655 diag::err_opencl_builtin_pipe_invalid_access_modifier) 656 << "write_only" << Arg0->getSourceRange(); 657 return true; 658 } 659 break; 660 default: 661 break; 662 } 663 return false; 664 } 665 666 /// Returns true if pipe element type is different from the pointer. 667 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 668 const Expr *Arg0 = Call->getArg(0); 669 const Expr *ArgIdx = Call->getArg(Idx); 670 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 671 const QualType EltTy = PipeTy->getElementType(); 672 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 673 // The Idx argument should be a pointer and the type of the pointer and 674 // the type of pipe element should also be the same. 675 if (!ArgTy || 676 !S.Context.hasSameType( 677 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 678 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 679 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 680 << ArgIdx->getType() << ArgIdx->getSourceRange(); 681 return true; 682 } 683 return false; 684 } 685 686 // \brief Performs semantic analysis for the read/write_pipe call. 687 // \param S Reference to the semantic analyzer. 688 // \param Call A pointer to the builtin call. 689 // \return True if a semantic error has been found, false otherwise. 690 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 691 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 692 // functions have two forms. 693 switch (Call->getNumArgs()) { 694 case 2: 695 if (checkOpenCLPipeArg(S, Call)) 696 return true; 697 // The call with 2 arguments should be 698 // read/write_pipe(pipe T, T*). 699 // Check packet type T. 700 if (checkOpenCLPipePacketType(S, Call, 1)) 701 return true; 702 break; 703 704 case 4: { 705 if (checkOpenCLPipeArg(S, Call)) 706 return true; 707 // The call with 4 arguments should be 708 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 709 // Check reserve_id_t. 710 if (!Call->getArg(1)->getType()->isReserveIDT()) { 711 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 712 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 713 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 714 return true; 715 } 716 717 // Check the index. 718 const Expr *Arg2 = Call->getArg(2); 719 if (!Arg2->getType()->isIntegerType() && 720 !Arg2->getType()->isUnsignedIntegerType()) { 721 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 722 << Call->getDirectCallee() << S.Context.UnsignedIntTy 723 << Arg2->getType() << Arg2->getSourceRange(); 724 return true; 725 } 726 727 // Check packet type T. 728 if (checkOpenCLPipePacketType(S, Call, 3)) 729 return true; 730 } break; 731 default: 732 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 733 << Call->getDirectCallee() << Call->getSourceRange(); 734 return true; 735 } 736 737 return false; 738 } 739 740 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 741 // /_}reserve_{read/write}_pipe 742 // \param S Reference to the semantic analyzer. 743 // \param Call The call to the builtin function to be analyzed. 744 // \return True if a semantic error was found, false otherwise. 745 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 746 if (checkArgCount(S, Call, 2)) 747 return true; 748 749 if (checkOpenCLPipeArg(S, Call)) 750 return true; 751 752 // Check the reserve size. 753 if (!Call->getArg(1)->getType()->isIntegerType() && 754 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 755 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 756 << Call->getDirectCallee() << S.Context.UnsignedIntTy 757 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 758 return true; 759 } 760 761 // Since return type of reserve_read/write_pipe built-in function is 762 // reserve_id_t, which is not defined in the builtin def file , we used int 763 // as return type and need to override the return type of these functions. 764 Call->setType(S.Context.OCLReserveIDTy); 765 766 return false; 767 } 768 769 // \brief Performs a semantic analysis on {work_group_/sub_group_ 770 // /_}commit_{read/write}_pipe 771 // \param S Reference to the semantic analyzer. 772 // \param Call The call to the builtin function to be analyzed. 773 // \return True if a semantic error was found, false otherwise. 774 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 775 if (checkArgCount(S, Call, 2)) 776 return true; 777 778 if (checkOpenCLPipeArg(S, Call)) 779 return true; 780 781 // Check reserve_id_t. 782 if (!Call->getArg(1)->getType()->isReserveIDT()) { 783 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 784 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 785 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 786 return true; 787 } 788 789 return false; 790 } 791 792 // \brief Performs a semantic analysis on the call to built-in Pipe 793 // Query Functions. 794 // \param S Reference to the semantic analyzer. 795 // \param Call The call to the builtin function to be analyzed. 796 // \return True if a semantic error was found, false otherwise. 797 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 798 if (checkArgCount(S, Call, 1)) 799 return true; 800 801 if (!Call->getArg(0)->getType()->isPipeType()) { 802 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 803 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 804 return true; 805 } 806 807 return false; 808 } 809 810 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 811 // \brief Performs semantic analysis for the to_global/local/private call. 812 // \param S Reference to the semantic analyzer. 813 // \param BuiltinID ID of the builtin function. 814 // \param Call A pointer to the builtin call. 815 // \return True if a semantic error has been found, false otherwise. 816 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 817 CallExpr *Call) { 818 if (Call->getNumArgs() != 1) { 819 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 820 << Call->getDirectCallee() << Call->getSourceRange(); 821 return true; 822 } 823 824 auto RT = Call->getArg(0)->getType(); 825 if (!RT->isPointerType() || RT->getPointeeType() 826 .getAddressSpace() == LangAS::opencl_constant) { 827 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 828 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 829 return true; 830 } 831 832 RT = RT->getPointeeType(); 833 auto Qual = RT.getQualifiers(); 834 switch (BuiltinID) { 835 case Builtin::BIto_global: 836 Qual.setAddressSpace(LangAS::opencl_global); 837 break; 838 case Builtin::BIto_local: 839 Qual.setAddressSpace(LangAS::opencl_local); 840 break; 841 case Builtin::BIto_private: 842 Qual.setAddressSpace(LangAS::opencl_private); 843 break; 844 default: 845 llvm_unreachable("Invalid builtin function"); 846 } 847 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 848 RT.getUnqualifiedType(), Qual))); 849 850 return false; 851 } 852 853 ExprResult 854 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 855 CallExpr *TheCall) { 856 ExprResult TheCallResult(TheCall); 857 858 // Find out if any arguments are required to be integer constant expressions. 859 unsigned ICEArguments = 0; 860 ASTContext::GetBuiltinTypeError Error; 861 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 862 if (Error != ASTContext::GE_None) 863 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 864 865 // If any arguments are required to be ICE's, check and diagnose. 866 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 867 // Skip arguments not required to be ICE's. 868 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 869 870 llvm::APSInt Result; 871 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 872 return true; 873 ICEArguments &= ~(1 << ArgNo); 874 } 875 876 switch (BuiltinID) { 877 case Builtin::BI__builtin___CFStringMakeConstantString: 878 assert(TheCall->getNumArgs() == 1 && 879 "Wrong # arguments to builtin CFStringMakeConstantString"); 880 if (CheckObjCString(TheCall->getArg(0))) 881 return ExprError(); 882 break; 883 case Builtin::BI__builtin_ms_va_start: 884 case Builtin::BI__builtin_stdarg_start: 885 case Builtin::BI__builtin_va_start: 886 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 887 return ExprError(); 888 break; 889 case Builtin::BI__va_start: { 890 switch (Context.getTargetInfo().getTriple().getArch()) { 891 case llvm::Triple::arm: 892 case llvm::Triple::thumb: 893 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 894 return ExprError(); 895 break; 896 default: 897 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 898 return ExprError(); 899 break; 900 } 901 break; 902 } 903 case Builtin::BI__builtin_isgreater: 904 case Builtin::BI__builtin_isgreaterequal: 905 case Builtin::BI__builtin_isless: 906 case Builtin::BI__builtin_islessequal: 907 case Builtin::BI__builtin_islessgreater: 908 case Builtin::BI__builtin_isunordered: 909 if (SemaBuiltinUnorderedCompare(TheCall)) 910 return ExprError(); 911 break; 912 case Builtin::BI__builtin_fpclassify: 913 if (SemaBuiltinFPClassification(TheCall, 6)) 914 return ExprError(); 915 break; 916 case Builtin::BI__builtin_isfinite: 917 case Builtin::BI__builtin_isinf: 918 case Builtin::BI__builtin_isinf_sign: 919 case Builtin::BI__builtin_isnan: 920 case Builtin::BI__builtin_isnormal: 921 if (SemaBuiltinFPClassification(TheCall, 1)) 922 return ExprError(); 923 break; 924 case Builtin::BI__builtin_shufflevector: 925 return SemaBuiltinShuffleVector(TheCall); 926 // TheCall will be freed by the smart pointer here, but that's fine, since 927 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 928 case Builtin::BI__builtin_prefetch: 929 if (SemaBuiltinPrefetch(TheCall)) 930 return ExprError(); 931 break; 932 case Builtin::BI__builtin_alloca_with_align: 933 if (SemaBuiltinAllocaWithAlign(TheCall)) 934 return ExprError(); 935 break; 936 case Builtin::BI__assume: 937 case Builtin::BI__builtin_assume: 938 if (SemaBuiltinAssume(TheCall)) 939 return ExprError(); 940 break; 941 case Builtin::BI__builtin_assume_aligned: 942 if (SemaBuiltinAssumeAligned(TheCall)) 943 return ExprError(); 944 break; 945 case Builtin::BI__builtin_object_size: 946 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 947 return ExprError(); 948 break; 949 case Builtin::BI__builtin_longjmp: 950 if (SemaBuiltinLongjmp(TheCall)) 951 return ExprError(); 952 break; 953 case Builtin::BI__builtin_setjmp: 954 if (SemaBuiltinSetjmp(TheCall)) 955 return ExprError(); 956 break; 957 case Builtin::BI_setjmp: 958 case Builtin::BI_setjmpex: 959 if (checkArgCount(*this, TheCall, 1)) 960 return true; 961 break; 962 case Builtin::BI__builtin_classify_type: 963 if (checkArgCount(*this, TheCall, 1)) return true; 964 TheCall->setType(Context.IntTy); 965 break; 966 case Builtin::BI__builtin_constant_p: 967 if (checkArgCount(*this, TheCall, 1)) return true; 968 TheCall->setType(Context.IntTy); 969 break; 970 case Builtin::BI__sync_fetch_and_add: 971 case Builtin::BI__sync_fetch_and_add_1: 972 case Builtin::BI__sync_fetch_and_add_2: 973 case Builtin::BI__sync_fetch_and_add_4: 974 case Builtin::BI__sync_fetch_and_add_8: 975 case Builtin::BI__sync_fetch_and_add_16: 976 case Builtin::BI__sync_fetch_and_sub: 977 case Builtin::BI__sync_fetch_and_sub_1: 978 case Builtin::BI__sync_fetch_and_sub_2: 979 case Builtin::BI__sync_fetch_and_sub_4: 980 case Builtin::BI__sync_fetch_and_sub_8: 981 case Builtin::BI__sync_fetch_and_sub_16: 982 case Builtin::BI__sync_fetch_and_or: 983 case Builtin::BI__sync_fetch_and_or_1: 984 case Builtin::BI__sync_fetch_and_or_2: 985 case Builtin::BI__sync_fetch_and_or_4: 986 case Builtin::BI__sync_fetch_and_or_8: 987 case Builtin::BI__sync_fetch_and_or_16: 988 case Builtin::BI__sync_fetch_and_and: 989 case Builtin::BI__sync_fetch_and_and_1: 990 case Builtin::BI__sync_fetch_and_and_2: 991 case Builtin::BI__sync_fetch_and_and_4: 992 case Builtin::BI__sync_fetch_and_and_8: 993 case Builtin::BI__sync_fetch_and_and_16: 994 case Builtin::BI__sync_fetch_and_xor: 995 case Builtin::BI__sync_fetch_and_xor_1: 996 case Builtin::BI__sync_fetch_and_xor_2: 997 case Builtin::BI__sync_fetch_and_xor_4: 998 case Builtin::BI__sync_fetch_and_xor_8: 999 case Builtin::BI__sync_fetch_and_xor_16: 1000 case Builtin::BI__sync_fetch_and_nand: 1001 case Builtin::BI__sync_fetch_and_nand_1: 1002 case Builtin::BI__sync_fetch_and_nand_2: 1003 case Builtin::BI__sync_fetch_and_nand_4: 1004 case Builtin::BI__sync_fetch_and_nand_8: 1005 case Builtin::BI__sync_fetch_and_nand_16: 1006 case Builtin::BI__sync_add_and_fetch: 1007 case Builtin::BI__sync_add_and_fetch_1: 1008 case Builtin::BI__sync_add_and_fetch_2: 1009 case Builtin::BI__sync_add_and_fetch_4: 1010 case Builtin::BI__sync_add_and_fetch_8: 1011 case Builtin::BI__sync_add_and_fetch_16: 1012 case Builtin::BI__sync_sub_and_fetch: 1013 case Builtin::BI__sync_sub_and_fetch_1: 1014 case Builtin::BI__sync_sub_and_fetch_2: 1015 case Builtin::BI__sync_sub_and_fetch_4: 1016 case Builtin::BI__sync_sub_and_fetch_8: 1017 case Builtin::BI__sync_sub_and_fetch_16: 1018 case Builtin::BI__sync_and_and_fetch: 1019 case Builtin::BI__sync_and_and_fetch_1: 1020 case Builtin::BI__sync_and_and_fetch_2: 1021 case Builtin::BI__sync_and_and_fetch_4: 1022 case Builtin::BI__sync_and_and_fetch_8: 1023 case Builtin::BI__sync_and_and_fetch_16: 1024 case Builtin::BI__sync_or_and_fetch: 1025 case Builtin::BI__sync_or_and_fetch_1: 1026 case Builtin::BI__sync_or_and_fetch_2: 1027 case Builtin::BI__sync_or_and_fetch_4: 1028 case Builtin::BI__sync_or_and_fetch_8: 1029 case Builtin::BI__sync_or_and_fetch_16: 1030 case Builtin::BI__sync_xor_and_fetch: 1031 case Builtin::BI__sync_xor_and_fetch_1: 1032 case Builtin::BI__sync_xor_and_fetch_2: 1033 case Builtin::BI__sync_xor_and_fetch_4: 1034 case Builtin::BI__sync_xor_and_fetch_8: 1035 case Builtin::BI__sync_xor_and_fetch_16: 1036 case Builtin::BI__sync_nand_and_fetch: 1037 case Builtin::BI__sync_nand_and_fetch_1: 1038 case Builtin::BI__sync_nand_and_fetch_2: 1039 case Builtin::BI__sync_nand_and_fetch_4: 1040 case Builtin::BI__sync_nand_and_fetch_8: 1041 case Builtin::BI__sync_nand_and_fetch_16: 1042 case Builtin::BI__sync_val_compare_and_swap: 1043 case Builtin::BI__sync_val_compare_and_swap_1: 1044 case Builtin::BI__sync_val_compare_and_swap_2: 1045 case Builtin::BI__sync_val_compare_and_swap_4: 1046 case Builtin::BI__sync_val_compare_and_swap_8: 1047 case Builtin::BI__sync_val_compare_and_swap_16: 1048 case Builtin::BI__sync_bool_compare_and_swap: 1049 case Builtin::BI__sync_bool_compare_and_swap_1: 1050 case Builtin::BI__sync_bool_compare_and_swap_2: 1051 case Builtin::BI__sync_bool_compare_and_swap_4: 1052 case Builtin::BI__sync_bool_compare_and_swap_8: 1053 case Builtin::BI__sync_bool_compare_and_swap_16: 1054 case Builtin::BI__sync_lock_test_and_set: 1055 case Builtin::BI__sync_lock_test_and_set_1: 1056 case Builtin::BI__sync_lock_test_and_set_2: 1057 case Builtin::BI__sync_lock_test_and_set_4: 1058 case Builtin::BI__sync_lock_test_and_set_8: 1059 case Builtin::BI__sync_lock_test_and_set_16: 1060 case Builtin::BI__sync_lock_release: 1061 case Builtin::BI__sync_lock_release_1: 1062 case Builtin::BI__sync_lock_release_2: 1063 case Builtin::BI__sync_lock_release_4: 1064 case Builtin::BI__sync_lock_release_8: 1065 case Builtin::BI__sync_lock_release_16: 1066 case Builtin::BI__sync_swap: 1067 case Builtin::BI__sync_swap_1: 1068 case Builtin::BI__sync_swap_2: 1069 case Builtin::BI__sync_swap_4: 1070 case Builtin::BI__sync_swap_8: 1071 case Builtin::BI__sync_swap_16: 1072 return SemaBuiltinAtomicOverloaded(TheCallResult); 1073 case Builtin::BI__builtin_nontemporal_load: 1074 case Builtin::BI__builtin_nontemporal_store: 1075 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1076 #define BUILTIN(ID, TYPE, ATTRS) 1077 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1078 case Builtin::BI##ID: \ 1079 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1080 #include "clang/Basic/Builtins.def" 1081 case Builtin::BI__annotation: 1082 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1083 return ExprError(); 1084 break; 1085 case Builtin::BI__builtin_annotation: 1086 if (SemaBuiltinAnnotation(*this, TheCall)) 1087 return ExprError(); 1088 break; 1089 case Builtin::BI__builtin_addressof: 1090 if (SemaBuiltinAddressof(*this, TheCall)) 1091 return ExprError(); 1092 break; 1093 case Builtin::BI__builtin_add_overflow: 1094 case Builtin::BI__builtin_sub_overflow: 1095 case Builtin::BI__builtin_mul_overflow: 1096 if (SemaBuiltinOverflow(*this, TheCall)) 1097 return ExprError(); 1098 break; 1099 case Builtin::BI__builtin_operator_new: 1100 case Builtin::BI__builtin_operator_delete: 1101 if (!getLangOpts().CPlusPlus) { 1102 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 1103 << (BuiltinID == Builtin::BI__builtin_operator_new 1104 ? "__builtin_operator_new" 1105 : "__builtin_operator_delete") 1106 << "C++"; 1107 return ExprError(); 1108 } 1109 // CodeGen assumes it can find the global new and delete to call, 1110 // so ensure that they are declared. 1111 DeclareGlobalNewDelete(); 1112 break; 1113 1114 // check secure string manipulation functions where overflows 1115 // are detectable at compile time 1116 case Builtin::BI__builtin___memcpy_chk: 1117 case Builtin::BI__builtin___memmove_chk: 1118 case Builtin::BI__builtin___memset_chk: 1119 case Builtin::BI__builtin___strlcat_chk: 1120 case Builtin::BI__builtin___strlcpy_chk: 1121 case Builtin::BI__builtin___strncat_chk: 1122 case Builtin::BI__builtin___strncpy_chk: 1123 case Builtin::BI__builtin___stpncpy_chk: 1124 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1125 break; 1126 case Builtin::BI__builtin___memccpy_chk: 1127 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1128 break; 1129 case Builtin::BI__builtin___snprintf_chk: 1130 case Builtin::BI__builtin___vsnprintf_chk: 1131 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1132 break; 1133 case Builtin::BI__builtin_call_with_static_chain: 1134 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1135 return ExprError(); 1136 break; 1137 case Builtin::BI__exception_code: 1138 case Builtin::BI_exception_code: 1139 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1140 diag::err_seh___except_block)) 1141 return ExprError(); 1142 break; 1143 case Builtin::BI__exception_info: 1144 case Builtin::BI_exception_info: 1145 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1146 diag::err_seh___except_filter)) 1147 return ExprError(); 1148 break; 1149 case Builtin::BI__GetExceptionInfo: 1150 if (checkArgCount(*this, TheCall, 1)) 1151 return ExprError(); 1152 1153 if (CheckCXXThrowOperand( 1154 TheCall->getLocStart(), 1155 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1156 TheCall)) 1157 return ExprError(); 1158 1159 TheCall->setType(Context.VoidPtrTy); 1160 break; 1161 // OpenCL v2.0, s6.13.16 - Pipe functions 1162 case Builtin::BIread_pipe: 1163 case Builtin::BIwrite_pipe: 1164 // Since those two functions are declared with var args, we need a semantic 1165 // check for the argument. 1166 if (SemaBuiltinRWPipe(*this, TheCall)) 1167 return ExprError(); 1168 TheCall->setType(Context.IntTy); 1169 break; 1170 case Builtin::BIreserve_read_pipe: 1171 case Builtin::BIreserve_write_pipe: 1172 case Builtin::BIwork_group_reserve_read_pipe: 1173 case Builtin::BIwork_group_reserve_write_pipe: 1174 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1175 return ExprError(); 1176 break; 1177 case Builtin::BIsub_group_reserve_read_pipe: 1178 case Builtin::BIsub_group_reserve_write_pipe: 1179 if (checkOpenCLSubgroupExt(*this, TheCall) || 1180 SemaBuiltinReserveRWPipe(*this, TheCall)) 1181 return ExprError(); 1182 break; 1183 case Builtin::BIcommit_read_pipe: 1184 case Builtin::BIcommit_write_pipe: 1185 case Builtin::BIwork_group_commit_read_pipe: 1186 case Builtin::BIwork_group_commit_write_pipe: 1187 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1188 return ExprError(); 1189 break; 1190 case Builtin::BIsub_group_commit_read_pipe: 1191 case Builtin::BIsub_group_commit_write_pipe: 1192 if (checkOpenCLSubgroupExt(*this, TheCall) || 1193 SemaBuiltinCommitRWPipe(*this, TheCall)) 1194 return ExprError(); 1195 break; 1196 case Builtin::BIget_pipe_num_packets: 1197 case Builtin::BIget_pipe_max_packets: 1198 if (SemaBuiltinPipePackets(*this, TheCall)) 1199 return ExprError(); 1200 TheCall->setType(Context.UnsignedIntTy); 1201 break; 1202 case Builtin::BIto_global: 1203 case Builtin::BIto_local: 1204 case Builtin::BIto_private: 1205 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1206 return ExprError(); 1207 break; 1208 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1209 case Builtin::BIenqueue_kernel: 1210 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1211 return ExprError(); 1212 break; 1213 case Builtin::BIget_kernel_work_group_size: 1214 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1215 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1216 return ExprError(); 1217 break; 1218 break; 1219 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1220 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1221 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1222 return ExprError(); 1223 break; 1224 case Builtin::BI__builtin_os_log_format: 1225 case Builtin::BI__builtin_os_log_format_buffer_size: 1226 if (SemaBuiltinOSLogFormat(TheCall)) 1227 return ExprError(); 1228 break; 1229 } 1230 1231 // Since the target specific builtins for each arch overlap, only check those 1232 // of the arch we are compiling for. 1233 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1234 switch (Context.getTargetInfo().getTriple().getArch()) { 1235 case llvm::Triple::arm: 1236 case llvm::Triple::armeb: 1237 case llvm::Triple::thumb: 1238 case llvm::Triple::thumbeb: 1239 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1240 return ExprError(); 1241 break; 1242 case llvm::Triple::aarch64: 1243 case llvm::Triple::aarch64_be: 1244 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1245 return ExprError(); 1246 break; 1247 case llvm::Triple::mips: 1248 case llvm::Triple::mipsel: 1249 case llvm::Triple::mips64: 1250 case llvm::Triple::mips64el: 1251 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1252 return ExprError(); 1253 break; 1254 case llvm::Triple::systemz: 1255 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1256 return ExprError(); 1257 break; 1258 case llvm::Triple::x86: 1259 case llvm::Triple::x86_64: 1260 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1261 return ExprError(); 1262 break; 1263 case llvm::Triple::ppc: 1264 case llvm::Triple::ppc64: 1265 case llvm::Triple::ppc64le: 1266 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1267 return ExprError(); 1268 break; 1269 default: 1270 break; 1271 } 1272 } 1273 1274 return TheCallResult; 1275 } 1276 1277 // Get the valid immediate range for the specified NEON type code. 1278 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1279 NeonTypeFlags Type(t); 1280 int IsQuad = ForceQuad ? true : Type.isQuad(); 1281 switch (Type.getEltType()) { 1282 case NeonTypeFlags::Int8: 1283 case NeonTypeFlags::Poly8: 1284 return shift ? 7 : (8 << IsQuad) - 1; 1285 case NeonTypeFlags::Int16: 1286 case NeonTypeFlags::Poly16: 1287 return shift ? 15 : (4 << IsQuad) - 1; 1288 case NeonTypeFlags::Int32: 1289 return shift ? 31 : (2 << IsQuad) - 1; 1290 case NeonTypeFlags::Int64: 1291 case NeonTypeFlags::Poly64: 1292 return shift ? 63 : (1 << IsQuad) - 1; 1293 case NeonTypeFlags::Poly128: 1294 return shift ? 127 : (1 << IsQuad) - 1; 1295 case NeonTypeFlags::Float16: 1296 assert(!shift && "cannot shift float types!"); 1297 return (4 << IsQuad) - 1; 1298 case NeonTypeFlags::Float32: 1299 assert(!shift && "cannot shift float types!"); 1300 return (2 << IsQuad) - 1; 1301 case NeonTypeFlags::Float64: 1302 assert(!shift && "cannot shift float types!"); 1303 return (1 << IsQuad) - 1; 1304 } 1305 llvm_unreachable("Invalid NeonTypeFlag!"); 1306 } 1307 1308 /// getNeonEltType - Return the QualType corresponding to the elements of 1309 /// the vector type specified by the NeonTypeFlags. This is used to check 1310 /// the pointer arguments for Neon load/store intrinsics. 1311 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1312 bool IsPolyUnsigned, bool IsInt64Long) { 1313 switch (Flags.getEltType()) { 1314 case NeonTypeFlags::Int8: 1315 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1316 case NeonTypeFlags::Int16: 1317 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1318 case NeonTypeFlags::Int32: 1319 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1320 case NeonTypeFlags::Int64: 1321 if (IsInt64Long) 1322 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1323 else 1324 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1325 : Context.LongLongTy; 1326 case NeonTypeFlags::Poly8: 1327 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1328 case NeonTypeFlags::Poly16: 1329 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1330 case NeonTypeFlags::Poly64: 1331 if (IsInt64Long) 1332 return Context.UnsignedLongTy; 1333 else 1334 return Context.UnsignedLongLongTy; 1335 case NeonTypeFlags::Poly128: 1336 break; 1337 case NeonTypeFlags::Float16: 1338 return Context.HalfTy; 1339 case NeonTypeFlags::Float32: 1340 return Context.FloatTy; 1341 case NeonTypeFlags::Float64: 1342 return Context.DoubleTy; 1343 } 1344 llvm_unreachable("Invalid NeonTypeFlag!"); 1345 } 1346 1347 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1348 llvm::APSInt Result; 1349 uint64_t mask = 0; 1350 unsigned TV = 0; 1351 int PtrArgNum = -1; 1352 bool HasConstPtr = false; 1353 switch (BuiltinID) { 1354 #define GET_NEON_OVERLOAD_CHECK 1355 #include "clang/Basic/arm_neon.inc" 1356 #undef GET_NEON_OVERLOAD_CHECK 1357 } 1358 1359 // For NEON intrinsics which are overloaded on vector element type, validate 1360 // the immediate which specifies which variant to emit. 1361 unsigned ImmArg = TheCall->getNumArgs()-1; 1362 if (mask) { 1363 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1364 return true; 1365 1366 TV = Result.getLimitedValue(64); 1367 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1368 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1369 << TheCall->getArg(ImmArg)->getSourceRange(); 1370 } 1371 1372 if (PtrArgNum >= 0) { 1373 // Check that pointer arguments have the specified type. 1374 Expr *Arg = TheCall->getArg(PtrArgNum); 1375 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1376 Arg = ICE->getSubExpr(); 1377 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1378 QualType RHSTy = RHS.get()->getType(); 1379 1380 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1381 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1382 Arch == llvm::Triple::aarch64_be; 1383 bool IsInt64Long = 1384 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1385 QualType EltTy = 1386 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1387 if (HasConstPtr) 1388 EltTy = EltTy.withConst(); 1389 QualType LHSTy = Context.getPointerType(EltTy); 1390 AssignConvertType ConvTy; 1391 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1392 if (RHS.isInvalid()) 1393 return true; 1394 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1395 RHS.get(), AA_Assigning)) 1396 return true; 1397 } 1398 1399 // For NEON intrinsics which take an immediate value as part of the 1400 // instruction, range check them here. 1401 unsigned i = 0, l = 0, u = 0; 1402 switch (BuiltinID) { 1403 default: 1404 return false; 1405 #define GET_NEON_IMMEDIATE_CHECK 1406 #include "clang/Basic/arm_neon.inc" 1407 #undef GET_NEON_IMMEDIATE_CHECK 1408 } 1409 1410 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1411 } 1412 1413 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1414 unsigned MaxWidth) { 1415 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1416 BuiltinID == ARM::BI__builtin_arm_ldaex || 1417 BuiltinID == ARM::BI__builtin_arm_strex || 1418 BuiltinID == ARM::BI__builtin_arm_stlex || 1419 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1420 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1421 BuiltinID == AArch64::BI__builtin_arm_strex || 1422 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1423 "unexpected ARM builtin"); 1424 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1425 BuiltinID == ARM::BI__builtin_arm_ldaex || 1426 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1427 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1428 1429 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1430 1431 // Ensure that we have the proper number of arguments. 1432 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1433 return true; 1434 1435 // Inspect the pointer argument of the atomic builtin. This should always be 1436 // a pointer type, whose element is an integral scalar or pointer type. 1437 // Because it is a pointer type, we don't have to worry about any implicit 1438 // casts here. 1439 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1440 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1441 if (PointerArgRes.isInvalid()) 1442 return true; 1443 PointerArg = PointerArgRes.get(); 1444 1445 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1446 if (!pointerType) { 1447 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1448 << PointerArg->getType() << PointerArg->getSourceRange(); 1449 return true; 1450 } 1451 1452 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1453 // task is to insert the appropriate casts into the AST. First work out just 1454 // what the appropriate type is. 1455 QualType ValType = pointerType->getPointeeType(); 1456 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1457 if (IsLdrex) 1458 AddrType.addConst(); 1459 1460 // Issue a warning if the cast is dodgy. 1461 CastKind CastNeeded = CK_NoOp; 1462 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1463 CastNeeded = CK_BitCast; 1464 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1465 << PointerArg->getType() 1466 << Context.getPointerType(AddrType) 1467 << AA_Passing << PointerArg->getSourceRange(); 1468 } 1469 1470 // Finally, do the cast and replace the argument with the corrected version. 1471 AddrType = Context.getPointerType(AddrType); 1472 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1473 if (PointerArgRes.isInvalid()) 1474 return true; 1475 PointerArg = PointerArgRes.get(); 1476 1477 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1478 1479 // In general, we allow ints, floats and pointers to be loaded and stored. 1480 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1481 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1482 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1483 << PointerArg->getType() << PointerArg->getSourceRange(); 1484 return true; 1485 } 1486 1487 // But ARM doesn't have instructions to deal with 128-bit versions. 1488 if (Context.getTypeSize(ValType) > MaxWidth) { 1489 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1490 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1491 << PointerArg->getType() << PointerArg->getSourceRange(); 1492 return true; 1493 } 1494 1495 switch (ValType.getObjCLifetime()) { 1496 case Qualifiers::OCL_None: 1497 case Qualifiers::OCL_ExplicitNone: 1498 // okay 1499 break; 1500 1501 case Qualifiers::OCL_Weak: 1502 case Qualifiers::OCL_Strong: 1503 case Qualifiers::OCL_Autoreleasing: 1504 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1505 << ValType << PointerArg->getSourceRange(); 1506 return true; 1507 } 1508 1509 if (IsLdrex) { 1510 TheCall->setType(ValType); 1511 return false; 1512 } 1513 1514 // Initialize the argument to be stored. 1515 ExprResult ValArg = TheCall->getArg(0); 1516 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1517 Context, ValType, /*consume*/ false); 1518 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1519 if (ValArg.isInvalid()) 1520 return true; 1521 TheCall->setArg(0, ValArg.get()); 1522 1523 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1524 // but the custom checker bypasses all default analysis. 1525 TheCall->setType(Context.IntTy); 1526 return false; 1527 } 1528 1529 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1530 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1531 BuiltinID == ARM::BI__builtin_arm_ldaex || 1532 BuiltinID == ARM::BI__builtin_arm_strex || 1533 BuiltinID == ARM::BI__builtin_arm_stlex) { 1534 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1535 } 1536 1537 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1538 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1539 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1540 } 1541 1542 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1543 BuiltinID == ARM::BI__builtin_arm_wsr64) 1544 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1545 1546 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1547 BuiltinID == ARM::BI__builtin_arm_rsrp || 1548 BuiltinID == ARM::BI__builtin_arm_wsr || 1549 BuiltinID == ARM::BI__builtin_arm_wsrp) 1550 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1551 1552 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1553 return true; 1554 1555 // For intrinsics which take an immediate value as part of the instruction, 1556 // range check them here. 1557 // FIXME: VFP Intrinsics should error if VFP not present. 1558 switch (BuiltinID) { 1559 default: return false; 1560 case ARM::BI__builtin_arm_ssat: 1561 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1562 case ARM::BI__builtin_arm_usat: 1563 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1564 case ARM::BI__builtin_arm_ssat16: 1565 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1566 case ARM::BI__builtin_arm_usat16: 1567 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1568 case ARM::BI__builtin_arm_vcvtr_f: 1569 case ARM::BI__builtin_arm_vcvtr_d: 1570 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1571 case ARM::BI__builtin_arm_dmb: 1572 case ARM::BI__builtin_arm_dsb: 1573 case ARM::BI__builtin_arm_isb: 1574 case ARM::BI__builtin_arm_dbg: 1575 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1576 } 1577 } 1578 1579 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1580 CallExpr *TheCall) { 1581 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1582 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1583 BuiltinID == AArch64::BI__builtin_arm_strex || 1584 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1585 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1586 } 1587 1588 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1589 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1590 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1591 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1592 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1593 } 1594 1595 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1596 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1597 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1598 1599 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1600 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1601 BuiltinID == AArch64::BI__builtin_arm_wsr || 1602 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1603 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1604 1605 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1606 return true; 1607 1608 // For intrinsics which take an immediate value as part of the instruction, 1609 // range check them here. 1610 unsigned i = 0, l = 0, u = 0; 1611 switch (BuiltinID) { 1612 default: return false; 1613 case AArch64::BI__builtin_arm_dmb: 1614 case AArch64::BI__builtin_arm_dsb: 1615 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1616 } 1617 1618 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1619 } 1620 1621 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1622 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1623 // ordering for DSP is unspecified. MSA is ordered by the data format used 1624 // by the underlying instruction i.e., df/m, df/n and then by size. 1625 // 1626 // FIXME: The size tests here should instead be tablegen'd along with the 1627 // definitions from include/clang/Basic/BuiltinsMips.def. 1628 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1629 // be too. 1630 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1631 unsigned i = 0, l = 0, u = 0, m = 0; 1632 switch (BuiltinID) { 1633 default: return false; 1634 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1635 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1636 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1637 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1638 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1639 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1640 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1641 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1642 // df/m field. 1643 // These intrinsics take an unsigned 3 bit immediate. 1644 case Mips::BI__builtin_msa_bclri_b: 1645 case Mips::BI__builtin_msa_bnegi_b: 1646 case Mips::BI__builtin_msa_bseti_b: 1647 case Mips::BI__builtin_msa_sat_s_b: 1648 case Mips::BI__builtin_msa_sat_u_b: 1649 case Mips::BI__builtin_msa_slli_b: 1650 case Mips::BI__builtin_msa_srai_b: 1651 case Mips::BI__builtin_msa_srari_b: 1652 case Mips::BI__builtin_msa_srli_b: 1653 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1654 case Mips::BI__builtin_msa_binsli_b: 1655 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1656 // These intrinsics take an unsigned 4 bit immediate. 1657 case Mips::BI__builtin_msa_bclri_h: 1658 case Mips::BI__builtin_msa_bnegi_h: 1659 case Mips::BI__builtin_msa_bseti_h: 1660 case Mips::BI__builtin_msa_sat_s_h: 1661 case Mips::BI__builtin_msa_sat_u_h: 1662 case Mips::BI__builtin_msa_slli_h: 1663 case Mips::BI__builtin_msa_srai_h: 1664 case Mips::BI__builtin_msa_srari_h: 1665 case Mips::BI__builtin_msa_srli_h: 1666 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1667 case Mips::BI__builtin_msa_binsli_h: 1668 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1669 // These intrinsics take an unsigned 5 bit immedate. 1670 // The first block of intrinsics actually have an unsigned 5 bit field, 1671 // not a df/n field. 1672 case Mips::BI__builtin_msa_clei_u_b: 1673 case Mips::BI__builtin_msa_clei_u_h: 1674 case Mips::BI__builtin_msa_clei_u_w: 1675 case Mips::BI__builtin_msa_clei_u_d: 1676 case Mips::BI__builtin_msa_clti_u_b: 1677 case Mips::BI__builtin_msa_clti_u_h: 1678 case Mips::BI__builtin_msa_clti_u_w: 1679 case Mips::BI__builtin_msa_clti_u_d: 1680 case Mips::BI__builtin_msa_maxi_u_b: 1681 case Mips::BI__builtin_msa_maxi_u_h: 1682 case Mips::BI__builtin_msa_maxi_u_w: 1683 case Mips::BI__builtin_msa_maxi_u_d: 1684 case Mips::BI__builtin_msa_mini_u_b: 1685 case Mips::BI__builtin_msa_mini_u_h: 1686 case Mips::BI__builtin_msa_mini_u_w: 1687 case Mips::BI__builtin_msa_mini_u_d: 1688 case Mips::BI__builtin_msa_addvi_b: 1689 case Mips::BI__builtin_msa_addvi_h: 1690 case Mips::BI__builtin_msa_addvi_w: 1691 case Mips::BI__builtin_msa_addvi_d: 1692 case Mips::BI__builtin_msa_bclri_w: 1693 case Mips::BI__builtin_msa_bnegi_w: 1694 case Mips::BI__builtin_msa_bseti_w: 1695 case Mips::BI__builtin_msa_sat_s_w: 1696 case Mips::BI__builtin_msa_sat_u_w: 1697 case Mips::BI__builtin_msa_slli_w: 1698 case Mips::BI__builtin_msa_srai_w: 1699 case Mips::BI__builtin_msa_srari_w: 1700 case Mips::BI__builtin_msa_srli_w: 1701 case Mips::BI__builtin_msa_srlri_w: 1702 case Mips::BI__builtin_msa_subvi_b: 1703 case Mips::BI__builtin_msa_subvi_h: 1704 case Mips::BI__builtin_msa_subvi_w: 1705 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1706 case Mips::BI__builtin_msa_binsli_w: 1707 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1708 // These intrinsics take an unsigned 6 bit immediate. 1709 case Mips::BI__builtin_msa_bclri_d: 1710 case Mips::BI__builtin_msa_bnegi_d: 1711 case Mips::BI__builtin_msa_bseti_d: 1712 case Mips::BI__builtin_msa_sat_s_d: 1713 case Mips::BI__builtin_msa_sat_u_d: 1714 case Mips::BI__builtin_msa_slli_d: 1715 case Mips::BI__builtin_msa_srai_d: 1716 case Mips::BI__builtin_msa_srari_d: 1717 case Mips::BI__builtin_msa_srli_d: 1718 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1719 case Mips::BI__builtin_msa_binsli_d: 1720 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1721 // These intrinsics take a signed 5 bit immediate. 1722 case Mips::BI__builtin_msa_ceqi_b: 1723 case Mips::BI__builtin_msa_ceqi_h: 1724 case Mips::BI__builtin_msa_ceqi_w: 1725 case Mips::BI__builtin_msa_ceqi_d: 1726 case Mips::BI__builtin_msa_clti_s_b: 1727 case Mips::BI__builtin_msa_clti_s_h: 1728 case Mips::BI__builtin_msa_clti_s_w: 1729 case Mips::BI__builtin_msa_clti_s_d: 1730 case Mips::BI__builtin_msa_clei_s_b: 1731 case Mips::BI__builtin_msa_clei_s_h: 1732 case Mips::BI__builtin_msa_clei_s_w: 1733 case Mips::BI__builtin_msa_clei_s_d: 1734 case Mips::BI__builtin_msa_maxi_s_b: 1735 case Mips::BI__builtin_msa_maxi_s_h: 1736 case Mips::BI__builtin_msa_maxi_s_w: 1737 case Mips::BI__builtin_msa_maxi_s_d: 1738 case Mips::BI__builtin_msa_mini_s_b: 1739 case Mips::BI__builtin_msa_mini_s_h: 1740 case Mips::BI__builtin_msa_mini_s_w: 1741 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1742 // These intrinsics take an unsigned 8 bit immediate. 1743 case Mips::BI__builtin_msa_andi_b: 1744 case Mips::BI__builtin_msa_nori_b: 1745 case Mips::BI__builtin_msa_ori_b: 1746 case Mips::BI__builtin_msa_shf_b: 1747 case Mips::BI__builtin_msa_shf_h: 1748 case Mips::BI__builtin_msa_shf_w: 1749 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1750 case Mips::BI__builtin_msa_bseli_b: 1751 case Mips::BI__builtin_msa_bmnzi_b: 1752 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1753 // df/n format 1754 // These intrinsics take an unsigned 4 bit immediate. 1755 case Mips::BI__builtin_msa_copy_s_b: 1756 case Mips::BI__builtin_msa_copy_u_b: 1757 case Mips::BI__builtin_msa_insve_b: 1758 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1759 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1760 // These intrinsics take an unsigned 3 bit immediate. 1761 case Mips::BI__builtin_msa_copy_s_h: 1762 case Mips::BI__builtin_msa_copy_u_h: 1763 case Mips::BI__builtin_msa_insve_h: 1764 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1765 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1766 // These intrinsics take an unsigned 2 bit immediate. 1767 case Mips::BI__builtin_msa_copy_s_w: 1768 case Mips::BI__builtin_msa_copy_u_w: 1769 case Mips::BI__builtin_msa_insve_w: 1770 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1771 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1772 // These intrinsics take an unsigned 1 bit immediate. 1773 case Mips::BI__builtin_msa_copy_s_d: 1774 case Mips::BI__builtin_msa_copy_u_d: 1775 case Mips::BI__builtin_msa_insve_d: 1776 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1777 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1778 // Memory offsets and immediate loads. 1779 // These intrinsics take a signed 10 bit immediate. 1780 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 1781 case Mips::BI__builtin_msa_ldi_h: 1782 case Mips::BI__builtin_msa_ldi_w: 1783 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1784 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1785 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1786 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1787 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1788 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1789 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1790 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1791 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1792 } 1793 1794 if (!m) 1795 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1796 1797 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1798 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1799 } 1800 1801 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1802 unsigned i = 0, l = 0, u = 0; 1803 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1804 BuiltinID == PPC::BI__builtin_divdeu || 1805 BuiltinID == PPC::BI__builtin_bpermd; 1806 bool IsTarget64Bit = Context.getTargetInfo() 1807 .getTypeWidth(Context 1808 .getTargetInfo() 1809 .getIntPtrType()) == 64; 1810 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1811 BuiltinID == PPC::BI__builtin_divweu || 1812 BuiltinID == PPC::BI__builtin_divde || 1813 BuiltinID == PPC::BI__builtin_divdeu; 1814 1815 if (Is64BitBltin && !IsTarget64Bit) 1816 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1817 << TheCall->getSourceRange(); 1818 1819 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1820 (BuiltinID == PPC::BI__builtin_bpermd && 1821 !Context.getTargetInfo().hasFeature("bpermd"))) 1822 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1823 << TheCall->getSourceRange(); 1824 1825 switch (BuiltinID) { 1826 default: return false; 1827 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1828 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1829 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1830 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1831 case PPC::BI__builtin_tbegin: 1832 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1833 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1834 case PPC::BI__builtin_tabortwc: 1835 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1836 case PPC::BI__builtin_tabortwci: 1837 case PPC::BI__builtin_tabortdci: 1838 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1839 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1840 case PPC::BI__builtin_vsx_xxpermdi: 1841 case PPC::BI__builtin_vsx_xxsldwi: 1842 return SemaBuiltinVSX(TheCall); 1843 } 1844 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1845 } 1846 1847 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1848 CallExpr *TheCall) { 1849 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1850 Expr *Arg = TheCall->getArg(0); 1851 llvm::APSInt AbortCode(32); 1852 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1853 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1854 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1855 << Arg->getSourceRange(); 1856 } 1857 1858 // For intrinsics which take an immediate value as part of the instruction, 1859 // range check them here. 1860 unsigned i = 0, l = 0, u = 0; 1861 switch (BuiltinID) { 1862 default: return false; 1863 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1864 case SystemZ::BI__builtin_s390_verimb: 1865 case SystemZ::BI__builtin_s390_verimh: 1866 case SystemZ::BI__builtin_s390_verimf: 1867 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1868 case SystemZ::BI__builtin_s390_vfaeb: 1869 case SystemZ::BI__builtin_s390_vfaeh: 1870 case SystemZ::BI__builtin_s390_vfaef: 1871 case SystemZ::BI__builtin_s390_vfaebs: 1872 case SystemZ::BI__builtin_s390_vfaehs: 1873 case SystemZ::BI__builtin_s390_vfaefs: 1874 case SystemZ::BI__builtin_s390_vfaezb: 1875 case SystemZ::BI__builtin_s390_vfaezh: 1876 case SystemZ::BI__builtin_s390_vfaezf: 1877 case SystemZ::BI__builtin_s390_vfaezbs: 1878 case SystemZ::BI__builtin_s390_vfaezhs: 1879 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1880 case SystemZ::BI__builtin_s390_vfisb: 1881 case SystemZ::BI__builtin_s390_vfidb: 1882 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1883 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1884 case SystemZ::BI__builtin_s390_vftcisb: 1885 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1886 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1887 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1888 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1889 case SystemZ::BI__builtin_s390_vstrcb: 1890 case SystemZ::BI__builtin_s390_vstrch: 1891 case SystemZ::BI__builtin_s390_vstrcf: 1892 case SystemZ::BI__builtin_s390_vstrczb: 1893 case SystemZ::BI__builtin_s390_vstrczh: 1894 case SystemZ::BI__builtin_s390_vstrczf: 1895 case SystemZ::BI__builtin_s390_vstrcbs: 1896 case SystemZ::BI__builtin_s390_vstrchs: 1897 case SystemZ::BI__builtin_s390_vstrcfs: 1898 case SystemZ::BI__builtin_s390_vstrczbs: 1899 case SystemZ::BI__builtin_s390_vstrczhs: 1900 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1901 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 1902 case SystemZ::BI__builtin_s390_vfminsb: 1903 case SystemZ::BI__builtin_s390_vfmaxsb: 1904 case SystemZ::BI__builtin_s390_vfmindb: 1905 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 1906 } 1907 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1908 } 1909 1910 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1911 /// This checks that the target supports __builtin_cpu_supports and 1912 /// that the string argument is constant and valid. 1913 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1914 Expr *Arg = TheCall->getArg(0); 1915 1916 // Check if the argument is a string literal. 1917 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1918 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1919 << Arg->getSourceRange(); 1920 1921 // Check the contents of the string. 1922 StringRef Feature = 1923 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1924 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1925 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1926 << Arg->getSourceRange(); 1927 return false; 1928 } 1929 1930 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 1931 /// This checks that the target supports __builtin_cpu_is and 1932 /// that the string argument is constant and valid. 1933 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 1934 Expr *Arg = TheCall->getArg(0); 1935 1936 // Check if the argument is a string literal. 1937 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1938 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1939 << Arg->getSourceRange(); 1940 1941 // Check the contents of the string. 1942 StringRef Feature = 1943 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1944 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 1945 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is) 1946 << Arg->getSourceRange(); 1947 return false; 1948 } 1949 1950 // Check if the rounding mode is legal. 1951 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1952 // Indicates if this instruction has rounding control or just SAE. 1953 bool HasRC = false; 1954 1955 unsigned ArgNum = 0; 1956 switch (BuiltinID) { 1957 default: 1958 return false; 1959 case X86::BI__builtin_ia32_vcvttsd2si32: 1960 case X86::BI__builtin_ia32_vcvttsd2si64: 1961 case X86::BI__builtin_ia32_vcvttsd2usi32: 1962 case X86::BI__builtin_ia32_vcvttsd2usi64: 1963 case X86::BI__builtin_ia32_vcvttss2si32: 1964 case X86::BI__builtin_ia32_vcvttss2si64: 1965 case X86::BI__builtin_ia32_vcvttss2usi32: 1966 case X86::BI__builtin_ia32_vcvttss2usi64: 1967 ArgNum = 1; 1968 break; 1969 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1970 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1971 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1972 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1973 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1974 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1975 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1976 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1977 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1978 case X86::BI__builtin_ia32_exp2pd_mask: 1979 case X86::BI__builtin_ia32_exp2ps_mask: 1980 case X86::BI__builtin_ia32_getexppd512_mask: 1981 case X86::BI__builtin_ia32_getexpps512_mask: 1982 case X86::BI__builtin_ia32_rcp28pd_mask: 1983 case X86::BI__builtin_ia32_rcp28ps_mask: 1984 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1985 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1986 case X86::BI__builtin_ia32_vcomisd: 1987 case X86::BI__builtin_ia32_vcomiss: 1988 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1989 ArgNum = 3; 1990 break; 1991 case X86::BI__builtin_ia32_cmppd512_mask: 1992 case X86::BI__builtin_ia32_cmpps512_mask: 1993 case X86::BI__builtin_ia32_cmpsd_mask: 1994 case X86::BI__builtin_ia32_cmpss_mask: 1995 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1996 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1997 case X86::BI__builtin_ia32_getexpss128_round_mask: 1998 case X86::BI__builtin_ia32_maxpd512_mask: 1999 case X86::BI__builtin_ia32_maxps512_mask: 2000 case X86::BI__builtin_ia32_maxsd_round_mask: 2001 case X86::BI__builtin_ia32_maxss_round_mask: 2002 case X86::BI__builtin_ia32_minpd512_mask: 2003 case X86::BI__builtin_ia32_minps512_mask: 2004 case X86::BI__builtin_ia32_minsd_round_mask: 2005 case X86::BI__builtin_ia32_minss_round_mask: 2006 case X86::BI__builtin_ia32_rcp28sd_round_mask: 2007 case X86::BI__builtin_ia32_rcp28ss_round_mask: 2008 case X86::BI__builtin_ia32_reducepd512_mask: 2009 case X86::BI__builtin_ia32_reduceps512_mask: 2010 case X86::BI__builtin_ia32_rndscalepd_mask: 2011 case X86::BI__builtin_ia32_rndscaleps_mask: 2012 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 2013 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 2014 ArgNum = 4; 2015 break; 2016 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2017 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2018 case X86::BI__builtin_ia32_fixupimmps512_mask: 2019 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2020 case X86::BI__builtin_ia32_fixupimmsd_mask: 2021 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2022 case X86::BI__builtin_ia32_fixupimmss_mask: 2023 case X86::BI__builtin_ia32_fixupimmss_maskz: 2024 case X86::BI__builtin_ia32_rangepd512_mask: 2025 case X86::BI__builtin_ia32_rangeps512_mask: 2026 case X86::BI__builtin_ia32_rangesd128_round_mask: 2027 case X86::BI__builtin_ia32_rangess128_round_mask: 2028 case X86::BI__builtin_ia32_reducesd_mask: 2029 case X86::BI__builtin_ia32_reducess_mask: 2030 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2031 case X86::BI__builtin_ia32_rndscaless_round_mask: 2032 ArgNum = 5; 2033 break; 2034 case X86::BI__builtin_ia32_vcvtsd2si64: 2035 case X86::BI__builtin_ia32_vcvtsd2si32: 2036 case X86::BI__builtin_ia32_vcvtsd2usi32: 2037 case X86::BI__builtin_ia32_vcvtsd2usi64: 2038 case X86::BI__builtin_ia32_vcvtss2si32: 2039 case X86::BI__builtin_ia32_vcvtss2si64: 2040 case X86::BI__builtin_ia32_vcvtss2usi32: 2041 case X86::BI__builtin_ia32_vcvtss2usi64: 2042 ArgNum = 1; 2043 HasRC = true; 2044 break; 2045 case X86::BI__builtin_ia32_cvtsi2sd64: 2046 case X86::BI__builtin_ia32_cvtsi2ss32: 2047 case X86::BI__builtin_ia32_cvtsi2ss64: 2048 case X86::BI__builtin_ia32_cvtusi2sd64: 2049 case X86::BI__builtin_ia32_cvtusi2ss32: 2050 case X86::BI__builtin_ia32_cvtusi2ss64: 2051 ArgNum = 2; 2052 HasRC = true; 2053 break; 2054 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 2055 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 2056 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 2057 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 2058 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 2059 case X86::BI__builtin_ia32_cvtps2qq512_mask: 2060 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 2061 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 2062 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 2063 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 2064 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 2065 case X86::BI__builtin_ia32_sqrtpd512_mask: 2066 case X86::BI__builtin_ia32_sqrtps512_mask: 2067 ArgNum = 3; 2068 HasRC = true; 2069 break; 2070 case X86::BI__builtin_ia32_addpd512_mask: 2071 case X86::BI__builtin_ia32_addps512_mask: 2072 case X86::BI__builtin_ia32_divpd512_mask: 2073 case X86::BI__builtin_ia32_divps512_mask: 2074 case X86::BI__builtin_ia32_mulpd512_mask: 2075 case X86::BI__builtin_ia32_mulps512_mask: 2076 case X86::BI__builtin_ia32_subpd512_mask: 2077 case X86::BI__builtin_ia32_subps512_mask: 2078 case X86::BI__builtin_ia32_addss_round_mask: 2079 case X86::BI__builtin_ia32_addsd_round_mask: 2080 case X86::BI__builtin_ia32_divss_round_mask: 2081 case X86::BI__builtin_ia32_divsd_round_mask: 2082 case X86::BI__builtin_ia32_mulss_round_mask: 2083 case X86::BI__builtin_ia32_mulsd_round_mask: 2084 case X86::BI__builtin_ia32_subss_round_mask: 2085 case X86::BI__builtin_ia32_subsd_round_mask: 2086 case X86::BI__builtin_ia32_scalefpd512_mask: 2087 case X86::BI__builtin_ia32_scalefps512_mask: 2088 case X86::BI__builtin_ia32_scalefsd_round_mask: 2089 case X86::BI__builtin_ia32_scalefss_round_mask: 2090 case X86::BI__builtin_ia32_getmantpd512_mask: 2091 case X86::BI__builtin_ia32_getmantps512_mask: 2092 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 2093 case X86::BI__builtin_ia32_sqrtsd_round_mask: 2094 case X86::BI__builtin_ia32_sqrtss_round_mask: 2095 case X86::BI__builtin_ia32_vfmaddpd512_mask: 2096 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 2097 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 2098 case X86::BI__builtin_ia32_vfmaddps512_mask: 2099 case X86::BI__builtin_ia32_vfmaddps512_mask3: 2100 case X86::BI__builtin_ia32_vfmaddps512_maskz: 2101 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 2102 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 2103 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 2104 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 2105 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2106 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2107 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2108 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2109 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2110 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2111 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 2112 case X86::BI__builtin_ia32_vfnmaddps512_mask: 2113 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 2114 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 2115 case X86::BI__builtin_ia32_vfnmsubps512_mask: 2116 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 2117 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2118 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2119 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2120 case X86::BI__builtin_ia32_vfmaddss3_mask: 2121 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2122 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2123 ArgNum = 4; 2124 HasRC = true; 2125 break; 2126 case X86::BI__builtin_ia32_getmantsd_round_mask: 2127 case X86::BI__builtin_ia32_getmantss_round_mask: 2128 ArgNum = 5; 2129 HasRC = true; 2130 break; 2131 } 2132 2133 llvm::APSInt Result; 2134 2135 // We can't check the value of a dependent argument. 2136 Expr *Arg = TheCall->getArg(ArgNum); 2137 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2138 return false; 2139 2140 // Check constant-ness first. 2141 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2142 return true; 2143 2144 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2145 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2146 // combined with ROUND_NO_EXC. 2147 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2148 Result == 8/*ROUND_NO_EXC*/ || 2149 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2150 return false; 2151 2152 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2153 << Arg->getSourceRange(); 2154 } 2155 2156 // Check if the gather/scatter scale is legal. 2157 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2158 CallExpr *TheCall) { 2159 unsigned ArgNum = 0; 2160 switch (BuiltinID) { 2161 default: 2162 return false; 2163 case X86::BI__builtin_ia32_gatherpfdpd: 2164 case X86::BI__builtin_ia32_gatherpfdps: 2165 case X86::BI__builtin_ia32_gatherpfqpd: 2166 case X86::BI__builtin_ia32_gatherpfqps: 2167 case X86::BI__builtin_ia32_scatterpfdpd: 2168 case X86::BI__builtin_ia32_scatterpfdps: 2169 case X86::BI__builtin_ia32_scatterpfqpd: 2170 case X86::BI__builtin_ia32_scatterpfqps: 2171 ArgNum = 3; 2172 break; 2173 case X86::BI__builtin_ia32_gatherd_pd: 2174 case X86::BI__builtin_ia32_gatherd_pd256: 2175 case X86::BI__builtin_ia32_gatherq_pd: 2176 case X86::BI__builtin_ia32_gatherq_pd256: 2177 case X86::BI__builtin_ia32_gatherd_ps: 2178 case X86::BI__builtin_ia32_gatherd_ps256: 2179 case X86::BI__builtin_ia32_gatherq_ps: 2180 case X86::BI__builtin_ia32_gatherq_ps256: 2181 case X86::BI__builtin_ia32_gatherd_q: 2182 case X86::BI__builtin_ia32_gatherd_q256: 2183 case X86::BI__builtin_ia32_gatherq_q: 2184 case X86::BI__builtin_ia32_gatherq_q256: 2185 case X86::BI__builtin_ia32_gatherd_d: 2186 case X86::BI__builtin_ia32_gatherd_d256: 2187 case X86::BI__builtin_ia32_gatherq_d: 2188 case X86::BI__builtin_ia32_gatherq_d256: 2189 case X86::BI__builtin_ia32_gather3div2df: 2190 case X86::BI__builtin_ia32_gather3div2di: 2191 case X86::BI__builtin_ia32_gather3div4df: 2192 case X86::BI__builtin_ia32_gather3div4di: 2193 case X86::BI__builtin_ia32_gather3div4sf: 2194 case X86::BI__builtin_ia32_gather3div4si: 2195 case X86::BI__builtin_ia32_gather3div8sf: 2196 case X86::BI__builtin_ia32_gather3div8si: 2197 case X86::BI__builtin_ia32_gather3siv2df: 2198 case X86::BI__builtin_ia32_gather3siv2di: 2199 case X86::BI__builtin_ia32_gather3siv4df: 2200 case X86::BI__builtin_ia32_gather3siv4di: 2201 case X86::BI__builtin_ia32_gather3siv4sf: 2202 case X86::BI__builtin_ia32_gather3siv4si: 2203 case X86::BI__builtin_ia32_gather3siv8sf: 2204 case X86::BI__builtin_ia32_gather3siv8si: 2205 case X86::BI__builtin_ia32_gathersiv8df: 2206 case X86::BI__builtin_ia32_gathersiv16sf: 2207 case X86::BI__builtin_ia32_gatherdiv8df: 2208 case X86::BI__builtin_ia32_gatherdiv16sf: 2209 case X86::BI__builtin_ia32_gathersiv8di: 2210 case X86::BI__builtin_ia32_gathersiv16si: 2211 case X86::BI__builtin_ia32_gatherdiv8di: 2212 case X86::BI__builtin_ia32_gatherdiv16si: 2213 case X86::BI__builtin_ia32_scatterdiv2df: 2214 case X86::BI__builtin_ia32_scatterdiv2di: 2215 case X86::BI__builtin_ia32_scatterdiv4df: 2216 case X86::BI__builtin_ia32_scatterdiv4di: 2217 case X86::BI__builtin_ia32_scatterdiv4sf: 2218 case X86::BI__builtin_ia32_scatterdiv4si: 2219 case X86::BI__builtin_ia32_scatterdiv8sf: 2220 case X86::BI__builtin_ia32_scatterdiv8si: 2221 case X86::BI__builtin_ia32_scattersiv2df: 2222 case X86::BI__builtin_ia32_scattersiv2di: 2223 case X86::BI__builtin_ia32_scattersiv4df: 2224 case X86::BI__builtin_ia32_scattersiv4di: 2225 case X86::BI__builtin_ia32_scattersiv4sf: 2226 case X86::BI__builtin_ia32_scattersiv4si: 2227 case X86::BI__builtin_ia32_scattersiv8sf: 2228 case X86::BI__builtin_ia32_scattersiv8si: 2229 case X86::BI__builtin_ia32_scattersiv8df: 2230 case X86::BI__builtin_ia32_scattersiv16sf: 2231 case X86::BI__builtin_ia32_scatterdiv8df: 2232 case X86::BI__builtin_ia32_scatterdiv16sf: 2233 case X86::BI__builtin_ia32_scattersiv8di: 2234 case X86::BI__builtin_ia32_scattersiv16si: 2235 case X86::BI__builtin_ia32_scatterdiv8di: 2236 case X86::BI__builtin_ia32_scatterdiv16si: 2237 ArgNum = 4; 2238 break; 2239 } 2240 2241 llvm::APSInt Result; 2242 2243 // We can't check the value of a dependent argument. 2244 Expr *Arg = TheCall->getArg(ArgNum); 2245 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2246 return false; 2247 2248 // Check constant-ness first. 2249 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2250 return true; 2251 2252 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2253 return false; 2254 2255 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2256 << Arg->getSourceRange(); 2257 } 2258 2259 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2260 if (BuiltinID == X86::BI__builtin_cpu_supports) 2261 return SemaBuiltinCpuSupports(*this, TheCall); 2262 2263 if (BuiltinID == X86::BI__builtin_cpu_is) 2264 return SemaBuiltinCpuIs(*this, TheCall); 2265 2266 // If the intrinsic has rounding or SAE make sure its valid. 2267 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2268 return true; 2269 2270 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2271 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2272 return true; 2273 2274 // For intrinsics which take an immediate value as part of the instruction, 2275 // range check them here. 2276 int i = 0, l = 0, u = 0; 2277 switch (BuiltinID) { 2278 default: 2279 return false; 2280 case X86::BI_mm_prefetch: 2281 i = 1; l = 0; u = 7; 2282 break; 2283 case X86::BI__builtin_ia32_sha1rnds4: 2284 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2285 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2286 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2287 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2288 i = 2; l = 0; u = 3; 2289 break; 2290 case X86::BI__builtin_ia32_vpermil2pd: 2291 case X86::BI__builtin_ia32_vpermil2pd256: 2292 case X86::BI__builtin_ia32_vpermil2ps: 2293 case X86::BI__builtin_ia32_vpermil2ps256: 2294 i = 3; l = 0; u = 3; 2295 break; 2296 case X86::BI__builtin_ia32_cmpb128_mask: 2297 case X86::BI__builtin_ia32_cmpw128_mask: 2298 case X86::BI__builtin_ia32_cmpd128_mask: 2299 case X86::BI__builtin_ia32_cmpq128_mask: 2300 case X86::BI__builtin_ia32_cmpb256_mask: 2301 case X86::BI__builtin_ia32_cmpw256_mask: 2302 case X86::BI__builtin_ia32_cmpd256_mask: 2303 case X86::BI__builtin_ia32_cmpq256_mask: 2304 case X86::BI__builtin_ia32_cmpb512_mask: 2305 case X86::BI__builtin_ia32_cmpw512_mask: 2306 case X86::BI__builtin_ia32_cmpd512_mask: 2307 case X86::BI__builtin_ia32_cmpq512_mask: 2308 case X86::BI__builtin_ia32_ucmpb128_mask: 2309 case X86::BI__builtin_ia32_ucmpw128_mask: 2310 case X86::BI__builtin_ia32_ucmpd128_mask: 2311 case X86::BI__builtin_ia32_ucmpq128_mask: 2312 case X86::BI__builtin_ia32_ucmpb256_mask: 2313 case X86::BI__builtin_ia32_ucmpw256_mask: 2314 case X86::BI__builtin_ia32_ucmpd256_mask: 2315 case X86::BI__builtin_ia32_ucmpq256_mask: 2316 case X86::BI__builtin_ia32_ucmpb512_mask: 2317 case X86::BI__builtin_ia32_ucmpw512_mask: 2318 case X86::BI__builtin_ia32_ucmpd512_mask: 2319 case X86::BI__builtin_ia32_ucmpq512_mask: 2320 case X86::BI__builtin_ia32_vpcomub: 2321 case X86::BI__builtin_ia32_vpcomuw: 2322 case X86::BI__builtin_ia32_vpcomud: 2323 case X86::BI__builtin_ia32_vpcomuq: 2324 case X86::BI__builtin_ia32_vpcomb: 2325 case X86::BI__builtin_ia32_vpcomw: 2326 case X86::BI__builtin_ia32_vpcomd: 2327 case X86::BI__builtin_ia32_vpcomq: 2328 i = 2; l = 0; u = 7; 2329 break; 2330 case X86::BI__builtin_ia32_roundps: 2331 case X86::BI__builtin_ia32_roundpd: 2332 case X86::BI__builtin_ia32_roundps256: 2333 case X86::BI__builtin_ia32_roundpd256: 2334 i = 1; l = 0; u = 15; 2335 break; 2336 case X86::BI__builtin_ia32_roundss: 2337 case X86::BI__builtin_ia32_roundsd: 2338 case X86::BI__builtin_ia32_rangepd128_mask: 2339 case X86::BI__builtin_ia32_rangepd256_mask: 2340 case X86::BI__builtin_ia32_rangepd512_mask: 2341 case X86::BI__builtin_ia32_rangeps128_mask: 2342 case X86::BI__builtin_ia32_rangeps256_mask: 2343 case X86::BI__builtin_ia32_rangeps512_mask: 2344 case X86::BI__builtin_ia32_getmantsd_round_mask: 2345 case X86::BI__builtin_ia32_getmantss_round_mask: 2346 i = 2; l = 0; u = 15; 2347 break; 2348 case X86::BI__builtin_ia32_cmpps: 2349 case X86::BI__builtin_ia32_cmpss: 2350 case X86::BI__builtin_ia32_cmppd: 2351 case X86::BI__builtin_ia32_cmpsd: 2352 case X86::BI__builtin_ia32_cmpps256: 2353 case X86::BI__builtin_ia32_cmppd256: 2354 case X86::BI__builtin_ia32_cmpps128_mask: 2355 case X86::BI__builtin_ia32_cmppd128_mask: 2356 case X86::BI__builtin_ia32_cmpps256_mask: 2357 case X86::BI__builtin_ia32_cmppd256_mask: 2358 case X86::BI__builtin_ia32_cmpps512_mask: 2359 case X86::BI__builtin_ia32_cmppd512_mask: 2360 case X86::BI__builtin_ia32_cmpsd_mask: 2361 case X86::BI__builtin_ia32_cmpss_mask: 2362 i = 2; l = 0; u = 31; 2363 break; 2364 case X86::BI__builtin_ia32_vcvtps2ph: 2365 case X86::BI__builtin_ia32_vcvtps2ph_mask: 2366 case X86::BI__builtin_ia32_vcvtps2ph256: 2367 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 2368 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 2369 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2370 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2371 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2372 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2373 case X86::BI__builtin_ia32_rndscaleps_mask: 2374 case X86::BI__builtin_ia32_rndscalepd_mask: 2375 case X86::BI__builtin_ia32_reducepd128_mask: 2376 case X86::BI__builtin_ia32_reducepd256_mask: 2377 case X86::BI__builtin_ia32_reducepd512_mask: 2378 case X86::BI__builtin_ia32_reduceps128_mask: 2379 case X86::BI__builtin_ia32_reduceps256_mask: 2380 case X86::BI__builtin_ia32_reduceps512_mask: 2381 case X86::BI__builtin_ia32_prold512_mask: 2382 case X86::BI__builtin_ia32_prolq512_mask: 2383 case X86::BI__builtin_ia32_prold128_mask: 2384 case X86::BI__builtin_ia32_prold256_mask: 2385 case X86::BI__builtin_ia32_prolq128_mask: 2386 case X86::BI__builtin_ia32_prolq256_mask: 2387 case X86::BI__builtin_ia32_prord128_mask: 2388 case X86::BI__builtin_ia32_prord256_mask: 2389 case X86::BI__builtin_ia32_prorq128_mask: 2390 case X86::BI__builtin_ia32_prorq256_mask: 2391 case X86::BI__builtin_ia32_fpclasspd128_mask: 2392 case X86::BI__builtin_ia32_fpclasspd256_mask: 2393 case X86::BI__builtin_ia32_fpclassps128_mask: 2394 case X86::BI__builtin_ia32_fpclassps256_mask: 2395 case X86::BI__builtin_ia32_fpclassps512_mask: 2396 case X86::BI__builtin_ia32_fpclasspd512_mask: 2397 case X86::BI__builtin_ia32_fpclasssd_mask: 2398 case X86::BI__builtin_ia32_fpclassss_mask: 2399 i = 1; l = 0; u = 255; 2400 break; 2401 case X86::BI__builtin_ia32_palignr128: 2402 case X86::BI__builtin_ia32_palignr256: 2403 case X86::BI__builtin_ia32_palignr512_mask: 2404 case X86::BI__builtin_ia32_vcomisd: 2405 case X86::BI__builtin_ia32_vcomiss: 2406 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2407 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2408 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2409 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2410 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2411 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2412 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2413 case X86::BI__builtin_ia32_vpshldd128_mask: 2414 case X86::BI__builtin_ia32_vpshldd256_mask: 2415 case X86::BI__builtin_ia32_vpshldd512_mask: 2416 case X86::BI__builtin_ia32_vpshldq128_mask: 2417 case X86::BI__builtin_ia32_vpshldq256_mask: 2418 case X86::BI__builtin_ia32_vpshldq512_mask: 2419 case X86::BI__builtin_ia32_vpshldw128_mask: 2420 case X86::BI__builtin_ia32_vpshldw256_mask: 2421 case X86::BI__builtin_ia32_vpshldw512_mask: 2422 case X86::BI__builtin_ia32_vpshrdd128_mask: 2423 case X86::BI__builtin_ia32_vpshrdd256_mask: 2424 case X86::BI__builtin_ia32_vpshrdd512_mask: 2425 case X86::BI__builtin_ia32_vpshrdq128_mask: 2426 case X86::BI__builtin_ia32_vpshrdq256_mask: 2427 case X86::BI__builtin_ia32_vpshrdq512_mask: 2428 case X86::BI__builtin_ia32_vpshrdw128_mask: 2429 case X86::BI__builtin_ia32_vpshrdw256_mask: 2430 case X86::BI__builtin_ia32_vpshrdw512_mask: 2431 i = 2; l = 0; u = 255; 2432 break; 2433 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2434 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2435 case X86::BI__builtin_ia32_fixupimmps512_mask: 2436 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2437 case X86::BI__builtin_ia32_fixupimmsd_mask: 2438 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2439 case X86::BI__builtin_ia32_fixupimmss_mask: 2440 case X86::BI__builtin_ia32_fixupimmss_maskz: 2441 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2442 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2443 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2444 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2445 case X86::BI__builtin_ia32_fixupimmps128_mask: 2446 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2447 case X86::BI__builtin_ia32_fixupimmps256_mask: 2448 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2449 case X86::BI__builtin_ia32_pternlogd512_mask: 2450 case X86::BI__builtin_ia32_pternlogd512_maskz: 2451 case X86::BI__builtin_ia32_pternlogq512_mask: 2452 case X86::BI__builtin_ia32_pternlogq512_maskz: 2453 case X86::BI__builtin_ia32_pternlogd128_mask: 2454 case X86::BI__builtin_ia32_pternlogd128_maskz: 2455 case X86::BI__builtin_ia32_pternlogd256_mask: 2456 case X86::BI__builtin_ia32_pternlogd256_maskz: 2457 case X86::BI__builtin_ia32_pternlogq128_mask: 2458 case X86::BI__builtin_ia32_pternlogq128_maskz: 2459 case X86::BI__builtin_ia32_pternlogq256_mask: 2460 case X86::BI__builtin_ia32_pternlogq256_maskz: 2461 i = 3; l = 0; u = 255; 2462 break; 2463 case X86::BI__builtin_ia32_gatherpfdpd: 2464 case X86::BI__builtin_ia32_gatherpfdps: 2465 case X86::BI__builtin_ia32_gatherpfqpd: 2466 case X86::BI__builtin_ia32_gatherpfqps: 2467 case X86::BI__builtin_ia32_scatterpfdpd: 2468 case X86::BI__builtin_ia32_scatterpfdps: 2469 case X86::BI__builtin_ia32_scatterpfqpd: 2470 case X86::BI__builtin_ia32_scatterpfqps: 2471 i = 4; l = 2; u = 3; 2472 break; 2473 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2474 case X86::BI__builtin_ia32_rndscaless_round_mask: 2475 i = 4; l = 0; u = 255; 2476 break; 2477 } 2478 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2479 } 2480 2481 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2482 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2483 /// Returns true when the format fits the function and the FormatStringInfo has 2484 /// been populated. 2485 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2486 FormatStringInfo *FSI) { 2487 FSI->HasVAListArg = Format->getFirstArg() == 0; 2488 FSI->FormatIdx = Format->getFormatIdx() - 1; 2489 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2490 2491 // The way the format attribute works in GCC, the implicit this argument 2492 // of member functions is counted. However, it doesn't appear in our own 2493 // lists, so decrement format_idx in that case. 2494 if (IsCXXMember) { 2495 if(FSI->FormatIdx == 0) 2496 return false; 2497 --FSI->FormatIdx; 2498 if (FSI->FirstDataArg != 0) 2499 --FSI->FirstDataArg; 2500 } 2501 return true; 2502 } 2503 2504 /// Checks if a the given expression evaluates to null. 2505 /// 2506 /// \brief Returns true if the value evaluates to null. 2507 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2508 // If the expression has non-null type, it doesn't evaluate to null. 2509 if (auto nullability 2510 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2511 if (*nullability == NullabilityKind::NonNull) 2512 return false; 2513 } 2514 2515 // As a special case, transparent unions initialized with zero are 2516 // considered null for the purposes of the nonnull attribute. 2517 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2518 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2519 if (const CompoundLiteralExpr *CLE = 2520 dyn_cast<CompoundLiteralExpr>(Expr)) 2521 if (const InitListExpr *ILE = 2522 dyn_cast<InitListExpr>(CLE->getInitializer())) 2523 Expr = ILE->getInit(0); 2524 } 2525 2526 bool Result; 2527 return (!Expr->isValueDependent() && 2528 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2529 !Result); 2530 } 2531 2532 static void CheckNonNullArgument(Sema &S, 2533 const Expr *ArgExpr, 2534 SourceLocation CallSiteLoc) { 2535 if (CheckNonNullExpr(S, ArgExpr)) 2536 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2537 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2538 } 2539 2540 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2541 FormatStringInfo FSI; 2542 if ((GetFormatStringType(Format) == FST_NSString) && 2543 getFormatStringInfo(Format, false, &FSI)) { 2544 Idx = FSI.FormatIdx; 2545 return true; 2546 } 2547 return false; 2548 } 2549 2550 /// \brief Diagnose use of %s directive in an NSString which is being passed 2551 /// as formatting string to formatting method. 2552 static void 2553 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2554 const NamedDecl *FDecl, 2555 Expr **Args, 2556 unsigned NumArgs) { 2557 unsigned Idx = 0; 2558 bool Format = false; 2559 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2560 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2561 Idx = 2; 2562 Format = true; 2563 } 2564 else 2565 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2566 if (S.GetFormatNSStringIdx(I, Idx)) { 2567 Format = true; 2568 break; 2569 } 2570 } 2571 if (!Format || NumArgs <= Idx) 2572 return; 2573 const Expr *FormatExpr = Args[Idx]; 2574 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2575 FormatExpr = CSCE->getSubExpr(); 2576 const StringLiteral *FormatString; 2577 if (const ObjCStringLiteral *OSL = 2578 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2579 FormatString = OSL->getString(); 2580 else 2581 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2582 if (!FormatString) 2583 return; 2584 if (S.FormatStringHasSArg(FormatString)) { 2585 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2586 << "%s" << 1 << 1; 2587 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2588 << FDecl->getDeclName(); 2589 } 2590 } 2591 2592 /// Determine whether the given type has a non-null nullability annotation. 2593 static bool isNonNullType(ASTContext &ctx, QualType type) { 2594 if (auto nullability = type->getNullability(ctx)) 2595 return *nullability == NullabilityKind::NonNull; 2596 2597 return false; 2598 } 2599 2600 static void CheckNonNullArguments(Sema &S, 2601 const NamedDecl *FDecl, 2602 const FunctionProtoType *Proto, 2603 ArrayRef<const Expr *> Args, 2604 SourceLocation CallSiteLoc) { 2605 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2606 2607 // Check the attributes attached to the method/function itself. 2608 llvm::SmallBitVector NonNullArgs; 2609 if (FDecl) { 2610 // Handle the nonnull attribute on the function/method declaration itself. 2611 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2612 if (!NonNull->args_size()) { 2613 // Easy case: all pointer arguments are nonnull. 2614 for (const auto *Arg : Args) 2615 if (S.isValidPointerAttrType(Arg->getType())) 2616 CheckNonNullArgument(S, Arg, CallSiteLoc); 2617 return; 2618 } 2619 2620 for (unsigned Val : NonNull->args()) { 2621 if (Val >= Args.size()) 2622 continue; 2623 if (NonNullArgs.empty()) 2624 NonNullArgs.resize(Args.size()); 2625 NonNullArgs.set(Val); 2626 } 2627 } 2628 } 2629 2630 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2631 // Handle the nonnull attribute on the parameters of the 2632 // function/method. 2633 ArrayRef<ParmVarDecl*> parms; 2634 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2635 parms = FD->parameters(); 2636 else 2637 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2638 2639 unsigned ParamIndex = 0; 2640 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2641 I != E; ++I, ++ParamIndex) { 2642 const ParmVarDecl *PVD = *I; 2643 if (PVD->hasAttr<NonNullAttr>() || 2644 isNonNullType(S.Context, PVD->getType())) { 2645 if (NonNullArgs.empty()) 2646 NonNullArgs.resize(Args.size()); 2647 2648 NonNullArgs.set(ParamIndex); 2649 } 2650 } 2651 } else { 2652 // If we have a non-function, non-method declaration but no 2653 // function prototype, try to dig out the function prototype. 2654 if (!Proto) { 2655 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2656 QualType type = VD->getType().getNonReferenceType(); 2657 if (auto pointerType = type->getAs<PointerType>()) 2658 type = pointerType->getPointeeType(); 2659 else if (auto blockType = type->getAs<BlockPointerType>()) 2660 type = blockType->getPointeeType(); 2661 // FIXME: data member pointers? 2662 2663 // Dig out the function prototype, if there is one. 2664 Proto = type->getAs<FunctionProtoType>(); 2665 } 2666 } 2667 2668 // Fill in non-null argument information from the nullability 2669 // information on the parameter types (if we have them). 2670 if (Proto) { 2671 unsigned Index = 0; 2672 for (auto paramType : Proto->getParamTypes()) { 2673 if (isNonNullType(S.Context, paramType)) { 2674 if (NonNullArgs.empty()) 2675 NonNullArgs.resize(Args.size()); 2676 2677 NonNullArgs.set(Index); 2678 } 2679 2680 ++Index; 2681 } 2682 } 2683 } 2684 2685 // Check for non-null arguments. 2686 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2687 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2688 if (NonNullArgs[ArgIndex]) 2689 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2690 } 2691 } 2692 2693 /// Handles the checks for format strings, non-POD arguments to vararg 2694 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2695 /// attributes. 2696 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2697 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2698 bool IsMemberFunction, SourceLocation Loc, 2699 SourceRange Range, VariadicCallType CallType) { 2700 // FIXME: We should check as much as we can in the template definition. 2701 if (CurContext->isDependentContext()) 2702 return; 2703 2704 // Printf and scanf checking. 2705 llvm::SmallBitVector CheckedVarArgs; 2706 if (FDecl) { 2707 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2708 // Only create vector if there are format attributes. 2709 CheckedVarArgs.resize(Args.size()); 2710 2711 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2712 CheckedVarArgs); 2713 } 2714 } 2715 2716 // Refuse POD arguments that weren't caught by the format string 2717 // checks above. 2718 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2719 if (CallType != VariadicDoesNotApply && 2720 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2721 unsigned NumParams = Proto ? Proto->getNumParams() 2722 : FDecl && isa<FunctionDecl>(FDecl) 2723 ? cast<FunctionDecl>(FDecl)->getNumParams() 2724 : FDecl && isa<ObjCMethodDecl>(FDecl) 2725 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2726 : 0; 2727 2728 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2729 // Args[ArgIdx] can be null in malformed code. 2730 if (const Expr *Arg = Args[ArgIdx]) { 2731 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2732 checkVariadicArgument(Arg, CallType); 2733 } 2734 } 2735 } 2736 2737 if (FDecl || Proto) { 2738 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2739 2740 // Type safety checking. 2741 if (FDecl) { 2742 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2743 CheckArgumentWithTypeTag(I, Args, Loc); 2744 } 2745 } 2746 2747 if (FD) 2748 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 2749 } 2750 2751 /// CheckConstructorCall - Check a constructor call for correctness and safety 2752 /// properties not enforced by the C type system. 2753 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2754 ArrayRef<const Expr *> Args, 2755 const FunctionProtoType *Proto, 2756 SourceLocation Loc) { 2757 VariadicCallType CallType = 2758 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2759 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 2760 Loc, SourceRange(), CallType); 2761 } 2762 2763 /// CheckFunctionCall - Check a direct function call for various correctness 2764 /// and safety properties not strictly enforced by the C type system. 2765 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2766 const FunctionProtoType *Proto) { 2767 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2768 isa<CXXMethodDecl>(FDecl); 2769 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2770 IsMemberOperatorCall; 2771 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2772 TheCall->getCallee()); 2773 Expr** Args = TheCall->getArgs(); 2774 unsigned NumArgs = TheCall->getNumArgs(); 2775 2776 Expr *ImplicitThis = nullptr; 2777 if (IsMemberOperatorCall) { 2778 // If this is a call to a member operator, hide the first argument 2779 // from checkCall. 2780 // FIXME: Our choice of AST representation here is less than ideal. 2781 ImplicitThis = Args[0]; 2782 ++Args; 2783 --NumArgs; 2784 } else if (IsMemberFunction) 2785 ImplicitThis = 2786 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 2787 2788 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 2789 IsMemberFunction, TheCall->getRParenLoc(), 2790 TheCall->getCallee()->getSourceRange(), CallType); 2791 2792 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2793 // None of the checks below are needed for functions that don't have 2794 // simple names (e.g., C++ conversion functions). 2795 if (!FnInfo) 2796 return false; 2797 2798 CheckAbsoluteValueFunction(TheCall, FDecl); 2799 CheckMaxUnsignedZero(TheCall, FDecl); 2800 2801 if (getLangOpts().ObjC1) 2802 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2803 2804 unsigned CMId = FDecl->getMemoryFunctionKind(); 2805 if (CMId == 0) 2806 return false; 2807 2808 // Handle memory setting and copying functions. 2809 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2810 CheckStrlcpycatArguments(TheCall, FnInfo); 2811 else if (CMId == Builtin::BIstrncat) 2812 CheckStrncatArguments(TheCall, FnInfo); 2813 else 2814 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2815 2816 return false; 2817 } 2818 2819 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2820 ArrayRef<const Expr *> Args) { 2821 VariadicCallType CallType = 2822 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2823 2824 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 2825 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2826 CallType); 2827 2828 return false; 2829 } 2830 2831 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2832 const FunctionProtoType *Proto) { 2833 QualType Ty; 2834 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2835 Ty = V->getType().getNonReferenceType(); 2836 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2837 Ty = F->getType().getNonReferenceType(); 2838 else 2839 return false; 2840 2841 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2842 !Ty->isFunctionProtoType()) 2843 return false; 2844 2845 VariadicCallType CallType; 2846 if (!Proto || !Proto->isVariadic()) { 2847 CallType = VariadicDoesNotApply; 2848 } else if (Ty->isBlockPointerType()) { 2849 CallType = VariadicBlock; 2850 } else { // Ty->isFunctionPointerType() 2851 CallType = VariadicFunction; 2852 } 2853 2854 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 2855 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2856 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2857 TheCall->getCallee()->getSourceRange(), CallType); 2858 2859 return false; 2860 } 2861 2862 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2863 /// such as function pointers returned from functions. 2864 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2865 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2866 TheCall->getCallee()); 2867 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 2868 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2869 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2870 TheCall->getCallee()->getSourceRange(), CallType); 2871 2872 return false; 2873 } 2874 2875 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2876 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2877 return false; 2878 2879 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2880 switch (Op) { 2881 case AtomicExpr::AO__c11_atomic_init: 2882 case AtomicExpr::AO__opencl_atomic_init: 2883 llvm_unreachable("There is no ordering argument for an init"); 2884 2885 case AtomicExpr::AO__c11_atomic_load: 2886 case AtomicExpr::AO__opencl_atomic_load: 2887 case AtomicExpr::AO__atomic_load_n: 2888 case AtomicExpr::AO__atomic_load: 2889 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2890 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2891 2892 case AtomicExpr::AO__c11_atomic_store: 2893 case AtomicExpr::AO__opencl_atomic_store: 2894 case AtomicExpr::AO__atomic_store: 2895 case AtomicExpr::AO__atomic_store_n: 2896 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2897 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2898 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2899 2900 default: 2901 return true; 2902 } 2903 } 2904 2905 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2906 AtomicExpr::AtomicOp Op) { 2907 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2908 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2909 2910 // All the non-OpenCL operations take one of the following forms. 2911 // The OpenCL operations take the __c11 forms with one extra argument for 2912 // synchronization scope. 2913 enum { 2914 // C __c11_atomic_init(A *, C) 2915 Init, 2916 2917 // C __c11_atomic_load(A *, int) 2918 Load, 2919 2920 // void __atomic_load(A *, CP, int) 2921 LoadCopy, 2922 2923 // void __atomic_store(A *, CP, int) 2924 Copy, 2925 2926 // C __c11_atomic_add(A *, M, int) 2927 Arithmetic, 2928 2929 // C __atomic_exchange_n(A *, CP, int) 2930 Xchg, 2931 2932 // void __atomic_exchange(A *, C *, CP, int) 2933 GNUXchg, 2934 2935 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2936 C11CmpXchg, 2937 2938 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2939 GNUCmpXchg 2940 } Form = Init; 2941 2942 const unsigned NumForm = GNUCmpXchg + 1; 2943 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2944 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2945 // where: 2946 // C is an appropriate type, 2947 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2948 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2949 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2950 // the int parameters are for orderings. 2951 2952 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 2953 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 2954 "need to update code for modified forms"); 2955 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2956 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2957 AtomicExpr::AO__atomic_load, 2958 "need to update code for modified C11 atomics"); 2959 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 2960 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 2961 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 2962 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 2963 IsOpenCL; 2964 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2965 Op == AtomicExpr::AO__atomic_store_n || 2966 Op == AtomicExpr::AO__atomic_exchange_n || 2967 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2968 bool IsAddSub = false; 2969 2970 switch (Op) { 2971 case AtomicExpr::AO__c11_atomic_init: 2972 case AtomicExpr::AO__opencl_atomic_init: 2973 Form = Init; 2974 break; 2975 2976 case AtomicExpr::AO__c11_atomic_load: 2977 case AtomicExpr::AO__opencl_atomic_load: 2978 case AtomicExpr::AO__atomic_load_n: 2979 Form = Load; 2980 break; 2981 2982 case AtomicExpr::AO__atomic_load: 2983 Form = LoadCopy; 2984 break; 2985 2986 case AtomicExpr::AO__c11_atomic_store: 2987 case AtomicExpr::AO__opencl_atomic_store: 2988 case AtomicExpr::AO__atomic_store: 2989 case AtomicExpr::AO__atomic_store_n: 2990 Form = Copy; 2991 break; 2992 2993 case AtomicExpr::AO__c11_atomic_fetch_add: 2994 case AtomicExpr::AO__c11_atomic_fetch_sub: 2995 case AtomicExpr::AO__opencl_atomic_fetch_add: 2996 case AtomicExpr::AO__opencl_atomic_fetch_sub: 2997 case AtomicExpr::AO__opencl_atomic_fetch_min: 2998 case AtomicExpr::AO__opencl_atomic_fetch_max: 2999 case AtomicExpr::AO__atomic_fetch_add: 3000 case AtomicExpr::AO__atomic_fetch_sub: 3001 case AtomicExpr::AO__atomic_add_fetch: 3002 case AtomicExpr::AO__atomic_sub_fetch: 3003 IsAddSub = true; 3004 LLVM_FALLTHROUGH; 3005 case AtomicExpr::AO__c11_atomic_fetch_and: 3006 case AtomicExpr::AO__c11_atomic_fetch_or: 3007 case AtomicExpr::AO__c11_atomic_fetch_xor: 3008 case AtomicExpr::AO__opencl_atomic_fetch_and: 3009 case AtomicExpr::AO__opencl_atomic_fetch_or: 3010 case AtomicExpr::AO__opencl_atomic_fetch_xor: 3011 case AtomicExpr::AO__atomic_fetch_and: 3012 case AtomicExpr::AO__atomic_fetch_or: 3013 case AtomicExpr::AO__atomic_fetch_xor: 3014 case AtomicExpr::AO__atomic_fetch_nand: 3015 case AtomicExpr::AO__atomic_and_fetch: 3016 case AtomicExpr::AO__atomic_or_fetch: 3017 case AtomicExpr::AO__atomic_xor_fetch: 3018 case AtomicExpr::AO__atomic_nand_fetch: 3019 Form = Arithmetic; 3020 break; 3021 3022 case AtomicExpr::AO__c11_atomic_exchange: 3023 case AtomicExpr::AO__opencl_atomic_exchange: 3024 case AtomicExpr::AO__atomic_exchange_n: 3025 Form = Xchg; 3026 break; 3027 3028 case AtomicExpr::AO__atomic_exchange: 3029 Form = GNUXchg; 3030 break; 3031 3032 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3033 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3034 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 3035 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 3036 Form = C11CmpXchg; 3037 break; 3038 3039 case AtomicExpr::AO__atomic_compare_exchange: 3040 case AtomicExpr::AO__atomic_compare_exchange_n: 3041 Form = GNUCmpXchg; 3042 break; 3043 } 3044 3045 unsigned AdjustedNumArgs = NumArgs[Form]; 3046 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 3047 ++AdjustedNumArgs; 3048 // Check we have the right number of arguments. 3049 if (TheCall->getNumArgs() < AdjustedNumArgs) { 3050 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3051 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3052 << TheCall->getCallee()->getSourceRange(); 3053 return ExprError(); 3054 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 3055 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 3056 diag::err_typecheck_call_too_many_args) 3057 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3058 << TheCall->getCallee()->getSourceRange(); 3059 return ExprError(); 3060 } 3061 3062 // Inspect the first argument of the atomic operation. 3063 Expr *Ptr = TheCall->getArg(0); 3064 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 3065 if (ConvertedPtr.isInvalid()) 3066 return ExprError(); 3067 3068 Ptr = ConvertedPtr.get(); 3069 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 3070 if (!pointerType) { 3071 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3072 << Ptr->getType() << Ptr->getSourceRange(); 3073 return ExprError(); 3074 } 3075 3076 // For a __c11 builtin, this should be a pointer to an _Atomic type. 3077 QualType AtomTy = pointerType->getPointeeType(); // 'A' 3078 QualType ValType = AtomTy; // 'C' 3079 if (IsC11) { 3080 if (!AtomTy->isAtomicType()) { 3081 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 3082 << Ptr->getType() << Ptr->getSourceRange(); 3083 return ExprError(); 3084 } 3085 if (AtomTy.isConstQualified() || 3086 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3087 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 3088 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3089 << Ptr->getSourceRange(); 3090 return ExprError(); 3091 } 3092 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 3093 } else if (Form != Load && Form != LoadCopy) { 3094 if (ValType.isConstQualified()) { 3095 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 3096 << Ptr->getType() << Ptr->getSourceRange(); 3097 return ExprError(); 3098 } 3099 } 3100 3101 // For an arithmetic operation, the implied arithmetic must be well-formed. 3102 if (Form == Arithmetic) { 3103 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3104 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 3105 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3106 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3107 return ExprError(); 3108 } 3109 if (!IsAddSub && !ValType->isIntegerType()) { 3110 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3111 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3112 return ExprError(); 3113 } 3114 if (IsC11 && ValType->isPointerType() && 3115 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3116 diag::err_incomplete_type)) { 3117 return ExprError(); 3118 } 3119 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3120 // For __atomic_*_n operations, the value type must be a scalar integral or 3121 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3122 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3123 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3124 return ExprError(); 3125 } 3126 3127 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3128 !AtomTy->isScalarType()) { 3129 // For GNU atomics, require a trivially-copyable type. This is not part of 3130 // the GNU atomics specification, but we enforce it for sanity. 3131 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3132 << Ptr->getType() << Ptr->getSourceRange(); 3133 return ExprError(); 3134 } 3135 3136 switch (ValType.getObjCLifetime()) { 3137 case Qualifiers::OCL_None: 3138 case Qualifiers::OCL_ExplicitNone: 3139 // okay 3140 break; 3141 3142 case Qualifiers::OCL_Weak: 3143 case Qualifiers::OCL_Strong: 3144 case Qualifiers::OCL_Autoreleasing: 3145 // FIXME: Can this happen? By this point, ValType should be known 3146 // to be trivially copyable. 3147 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3148 << ValType << Ptr->getSourceRange(); 3149 return ExprError(); 3150 } 3151 3152 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 3153 // volatile-ness of the pointee-type inject itself into the result or the 3154 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 3155 ValType.removeLocalVolatile(); 3156 ValType.removeLocalConst(); 3157 QualType ResultType = ValType; 3158 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3159 Form == Init) 3160 ResultType = Context.VoidTy; 3161 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3162 ResultType = Context.BoolTy; 3163 3164 // The type of a parameter passed 'by value'. In the GNU atomics, such 3165 // arguments are actually passed as pointers. 3166 QualType ByValType = ValType; // 'CP' 3167 if (!IsC11 && !IsN) 3168 ByValType = Ptr->getType(); 3169 3170 // The first argument --- the pointer --- has a fixed type; we 3171 // deduce the types of the rest of the arguments accordingly. Walk 3172 // the remaining arguments, converting them to the deduced value type. 3173 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) { 3174 QualType Ty; 3175 if (i < NumVals[Form] + 1) { 3176 switch (i) { 3177 case 1: 3178 // The second argument is the non-atomic operand. For arithmetic, this 3179 // is always passed by value, and for a compare_exchange it is always 3180 // passed by address. For the rest, GNU uses by-address and C11 uses 3181 // by-value. 3182 assert(Form != Load); 3183 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3184 Ty = ValType; 3185 else if (Form == Copy || Form == Xchg) 3186 Ty = ByValType; 3187 else if (Form == Arithmetic) 3188 Ty = Context.getPointerDiffType(); 3189 else { 3190 Expr *ValArg = TheCall->getArg(i); 3191 // Treat this argument as _Nonnull as we want to show a warning if 3192 // NULL is passed into it. 3193 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3194 LangAS AS = LangAS::Default; 3195 // Keep address space of non-atomic pointer type. 3196 if (const PointerType *PtrTy = 3197 ValArg->getType()->getAs<PointerType>()) { 3198 AS = PtrTy->getPointeeType().getAddressSpace(); 3199 } 3200 Ty = Context.getPointerType( 3201 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3202 } 3203 break; 3204 case 2: 3205 // The third argument to compare_exchange / GNU exchange is a 3206 // (pointer to a) desired value. 3207 Ty = ByValType; 3208 break; 3209 case 3: 3210 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3211 Ty = Context.BoolTy; 3212 break; 3213 } 3214 } else { 3215 // The order(s) and scope are always converted to int. 3216 Ty = Context.IntTy; 3217 } 3218 3219 InitializedEntity Entity = 3220 InitializedEntity::InitializeParameter(Context, Ty, false); 3221 ExprResult Arg = TheCall->getArg(i); 3222 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3223 if (Arg.isInvalid()) 3224 return true; 3225 TheCall->setArg(i, Arg.get()); 3226 } 3227 3228 // Permute the arguments into a 'consistent' order. 3229 SmallVector<Expr*, 5> SubExprs; 3230 SubExprs.push_back(Ptr); 3231 switch (Form) { 3232 case Init: 3233 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3234 SubExprs.push_back(TheCall->getArg(1)); // Val1 3235 break; 3236 case Load: 3237 SubExprs.push_back(TheCall->getArg(1)); // Order 3238 break; 3239 case LoadCopy: 3240 case Copy: 3241 case Arithmetic: 3242 case Xchg: 3243 SubExprs.push_back(TheCall->getArg(2)); // Order 3244 SubExprs.push_back(TheCall->getArg(1)); // Val1 3245 break; 3246 case GNUXchg: 3247 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3248 SubExprs.push_back(TheCall->getArg(3)); // Order 3249 SubExprs.push_back(TheCall->getArg(1)); // Val1 3250 SubExprs.push_back(TheCall->getArg(2)); // Val2 3251 break; 3252 case C11CmpXchg: 3253 SubExprs.push_back(TheCall->getArg(3)); // Order 3254 SubExprs.push_back(TheCall->getArg(1)); // Val1 3255 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3256 SubExprs.push_back(TheCall->getArg(2)); // Val2 3257 break; 3258 case GNUCmpXchg: 3259 SubExprs.push_back(TheCall->getArg(4)); // Order 3260 SubExprs.push_back(TheCall->getArg(1)); // Val1 3261 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3262 SubExprs.push_back(TheCall->getArg(2)); // Val2 3263 SubExprs.push_back(TheCall->getArg(3)); // Weak 3264 break; 3265 } 3266 3267 if (SubExprs.size() >= 2 && Form != Init) { 3268 llvm::APSInt Result(32); 3269 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3270 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3271 Diag(SubExprs[1]->getLocStart(), 3272 diag::warn_atomic_op_has_invalid_memory_order) 3273 << SubExprs[1]->getSourceRange(); 3274 } 3275 3276 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 3277 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3278 llvm::APSInt Result(32); 3279 if (Scope->isIntegerConstantExpr(Result, Context) && 3280 !ScopeModel->isValid(Result.getZExtValue())) { 3281 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3282 << Scope->getSourceRange(); 3283 } 3284 SubExprs.push_back(Scope); 3285 } 3286 3287 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3288 SubExprs, ResultType, Op, 3289 TheCall->getRParenLoc()); 3290 3291 if ((Op == AtomicExpr::AO__c11_atomic_load || 3292 Op == AtomicExpr::AO__c11_atomic_store || 3293 Op == AtomicExpr::AO__opencl_atomic_load || 3294 Op == AtomicExpr::AO__opencl_atomic_store ) && 3295 Context.AtomicUsesUnsupportedLibcall(AE)) 3296 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3297 << ((Op == AtomicExpr::AO__c11_atomic_load || 3298 Op == AtomicExpr::AO__opencl_atomic_load) 3299 ? 0 : 1); 3300 3301 return AE; 3302 } 3303 3304 /// checkBuiltinArgument - Given a call to a builtin function, perform 3305 /// normal type-checking on the given argument, updating the call in 3306 /// place. This is useful when a builtin function requires custom 3307 /// type-checking for some of its arguments but not necessarily all of 3308 /// them. 3309 /// 3310 /// Returns true on error. 3311 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3312 FunctionDecl *Fn = E->getDirectCallee(); 3313 assert(Fn && "builtin call without direct callee!"); 3314 3315 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3316 InitializedEntity Entity = 3317 InitializedEntity::InitializeParameter(S.Context, Param); 3318 3319 ExprResult Arg = E->getArg(0); 3320 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3321 if (Arg.isInvalid()) 3322 return true; 3323 3324 E->setArg(ArgIndex, Arg.get()); 3325 return false; 3326 } 3327 3328 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3329 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3330 /// type of its first argument. The main ActOnCallExpr routines have already 3331 /// promoted the types of arguments because all of these calls are prototyped as 3332 /// void(...). 3333 /// 3334 /// This function goes through and does final semantic checking for these 3335 /// builtins, 3336 ExprResult 3337 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3338 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3339 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3340 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3341 3342 // Ensure that we have at least one argument to do type inference from. 3343 if (TheCall->getNumArgs() < 1) { 3344 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3345 << 0 << 1 << TheCall->getNumArgs() 3346 << TheCall->getCallee()->getSourceRange(); 3347 return ExprError(); 3348 } 3349 3350 // Inspect the first argument of the atomic builtin. This should always be 3351 // a pointer type, whose element is an integral scalar or pointer type. 3352 // Because it is a pointer type, we don't have to worry about any implicit 3353 // casts here. 3354 // FIXME: We don't allow floating point scalars as input. 3355 Expr *FirstArg = TheCall->getArg(0); 3356 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3357 if (FirstArgResult.isInvalid()) 3358 return ExprError(); 3359 FirstArg = FirstArgResult.get(); 3360 TheCall->setArg(0, FirstArg); 3361 3362 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3363 if (!pointerType) { 3364 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3365 << FirstArg->getType() << FirstArg->getSourceRange(); 3366 return ExprError(); 3367 } 3368 3369 QualType ValType = pointerType->getPointeeType(); 3370 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3371 !ValType->isBlockPointerType()) { 3372 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3373 << FirstArg->getType() << FirstArg->getSourceRange(); 3374 return ExprError(); 3375 } 3376 3377 switch (ValType.getObjCLifetime()) { 3378 case Qualifiers::OCL_None: 3379 case Qualifiers::OCL_ExplicitNone: 3380 // okay 3381 break; 3382 3383 case Qualifiers::OCL_Weak: 3384 case Qualifiers::OCL_Strong: 3385 case Qualifiers::OCL_Autoreleasing: 3386 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3387 << ValType << FirstArg->getSourceRange(); 3388 return ExprError(); 3389 } 3390 3391 // Strip any qualifiers off ValType. 3392 ValType = ValType.getUnqualifiedType(); 3393 3394 // The majority of builtins return a value, but a few have special return 3395 // types, so allow them to override appropriately below. 3396 QualType ResultType = ValType; 3397 3398 // We need to figure out which concrete builtin this maps onto. For example, 3399 // __sync_fetch_and_add with a 2 byte object turns into 3400 // __sync_fetch_and_add_2. 3401 #define BUILTIN_ROW(x) \ 3402 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3403 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3404 3405 static const unsigned BuiltinIndices[][5] = { 3406 BUILTIN_ROW(__sync_fetch_and_add), 3407 BUILTIN_ROW(__sync_fetch_and_sub), 3408 BUILTIN_ROW(__sync_fetch_and_or), 3409 BUILTIN_ROW(__sync_fetch_and_and), 3410 BUILTIN_ROW(__sync_fetch_and_xor), 3411 BUILTIN_ROW(__sync_fetch_and_nand), 3412 3413 BUILTIN_ROW(__sync_add_and_fetch), 3414 BUILTIN_ROW(__sync_sub_and_fetch), 3415 BUILTIN_ROW(__sync_and_and_fetch), 3416 BUILTIN_ROW(__sync_or_and_fetch), 3417 BUILTIN_ROW(__sync_xor_and_fetch), 3418 BUILTIN_ROW(__sync_nand_and_fetch), 3419 3420 BUILTIN_ROW(__sync_val_compare_and_swap), 3421 BUILTIN_ROW(__sync_bool_compare_and_swap), 3422 BUILTIN_ROW(__sync_lock_test_and_set), 3423 BUILTIN_ROW(__sync_lock_release), 3424 BUILTIN_ROW(__sync_swap) 3425 }; 3426 #undef BUILTIN_ROW 3427 3428 // Determine the index of the size. 3429 unsigned SizeIndex; 3430 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3431 case 1: SizeIndex = 0; break; 3432 case 2: SizeIndex = 1; break; 3433 case 4: SizeIndex = 2; break; 3434 case 8: SizeIndex = 3; break; 3435 case 16: SizeIndex = 4; break; 3436 default: 3437 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3438 << FirstArg->getType() << FirstArg->getSourceRange(); 3439 return ExprError(); 3440 } 3441 3442 // Each of these builtins has one pointer argument, followed by some number of 3443 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3444 // that we ignore. Find out which row of BuiltinIndices to read from as well 3445 // as the number of fixed args. 3446 unsigned BuiltinID = FDecl->getBuiltinID(); 3447 unsigned BuiltinIndex, NumFixed = 1; 3448 bool WarnAboutSemanticsChange = false; 3449 switch (BuiltinID) { 3450 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3451 case Builtin::BI__sync_fetch_and_add: 3452 case Builtin::BI__sync_fetch_and_add_1: 3453 case Builtin::BI__sync_fetch_and_add_2: 3454 case Builtin::BI__sync_fetch_and_add_4: 3455 case Builtin::BI__sync_fetch_and_add_8: 3456 case Builtin::BI__sync_fetch_and_add_16: 3457 BuiltinIndex = 0; 3458 break; 3459 3460 case Builtin::BI__sync_fetch_and_sub: 3461 case Builtin::BI__sync_fetch_and_sub_1: 3462 case Builtin::BI__sync_fetch_and_sub_2: 3463 case Builtin::BI__sync_fetch_and_sub_4: 3464 case Builtin::BI__sync_fetch_and_sub_8: 3465 case Builtin::BI__sync_fetch_and_sub_16: 3466 BuiltinIndex = 1; 3467 break; 3468 3469 case Builtin::BI__sync_fetch_and_or: 3470 case Builtin::BI__sync_fetch_and_or_1: 3471 case Builtin::BI__sync_fetch_and_or_2: 3472 case Builtin::BI__sync_fetch_and_or_4: 3473 case Builtin::BI__sync_fetch_and_or_8: 3474 case Builtin::BI__sync_fetch_and_or_16: 3475 BuiltinIndex = 2; 3476 break; 3477 3478 case Builtin::BI__sync_fetch_and_and: 3479 case Builtin::BI__sync_fetch_and_and_1: 3480 case Builtin::BI__sync_fetch_and_and_2: 3481 case Builtin::BI__sync_fetch_and_and_4: 3482 case Builtin::BI__sync_fetch_and_and_8: 3483 case Builtin::BI__sync_fetch_and_and_16: 3484 BuiltinIndex = 3; 3485 break; 3486 3487 case Builtin::BI__sync_fetch_and_xor: 3488 case Builtin::BI__sync_fetch_and_xor_1: 3489 case Builtin::BI__sync_fetch_and_xor_2: 3490 case Builtin::BI__sync_fetch_and_xor_4: 3491 case Builtin::BI__sync_fetch_and_xor_8: 3492 case Builtin::BI__sync_fetch_and_xor_16: 3493 BuiltinIndex = 4; 3494 break; 3495 3496 case Builtin::BI__sync_fetch_and_nand: 3497 case Builtin::BI__sync_fetch_and_nand_1: 3498 case Builtin::BI__sync_fetch_and_nand_2: 3499 case Builtin::BI__sync_fetch_and_nand_4: 3500 case Builtin::BI__sync_fetch_and_nand_8: 3501 case Builtin::BI__sync_fetch_and_nand_16: 3502 BuiltinIndex = 5; 3503 WarnAboutSemanticsChange = true; 3504 break; 3505 3506 case Builtin::BI__sync_add_and_fetch: 3507 case Builtin::BI__sync_add_and_fetch_1: 3508 case Builtin::BI__sync_add_and_fetch_2: 3509 case Builtin::BI__sync_add_and_fetch_4: 3510 case Builtin::BI__sync_add_and_fetch_8: 3511 case Builtin::BI__sync_add_and_fetch_16: 3512 BuiltinIndex = 6; 3513 break; 3514 3515 case Builtin::BI__sync_sub_and_fetch: 3516 case Builtin::BI__sync_sub_and_fetch_1: 3517 case Builtin::BI__sync_sub_and_fetch_2: 3518 case Builtin::BI__sync_sub_and_fetch_4: 3519 case Builtin::BI__sync_sub_and_fetch_8: 3520 case Builtin::BI__sync_sub_and_fetch_16: 3521 BuiltinIndex = 7; 3522 break; 3523 3524 case Builtin::BI__sync_and_and_fetch: 3525 case Builtin::BI__sync_and_and_fetch_1: 3526 case Builtin::BI__sync_and_and_fetch_2: 3527 case Builtin::BI__sync_and_and_fetch_4: 3528 case Builtin::BI__sync_and_and_fetch_8: 3529 case Builtin::BI__sync_and_and_fetch_16: 3530 BuiltinIndex = 8; 3531 break; 3532 3533 case Builtin::BI__sync_or_and_fetch: 3534 case Builtin::BI__sync_or_and_fetch_1: 3535 case Builtin::BI__sync_or_and_fetch_2: 3536 case Builtin::BI__sync_or_and_fetch_4: 3537 case Builtin::BI__sync_or_and_fetch_8: 3538 case Builtin::BI__sync_or_and_fetch_16: 3539 BuiltinIndex = 9; 3540 break; 3541 3542 case Builtin::BI__sync_xor_and_fetch: 3543 case Builtin::BI__sync_xor_and_fetch_1: 3544 case Builtin::BI__sync_xor_and_fetch_2: 3545 case Builtin::BI__sync_xor_and_fetch_4: 3546 case Builtin::BI__sync_xor_and_fetch_8: 3547 case Builtin::BI__sync_xor_and_fetch_16: 3548 BuiltinIndex = 10; 3549 break; 3550 3551 case Builtin::BI__sync_nand_and_fetch: 3552 case Builtin::BI__sync_nand_and_fetch_1: 3553 case Builtin::BI__sync_nand_and_fetch_2: 3554 case Builtin::BI__sync_nand_and_fetch_4: 3555 case Builtin::BI__sync_nand_and_fetch_8: 3556 case Builtin::BI__sync_nand_and_fetch_16: 3557 BuiltinIndex = 11; 3558 WarnAboutSemanticsChange = true; 3559 break; 3560 3561 case Builtin::BI__sync_val_compare_and_swap: 3562 case Builtin::BI__sync_val_compare_and_swap_1: 3563 case Builtin::BI__sync_val_compare_and_swap_2: 3564 case Builtin::BI__sync_val_compare_and_swap_4: 3565 case Builtin::BI__sync_val_compare_and_swap_8: 3566 case Builtin::BI__sync_val_compare_and_swap_16: 3567 BuiltinIndex = 12; 3568 NumFixed = 2; 3569 break; 3570 3571 case Builtin::BI__sync_bool_compare_and_swap: 3572 case Builtin::BI__sync_bool_compare_and_swap_1: 3573 case Builtin::BI__sync_bool_compare_and_swap_2: 3574 case Builtin::BI__sync_bool_compare_and_swap_4: 3575 case Builtin::BI__sync_bool_compare_and_swap_8: 3576 case Builtin::BI__sync_bool_compare_and_swap_16: 3577 BuiltinIndex = 13; 3578 NumFixed = 2; 3579 ResultType = Context.BoolTy; 3580 break; 3581 3582 case Builtin::BI__sync_lock_test_and_set: 3583 case Builtin::BI__sync_lock_test_and_set_1: 3584 case Builtin::BI__sync_lock_test_and_set_2: 3585 case Builtin::BI__sync_lock_test_and_set_4: 3586 case Builtin::BI__sync_lock_test_and_set_8: 3587 case Builtin::BI__sync_lock_test_and_set_16: 3588 BuiltinIndex = 14; 3589 break; 3590 3591 case Builtin::BI__sync_lock_release: 3592 case Builtin::BI__sync_lock_release_1: 3593 case Builtin::BI__sync_lock_release_2: 3594 case Builtin::BI__sync_lock_release_4: 3595 case Builtin::BI__sync_lock_release_8: 3596 case Builtin::BI__sync_lock_release_16: 3597 BuiltinIndex = 15; 3598 NumFixed = 0; 3599 ResultType = Context.VoidTy; 3600 break; 3601 3602 case Builtin::BI__sync_swap: 3603 case Builtin::BI__sync_swap_1: 3604 case Builtin::BI__sync_swap_2: 3605 case Builtin::BI__sync_swap_4: 3606 case Builtin::BI__sync_swap_8: 3607 case Builtin::BI__sync_swap_16: 3608 BuiltinIndex = 16; 3609 break; 3610 } 3611 3612 // Now that we know how many fixed arguments we expect, first check that we 3613 // have at least that many. 3614 if (TheCall->getNumArgs() < 1+NumFixed) { 3615 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3616 << 0 << 1+NumFixed << TheCall->getNumArgs() 3617 << TheCall->getCallee()->getSourceRange(); 3618 return ExprError(); 3619 } 3620 3621 if (WarnAboutSemanticsChange) { 3622 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3623 << TheCall->getCallee()->getSourceRange(); 3624 } 3625 3626 // Get the decl for the concrete builtin from this, we can tell what the 3627 // concrete integer type we should convert to is. 3628 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3629 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3630 FunctionDecl *NewBuiltinDecl; 3631 if (NewBuiltinID == BuiltinID) 3632 NewBuiltinDecl = FDecl; 3633 else { 3634 // Perform builtin lookup to avoid redeclaring it. 3635 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3636 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3637 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3638 assert(Res.getFoundDecl()); 3639 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3640 if (!NewBuiltinDecl) 3641 return ExprError(); 3642 } 3643 3644 // The first argument --- the pointer --- has a fixed type; we 3645 // deduce the types of the rest of the arguments accordingly. Walk 3646 // the remaining arguments, converting them to the deduced value type. 3647 for (unsigned i = 0; i != NumFixed; ++i) { 3648 ExprResult Arg = TheCall->getArg(i+1); 3649 3650 // GCC does an implicit conversion to the pointer or integer ValType. This 3651 // can fail in some cases (1i -> int**), check for this error case now. 3652 // Initialize the argument. 3653 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3654 ValType, /*consume*/ false); 3655 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3656 if (Arg.isInvalid()) 3657 return ExprError(); 3658 3659 // Okay, we have something that *can* be converted to the right type. Check 3660 // to see if there is a potentially weird extension going on here. This can 3661 // happen when you do an atomic operation on something like an char* and 3662 // pass in 42. The 42 gets converted to char. This is even more strange 3663 // for things like 45.123 -> char, etc. 3664 // FIXME: Do this check. 3665 TheCall->setArg(i+1, Arg.get()); 3666 } 3667 3668 ASTContext& Context = this->getASTContext(); 3669 3670 // Create a new DeclRefExpr to refer to the new decl. 3671 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3672 Context, 3673 DRE->getQualifierLoc(), 3674 SourceLocation(), 3675 NewBuiltinDecl, 3676 /*enclosing*/ false, 3677 DRE->getLocation(), 3678 Context.BuiltinFnTy, 3679 DRE->getValueKind()); 3680 3681 // Set the callee in the CallExpr. 3682 // FIXME: This loses syntactic information. 3683 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3684 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3685 CK_BuiltinFnToFnPtr); 3686 TheCall->setCallee(PromotedCall.get()); 3687 3688 // Change the result type of the call to match the original value type. This 3689 // is arbitrary, but the codegen for these builtins ins design to handle it 3690 // gracefully. 3691 TheCall->setType(ResultType); 3692 3693 return TheCallResult; 3694 } 3695 3696 /// SemaBuiltinNontemporalOverloaded - We have a call to 3697 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3698 /// overloaded function based on the pointer type of its last argument. 3699 /// 3700 /// This function goes through and does final semantic checking for these 3701 /// builtins. 3702 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3703 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3704 DeclRefExpr *DRE = 3705 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3706 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3707 unsigned BuiltinID = FDecl->getBuiltinID(); 3708 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3709 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3710 "Unexpected nontemporal load/store builtin!"); 3711 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3712 unsigned numArgs = isStore ? 2 : 1; 3713 3714 // Ensure that we have the proper number of arguments. 3715 if (checkArgCount(*this, TheCall, numArgs)) 3716 return ExprError(); 3717 3718 // Inspect the last argument of the nontemporal builtin. This should always 3719 // be a pointer type, from which we imply the type of the memory access. 3720 // Because it is a pointer type, we don't have to worry about any implicit 3721 // casts here. 3722 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3723 ExprResult PointerArgResult = 3724 DefaultFunctionArrayLvalueConversion(PointerArg); 3725 3726 if (PointerArgResult.isInvalid()) 3727 return ExprError(); 3728 PointerArg = PointerArgResult.get(); 3729 TheCall->setArg(numArgs - 1, PointerArg); 3730 3731 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3732 if (!pointerType) { 3733 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3734 << PointerArg->getType() << PointerArg->getSourceRange(); 3735 return ExprError(); 3736 } 3737 3738 QualType ValType = pointerType->getPointeeType(); 3739 3740 // Strip any qualifiers off ValType. 3741 ValType = ValType.getUnqualifiedType(); 3742 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3743 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3744 !ValType->isVectorType()) { 3745 Diag(DRE->getLocStart(), 3746 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3747 << PointerArg->getType() << PointerArg->getSourceRange(); 3748 return ExprError(); 3749 } 3750 3751 if (!isStore) { 3752 TheCall->setType(ValType); 3753 return TheCallResult; 3754 } 3755 3756 ExprResult ValArg = TheCall->getArg(0); 3757 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3758 Context, ValType, /*consume*/ false); 3759 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3760 if (ValArg.isInvalid()) 3761 return ExprError(); 3762 3763 TheCall->setArg(0, ValArg.get()); 3764 TheCall->setType(Context.VoidTy); 3765 return TheCallResult; 3766 } 3767 3768 /// CheckObjCString - Checks that the argument to the builtin 3769 /// CFString constructor is correct 3770 /// Note: It might also make sense to do the UTF-16 conversion here (would 3771 /// simplify the backend). 3772 bool Sema::CheckObjCString(Expr *Arg) { 3773 Arg = Arg->IgnoreParenCasts(); 3774 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3775 3776 if (!Literal || !Literal->isAscii()) { 3777 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3778 << Arg->getSourceRange(); 3779 return true; 3780 } 3781 3782 if (Literal->containsNonAsciiOrNull()) { 3783 StringRef String = Literal->getString(); 3784 unsigned NumBytes = String.size(); 3785 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3786 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3787 llvm::UTF16 *ToPtr = &ToBuf[0]; 3788 3789 llvm::ConversionResult Result = 3790 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3791 ToPtr + NumBytes, llvm::strictConversion); 3792 // Check for conversion failure. 3793 if (Result != llvm::conversionOK) 3794 Diag(Arg->getLocStart(), 3795 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3796 } 3797 return false; 3798 } 3799 3800 /// CheckObjCString - Checks that the format string argument to the os_log() 3801 /// and os_trace() functions is correct, and converts it to const char *. 3802 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3803 Arg = Arg->IgnoreParenCasts(); 3804 auto *Literal = dyn_cast<StringLiteral>(Arg); 3805 if (!Literal) { 3806 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3807 Literal = ObjcLiteral->getString(); 3808 } 3809 } 3810 3811 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3812 return ExprError( 3813 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3814 << Arg->getSourceRange()); 3815 } 3816 3817 ExprResult Result(Literal); 3818 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3819 InitializedEntity Entity = 3820 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3821 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3822 return Result; 3823 } 3824 3825 /// Check that the user is calling the appropriate va_start builtin for the 3826 /// target and calling convention. 3827 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 3828 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 3829 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 3830 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 3831 bool IsWindows = TT.isOSWindows(); 3832 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 3833 if (IsX64 || IsAArch64) { 3834 CallingConv CC = CC_C; 3835 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 3836 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3837 if (IsMSVAStart) { 3838 // Don't allow this in System V ABI functions. 3839 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 3840 return S.Diag(Fn->getLocStart(), 3841 diag::err_ms_va_start_used_in_sysv_function); 3842 } else { 3843 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 3844 // On x64 Windows, don't allow this in System V ABI functions. 3845 // (Yes, that means there's no corresponding way to support variadic 3846 // System V ABI functions on Windows.) 3847 if ((IsWindows && CC == CC_X86_64SysV) || 3848 (!IsWindows && CC == CC_Win64)) 3849 return S.Diag(Fn->getLocStart(), 3850 diag::err_va_start_used_in_wrong_abi_function) 3851 << !IsWindows; 3852 } 3853 return false; 3854 } 3855 3856 if (IsMSVAStart) 3857 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 3858 return false; 3859 } 3860 3861 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 3862 ParmVarDecl **LastParam = nullptr) { 3863 // Determine whether the current function, block, or obj-c method is variadic 3864 // and get its parameter list. 3865 bool IsVariadic = false; 3866 ArrayRef<ParmVarDecl *> Params; 3867 DeclContext *Caller = S.CurContext; 3868 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 3869 IsVariadic = Block->isVariadic(); 3870 Params = Block->parameters(); 3871 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 3872 IsVariadic = FD->isVariadic(); 3873 Params = FD->parameters(); 3874 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 3875 IsVariadic = MD->isVariadic(); 3876 // FIXME: This isn't correct for methods (results in bogus warning). 3877 Params = MD->parameters(); 3878 } else if (isa<CapturedDecl>(Caller)) { 3879 // We don't support va_start in a CapturedDecl. 3880 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 3881 return true; 3882 } else { 3883 // This must be some other declcontext that parses exprs. 3884 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 3885 return true; 3886 } 3887 3888 if (!IsVariadic) { 3889 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 3890 return true; 3891 } 3892 3893 if (LastParam) 3894 *LastParam = Params.empty() ? nullptr : Params.back(); 3895 3896 return false; 3897 } 3898 3899 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3900 /// for validity. Emit an error and return true on failure; return false 3901 /// on success. 3902 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 3903 Expr *Fn = TheCall->getCallee(); 3904 3905 if (checkVAStartABI(*this, BuiltinID, Fn)) 3906 return true; 3907 3908 if (TheCall->getNumArgs() > 2) { 3909 Diag(TheCall->getArg(2)->getLocStart(), 3910 diag::err_typecheck_call_too_many_args) 3911 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3912 << Fn->getSourceRange() 3913 << SourceRange(TheCall->getArg(2)->getLocStart(), 3914 (*(TheCall->arg_end()-1))->getLocEnd()); 3915 return true; 3916 } 3917 3918 if (TheCall->getNumArgs() < 2) { 3919 return Diag(TheCall->getLocEnd(), 3920 diag::err_typecheck_call_too_few_args_at_least) 3921 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3922 } 3923 3924 // Type-check the first argument normally. 3925 if (checkBuiltinArgument(*this, TheCall, 0)) 3926 return true; 3927 3928 // Check that the current function is variadic, and get its last parameter. 3929 ParmVarDecl *LastParam; 3930 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 3931 return true; 3932 3933 // Verify that the second argument to the builtin is the last argument of the 3934 // current function or method. 3935 bool SecondArgIsLastNamedArgument = false; 3936 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3937 3938 // These are valid if SecondArgIsLastNamedArgument is false after the next 3939 // block. 3940 QualType Type; 3941 SourceLocation ParamLoc; 3942 bool IsCRegister = false; 3943 3944 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3945 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3946 SecondArgIsLastNamedArgument = PV == LastParam; 3947 3948 Type = PV->getType(); 3949 ParamLoc = PV->getLocation(); 3950 IsCRegister = 3951 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3952 } 3953 } 3954 3955 if (!SecondArgIsLastNamedArgument) 3956 Diag(TheCall->getArg(1)->getLocStart(), 3957 diag::warn_second_arg_of_va_start_not_last_named_param); 3958 else if (IsCRegister || Type->isReferenceType() || 3959 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3960 // Promotable integers are UB, but enumerations need a bit of 3961 // extra checking to see what their promotable type actually is. 3962 if (!Type->isPromotableIntegerType()) 3963 return false; 3964 if (!Type->isEnumeralType()) 3965 return true; 3966 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3967 return !(ED && 3968 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3969 }()) { 3970 unsigned Reason = 0; 3971 if (Type->isReferenceType()) Reason = 1; 3972 else if (IsCRegister) Reason = 2; 3973 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3974 Diag(ParamLoc, diag::note_parameter_type) << Type; 3975 } 3976 3977 TheCall->setType(Context.VoidTy); 3978 return false; 3979 } 3980 3981 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 3982 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3983 // const char *named_addr); 3984 3985 Expr *Func = Call->getCallee(); 3986 3987 if (Call->getNumArgs() < 3) 3988 return Diag(Call->getLocEnd(), 3989 diag::err_typecheck_call_too_few_args_at_least) 3990 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3991 3992 // Type-check the first argument normally. 3993 if (checkBuiltinArgument(*this, Call, 0)) 3994 return true; 3995 3996 // Check that the current function is variadic. 3997 if (checkVAStartIsInVariadicFunction(*this, Func)) 3998 return true; 3999 4000 // __va_start on Windows does not validate the parameter qualifiers 4001 4002 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 4003 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 4004 4005 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 4006 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 4007 4008 const QualType &ConstCharPtrTy = 4009 Context.getPointerType(Context.CharTy.withConst()); 4010 if (!Arg1Ty->isPointerType() || 4011 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 4012 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible) 4013 << Arg1->getType() << ConstCharPtrTy 4014 << 1 /* different class */ 4015 << 0 /* qualifier difference */ 4016 << 3 /* parameter mismatch */ 4017 << 2 << Arg1->getType() << ConstCharPtrTy; 4018 4019 const QualType SizeTy = Context.getSizeType(); 4020 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 4021 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible) 4022 << Arg2->getType() << SizeTy 4023 << 1 /* different class */ 4024 << 0 /* qualifier difference */ 4025 << 3 /* parameter mismatch */ 4026 << 3 << Arg2->getType() << SizeTy; 4027 4028 return false; 4029 } 4030 4031 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 4032 /// friends. This is declared to take (...), so we have to check everything. 4033 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 4034 if (TheCall->getNumArgs() < 2) 4035 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4036 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 4037 if (TheCall->getNumArgs() > 2) 4038 return Diag(TheCall->getArg(2)->getLocStart(), 4039 diag::err_typecheck_call_too_many_args) 4040 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4041 << SourceRange(TheCall->getArg(2)->getLocStart(), 4042 (*(TheCall->arg_end()-1))->getLocEnd()); 4043 4044 ExprResult OrigArg0 = TheCall->getArg(0); 4045 ExprResult OrigArg1 = TheCall->getArg(1); 4046 4047 // Do standard promotions between the two arguments, returning their common 4048 // type. 4049 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 4050 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 4051 return true; 4052 4053 // Make sure any conversions are pushed back into the call; this is 4054 // type safe since unordered compare builtins are declared as "_Bool 4055 // foo(...)". 4056 TheCall->setArg(0, OrigArg0.get()); 4057 TheCall->setArg(1, OrigArg1.get()); 4058 4059 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 4060 return false; 4061 4062 // If the common type isn't a real floating type, then the arguments were 4063 // invalid for this operation. 4064 if (Res.isNull() || !Res->isRealFloatingType()) 4065 return Diag(OrigArg0.get()->getLocStart(), 4066 diag::err_typecheck_call_invalid_ordered_compare) 4067 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 4068 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 4069 4070 return false; 4071 } 4072 4073 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 4074 /// __builtin_isnan and friends. This is declared to take (...), so we have 4075 /// to check everything. We expect the last argument to be a floating point 4076 /// value. 4077 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 4078 if (TheCall->getNumArgs() < NumArgs) 4079 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4080 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 4081 if (TheCall->getNumArgs() > NumArgs) 4082 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 4083 diag::err_typecheck_call_too_many_args) 4084 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 4085 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 4086 (*(TheCall->arg_end()-1))->getLocEnd()); 4087 4088 Expr *OrigArg = TheCall->getArg(NumArgs-1); 4089 4090 if (OrigArg->isTypeDependent()) 4091 return false; 4092 4093 // This operation requires a non-_Complex floating-point number. 4094 if (!OrigArg->getType()->isRealFloatingType()) 4095 return Diag(OrigArg->getLocStart(), 4096 diag::err_typecheck_call_invalid_unary_fp) 4097 << OrigArg->getType() << OrigArg->getSourceRange(); 4098 4099 // If this is an implicit conversion from float -> float or double, remove it. 4100 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4101 // Only remove standard FloatCasts, leaving other casts inplace 4102 if (Cast->getCastKind() == CK_FloatingCast) { 4103 Expr *CastArg = Cast->getSubExpr(); 4104 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4105 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4106 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 4107 "promotion from float to either float or double is the only expected cast here"); 4108 Cast->setSubExpr(nullptr); 4109 TheCall->setArg(NumArgs-1, CastArg); 4110 } 4111 } 4112 } 4113 4114 return false; 4115 } 4116 4117 // Customized Sema Checking for VSX builtins that have the following signature: 4118 // vector [...] builtinName(vector [...], vector [...], const int); 4119 // Which takes the same type of vectors (any legal vector type) for the first 4120 // two arguments and takes compile time constant for the third argument. 4121 // Example builtins are : 4122 // vector double vec_xxpermdi(vector double, vector double, int); 4123 // vector short vec_xxsldwi(vector short, vector short, int); 4124 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4125 unsigned ExpectedNumArgs = 3; 4126 if (TheCall->getNumArgs() < ExpectedNumArgs) 4127 return Diag(TheCall->getLocEnd(), 4128 diag::err_typecheck_call_too_few_args_at_least) 4129 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4130 << TheCall->getSourceRange(); 4131 4132 if (TheCall->getNumArgs() > ExpectedNumArgs) 4133 return Diag(TheCall->getLocEnd(), 4134 diag::err_typecheck_call_too_many_args_at_most) 4135 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4136 << TheCall->getSourceRange(); 4137 4138 // Check the third argument is a compile time constant 4139 llvm::APSInt Value; 4140 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4141 return Diag(TheCall->getLocStart(), 4142 diag::err_vsx_builtin_nonconstant_argument) 4143 << 3 /* argument index */ << TheCall->getDirectCallee() 4144 << SourceRange(TheCall->getArg(2)->getLocStart(), 4145 TheCall->getArg(2)->getLocEnd()); 4146 4147 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4148 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4149 4150 // Check the type of argument 1 and argument 2 are vectors. 4151 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4152 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4153 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4154 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4155 << TheCall->getDirectCallee() 4156 << SourceRange(TheCall->getArg(0)->getLocStart(), 4157 TheCall->getArg(1)->getLocEnd()); 4158 } 4159 4160 // Check the first two arguments are the same type. 4161 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4162 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4163 << TheCall->getDirectCallee() 4164 << SourceRange(TheCall->getArg(0)->getLocStart(), 4165 TheCall->getArg(1)->getLocEnd()); 4166 } 4167 4168 // When default clang type checking is turned off and the customized type 4169 // checking is used, the returning type of the function must be explicitly 4170 // set. Otherwise it is _Bool by default. 4171 TheCall->setType(Arg1Ty); 4172 4173 return false; 4174 } 4175 4176 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4177 // This is declared to take (...), so we have to check everything. 4178 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4179 if (TheCall->getNumArgs() < 2) 4180 return ExprError(Diag(TheCall->getLocEnd(), 4181 diag::err_typecheck_call_too_few_args_at_least) 4182 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4183 << TheCall->getSourceRange()); 4184 4185 // Determine which of the following types of shufflevector we're checking: 4186 // 1) unary, vector mask: (lhs, mask) 4187 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4188 QualType resType = TheCall->getArg(0)->getType(); 4189 unsigned numElements = 0; 4190 4191 if (!TheCall->getArg(0)->isTypeDependent() && 4192 !TheCall->getArg(1)->isTypeDependent()) { 4193 QualType LHSType = TheCall->getArg(0)->getType(); 4194 QualType RHSType = TheCall->getArg(1)->getType(); 4195 4196 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4197 return ExprError(Diag(TheCall->getLocStart(), 4198 diag::err_vec_builtin_non_vector) 4199 << TheCall->getDirectCallee() 4200 << SourceRange(TheCall->getArg(0)->getLocStart(), 4201 TheCall->getArg(1)->getLocEnd())); 4202 4203 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4204 unsigned numResElements = TheCall->getNumArgs() - 2; 4205 4206 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4207 // with mask. If so, verify that RHS is an integer vector type with the 4208 // same number of elts as lhs. 4209 if (TheCall->getNumArgs() == 2) { 4210 if (!RHSType->hasIntegerRepresentation() || 4211 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4212 return ExprError(Diag(TheCall->getLocStart(), 4213 diag::err_vec_builtin_incompatible_vector) 4214 << TheCall->getDirectCallee() 4215 << SourceRange(TheCall->getArg(1)->getLocStart(), 4216 TheCall->getArg(1)->getLocEnd())); 4217 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4218 return ExprError(Diag(TheCall->getLocStart(), 4219 diag::err_vec_builtin_incompatible_vector) 4220 << TheCall->getDirectCallee() 4221 << SourceRange(TheCall->getArg(0)->getLocStart(), 4222 TheCall->getArg(1)->getLocEnd())); 4223 } else if (numElements != numResElements) { 4224 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4225 resType = Context.getVectorType(eltType, numResElements, 4226 VectorType::GenericVector); 4227 } 4228 } 4229 4230 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4231 if (TheCall->getArg(i)->isTypeDependent() || 4232 TheCall->getArg(i)->isValueDependent()) 4233 continue; 4234 4235 llvm::APSInt Result(32); 4236 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4237 return ExprError(Diag(TheCall->getLocStart(), 4238 diag::err_shufflevector_nonconstant_argument) 4239 << TheCall->getArg(i)->getSourceRange()); 4240 4241 // Allow -1 which will be translated to undef in the IR. 4242 if (Result.isSigned() && Result.isAllOnesValue()) 4243 continue; 4244 4245 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4246 return ExprError(Diag(TheCall->getLocStart(), 4247 diag::err_shufflevector_argument_too_large) 4248 << TheCall->getArg(i)->getSourceRange()); 4249 } 4250 4251 SmallVector<Expr*, 32> exprs; 4252 4253 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4254 exprs.push_back(TheCall->getArg(i)); 4255 TheCall->setArg(i, nullptr); 4256 } 4257 4258 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4259 TheCall->getCallee()->getLocStart(), 4260 TheCall->getRParenLoc()); 4261 } 4262 4263 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4264 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4265 SourceLocation BuiltinLoc, 4266 SourceLocation RParenLoc) { 4267 ExprValueKind VK = VK_RValue; 4268 ExprObjectKind OK = OK_Ordinary; 4269 QualType DstTy = TInfo->getType(); 4270 QualType SrcTy = E->getType(); 4271 4272 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4273 return ExprError(Diag(BuiltinLoc, 4274 diag::err_convertvector_non_vector) 4275 << E->getSourceRange()); 4276 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4277 return ExprError(Diag(BuiltinLoc, 4278 diag::err_convertvector_non_vector_type)); 4279 4280 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4281 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4282 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4283 if (SrcElts != DstElts) 4284 return ExprError(Diag(BuiltinLoc, 4285 diag::err_convertvector_incompatible_vector) 4286 << E->getSourceRange()); 4287 } 4288 4289 return new (Context) 4290 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4291 } 4292 4293 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4294 // This is declared to take (const void*, ...) and can take two 4295 // optional constant int args. 4296 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4297 unsigned NumArgs = TheCall->getNumArgs(); 4298 4299 if (NumArgs > 3) 4300 return Diag(TheCall->getLocEnd(), 4301 diag::err_typecheck_call_too_many_args_at_most) 4302 << 0 /*function call*/ << 3 << NumArgs 4303 << TheCall->getSourceRange(); 4304 4305 // Argument 0 is checked for us and the remaining arguments must be 4306 // constant integers. 4307 for (unsigned i = 1; i != NumArgs; ++i) 4308 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4309 return true; 4310 4311 return false; 4312 } 4313 4314 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4315 // __assume does not evaluate its arguments, and should warn if its argument 4316 // has side effects. 4317 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4318 Expr *Arg = TheCall->getArg(0); 4319 if (Arg->isInstantiationDependent()) return false; 4320 4321 if (Arg->HasSideEffects(Context)) 4322 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4323 << Arg->getSourceRange() 4324 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4325 4326 return false; 4327 } 4328 4329 /// Handle __builtin_alloca_with_align. This is declared 4330 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4331 /// than 8. 4332 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4333 // The alignment must be a constant integer. 4334 Expr *Arg = TheCall->getArg(1); 4335 4336 // We can't check the value of a dependent argument. 4337 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4338 if (const auto *UE = 4339 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4340 if (UE->getKind() == UETT_AlignOf) 4341 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4342 << Arg->getSourceRange(); 4343 4344 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4345 4346 if (!Result.isPowerOf2()) 4347 return Diag(TheCall->getLocStart(), 4348 diag::err_alignment_not_power_of_two) 4349 << Arg->getSourceRange(); 4350 4351 if (Result < Context.getCharWidth()) 4352 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4353 << (unsigned)Context.getCharWidth() 4354 << Arg->getSourceRange(); 4355 4356 if (Result > std::numeric_limits<int32_t>::max()) 4357 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4358 << std::numeric_limits<int32_t>::max() 4359 << Arg->getSourceRange(); 4360 } 4361 4362 return false; 4363 } 4364 4365 /// Handle __builtin_assume_aligned. This is declared 4366 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4367 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4368 unsigned NumArgs = TheCall->getNumArgs(); 4369 4370 if (NumArgs > 3) 4371 return Diag(TheCall->getLocEnd(), 4372 diag::err_typecheck_call_too_many_args_at_most) 4373 << 0 /*function call*/ << 3 << NumArgs 4374 << TheCall->getSourceRange(); 4375 4376 // The alignment must be a constant integer. 4377 Expr *Arg = TheCall->getArg(1); 4378 4379 // We can't check the value of a dependent argument. 4380 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4381 llvm::APSInt Result; 4382 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4383 return true; 4384 4385 if (!Result.isPowerOf2()) 4386 return Diag(TheCall->getLocStart(), 4387 diag::err_alignment_not_power_of_two) 4388 << Arg->getSourceRange(); 4389 } 4390 4391 if (NumArgs > 2) { 4392 ExprResult Arg(TheCall->getArg(2)); 4393 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4394 Context.getSizeType(), false); 4395 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4396 if (Arg.isInvalid()) return true; 4397 TheCall->setArg(2, Arg.get()); 4398 } 4399 4400 return false; 4401 } 4402 4403 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4404 unsigned BuiltinID = 4405 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4406 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4407 4408 unsigned NumArgs = TheCall->getNumArgs(); 4409 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4410 if (NumArgs < NumRequiredArgs) { 4411 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4412 << 0 /* function call */ << NumRequiredArgs << NumArgs 4413 << TheCall->getSourceRange(); 4414 } 4415 if (NumArgs >= NumRequiredArgs + 0x100) { 4416 return Diag(TheCall->getLocEnd(), 4417 diag::err_typecheck_call_too_many_args_at_most) 4418 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4419 << TheCall->getSourceRange(); 4420 } 4421 unsigned i = 0; 4422 4423 // For formatting call, check buffer arg. 4424 if (!IsSizeCall) { 4425 ExprResult Arg(TheCall->getArg(i)); 4426 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4427 Context, Context.VoidPtrTy, false); 4428 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4429 if (Arg.isInvalid()) 4430 return true; 4431 TheCall->setArg(i, Arg.get()); 4432 i++; 4433 } 4434 4435 // Check string literal arg. 4436 unsigned FormatIdx = i; 4437 { 4438 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4439 if (Arg.isInvalid()) 4440 return true; 4441 TheCall->setArg(i, Arg.get()); 4442 i++; 4443 } 4444 4445 // Make sure variadic args are scalar. 4446 unsigned FirstDataArg = i; 4447 while (i < NumArgs) { 4448 ExprResult Arg = DefaultVariadicArgumentPromotion( 4449 TheCall->getArg(i), VariadicFunction, nullptr); 4450 if (Arg.isInvalid()) 4451 return true; 4452 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4453 if (ArgSize.getQuantity() >= 0x100) { 4454 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4455 << i << (int)ArgSize.getQuantity() << 0xff 4456 << TheCall->getSourceRange(); 4457 } 4458 TheCall->setArg(i, Arg.get()); 4459 i++; 4460 } 4461 4462 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4463 // call to avoid duplicate diagnostics. 4464 if (!IsSizeCall) { 4465 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4466 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4467 bool Success = CheckFormatArguments( 4468 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4469 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4470 CheckedVarArgs); 4471 if (!Success) 4472 return true; 4473 } 4474 4475 if (IsSizeCall) { 4476 TheCall->setType(Context.getSizeType()); 4477 } else { 4478 TheCall->setType(Context.VoidPtrTy); 4479 } 4480 return false; 4481 } 4482 4483 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4484 /// TheCall is a constant expression. 4485 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4486 llvm::APSInt &Result) { 4487 Expr *Arg = TheCall->getArg(ArgNum); 4488 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4489 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4490 4491 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4492 4493 if (!Arg->isIntegerConstantExpr(Result, Context)) 4494 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4495 << FDecl->getDeclName() << Arg->getSourceRange(); 4496 4497 return false; 4498 } 4499 4500 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4501 /// TheCall is a constant expression in the range [Low, High]. 4502 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4503 int Low, int High) { 4504 llvm::APSInt Result; 4505 4506 // We can't check the value of a dependent argument. 4507 Expr *Arg = TheCall->getArg(ArgNum); 4508 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4509 return false; 4510 4511 // Check constant-ness first. 4512 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4513 return true; 4514 4515 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4516 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4517 << Low << High << Arg->getSourceRange(); 4518 4519 return false; 4520 } 4521 4522 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4523 /// TheCall is a constant expression is a multiple of Num.. 4524 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4525 unsigned Num) { 4526 llvm::APSInt Result; 4527 4528 // We can't check the value of a dependent argument. 4529 Expr *Arg = TheCall->getArg(ArgNum); 4530 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4531 return false; 4532 4533 // Check constant-ness first. 4534 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4535 return true; 4536 4537 if (Result.getSExtValue() % Num != 0) 4538 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4539 << Num << Arg->getSourceRange(); 4540 4541 return false; 4542 } 4543 4544 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4545 /// TheCall is an ARM/AArch64 special register string literal. 4546 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4547 int ArgNum, unsigned ExpectedFieldNum, 4548 bool AllowName) { 4549 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4550 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4551 BuiltinID == ARM::BI__builtin_arm_rsr || 4552 BuiltinID == ARM::BI__builtin_arm_rsrp || 4553 BuiltinID == ARM::BI__builtin_arm_wsr || 4554 BuiltinID == ARM::BI__builtin_arm_wsrp; 4555 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4556 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4557 BuiltinID == AArch64::BI__builtin_arm_rsr || 4558 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4559 BuiltinID == AArch64::BI__builtin_arm_wsr || 4560 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4561 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4562 4563 // We can't check the value of a dependent argument. 4564 Expr *Arg = TheCall->getArg(ArgNum); 4565 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4566 return false; 4567 4568 // Check if the argument is a string literal. 4569 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4570 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4571 << Arg->getSourceRange(); 4572 4573 // Check the type of special register given. 4574 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4575 SmallVector<StringRef, 6> Fields; 4576 Reg.split(Fields, ":"); 4577 4578 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4579 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4580 << Arg->getSourceRange(); 4581 4582 // If the string is the name of a register then we cannot check that it is 4583 // valid here but if the string is of one the forms described in ACLE then we 4584 // can check that the supplied fields are integers and within the valid 4585 // ranges. 4586 if (Fields.size() > 1) { 4587 bool FiveFields = Fields.size() == 5; 4588 4589 bool ValidString = true; 4590 if (IsARMBuiltin) { 4591 ValidString &= Fields[0].startswith_lower("cp") || 4592 Fields[0].startswith_lower("p"); 4593 if (ValidString) 4594 Fields[0] = 4595 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4596 4597 ValidString &= Fields[2].startswith_lower("c"); 4598 if (ValidString) 4599 Fields[2] = Fields[2].drop_front(1); 4600 4601 if (FiveFields) { 4602 ValidString &= Fields[3].startswith_lower("c"); 4603 if (ValidString) 4604 Fields[3] = Fields[3].drop_front(1); 4605 } 4606 } 4607 4608 SmallVector<int, 5> Ranges; 4609 if (FiveFields) 4610 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4611 else 4612 Ranges.append({15, 7, 15}); 4613 4614 for (unsigned i=0; i<Fields.size(); ++i) { 4615 int IntField; 4616 ValidString &= !Fields[i].getAsInteger(10, IntField); 4617 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4618 } 4619 4620 if (!ValidString) 4621 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4622 << Arg->getSourceRange(); 4623 } else if (IsAArch64Builtin && Fields.size() == 1) { 4624 // If the register name is one of those that appear in the condition below 4625 // and the special register builtin being used is one of the write builtins, 4626 // then we require that the argument provided for writing to the register 4627 // is an integer constant expression. This is because it will be lowered to 4628 // an MSR (immediate) instruction, so we need to know the immediate at 4629 // compile time. 4630 if (TheCall->getNumArgs() != 2) 4631 return false; 4632 4633 std::string RegLower = Reg.lower(); 4634 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4635 RegLower != "pan" && RegLower != "uao") 4636 return false; 4637 4638 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4639 } 4640 4641 return false; 4642 } 4643 4644 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4645 /// This checks that the target supports __builtin_longjmp and 4646 /// that val is a constant 1. 4647 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4648 if (!Context.getTargetInfo().hasSjLjLowering()) 4649 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4650 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4651 4652 Expr *Arg = TheCall->getArg(1); 4653 llvm::APSInt Result; 4654 4655 // TODO: This is less than ideal. Overload this to take a value. 4656 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4657 return true; 4658 4659 if (Result != 1) 4660 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4661 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4662 4663 return false; 4664 } 4665 4666 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4667 /// This checks that the target supports __builtin_setjmp. 4668 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4669 if (!Context.getTargetInfo().hasSjLjLowering()) 4670 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4671 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4672 return false; 4673 } 4674 4675 namespace { 4676 4677 class UncoveredArgHandler { 4678 enum { Unknown = -1, AllCovered = -2 }; 4679 4680 signed FirstUncoveredArg = Unknown; 4681 SmallVector<const Expr *, 4> DiagnosticExprs; 4682 4683 public: 4684 UncoveredArgHandler() = default; 4685 4686 bool hasUncoveredArg() const { 4687 return (FirstUncoveredArg >= 0); 4688 } 4689 4690 unsigned getUncoveredArg() const { 4691 assert(hasUncoveredArg() && "no uncovered argument"); 4692 return FirstUncoveredArg; 4693 } 4694 4695 void setAllCovered() { 4696 // A string has been found with all arguments covered, so clear out 4697 // the diagnostics. 4698 DiagnosticExprs.clear(); 4699 FirstUncoveredArg = AllCovered; 4700 } 4701 4702 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4703 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4704 4705 // Don't update if a previous string covers all arguments. 4706 if (FirstUncoveredArg == AllCovered) 4707 return; 4708 4709 // UncoveredArgHandler tracks the highest uncovered argument index 4710 // and with it all the strings that match this index. 4711 if (NewFirstUncoveredArg == FirstUncoveredArg) 4712 DiagnosticExprs.push_back(StrExpr); 4713 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4714 DiagnosticExprs.clear(); 4715 DiagnosticExprs.push_back(StrExpr); 4716 FirstUncoveredArg = NewFirstUncoveredArg; 4717 } 4718 } 4719 4720 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4721 }; 4722 4723 enum StringLiteralCheckType { 4724 SLCT_NotALiteral, 4725 SLCT_UncheckedLiteral, 4726 SLCT_CheckedLiteral 4727 }; 4728 4729 } // namespace 4730 4731 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4732 BinaryOperatorKind BinOpKind, 4733 bool AddendIsRight) { 4734 unsigned BitWidth = Offset.getBitWidth(); 4735 unsigned AddendBitWidth = Addend.getBitWidth(); 4736 // There might be negative interim results. 4737 if (Addend.isUnsigned()) { 4738 Addend = Addend.zext(++AddendBitWidth); 4739 Addend.setIsSigned(true); 4740 } 4741 // Adjust the bit width of the APSInts. 4742 if (AddendBitWidth > BitWidth) { 4743 Offset = Offset.sext(AddendBitWidth); 4744 BitWidth = AddendBitWidth; 4745 } else if (BitWidth > AddendBitWidth) { 4746 Addend = Addend.sext(BitWidth); 4747 } 4748 4749 bool Ov = false; 4750 llvm::APSInt ResOffset = Offset; 4751 if (BinOpKind == BO_Add) 4752 ResOffset = Offset.sadd_ov(Addend, Ov); 4753 else { 4754 assert(AddendIsRight && BinOpKind == BO_Sub && 4755 "operator must be add or sub with addend on the right"); 4756 ResOffset = Offset.ssub_ov(Addend, Ov); 4757 } 4758 4759 // We add an offset to a pointer here so we should support an offset as big as 4760 // possible. 4761 if (Ov) { 4762 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 4763 "index (intermediate) result too big"); 4764 Offset = Offset.sext(2 * BitWidth); 4765 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4766 return; 4767 } 4768 4769 Offset = ResOffset; 4770 } 4771 4772 namespace { 4773 4774 // This is a wrapper class around StringLiteral to support offsetted string 4775 // literals as format strings. It takes the offset into account when returning 4776 // the string and its length or the source locations to display notes correctly. 4777 class FormatStringLiteral { 4778 const StringLiteral *FExpr; 4779 int64_t Offset; 4780 4781 public: 4782 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4783 : FExpr(fexpr), Offset(Offset) {} 4784 4785 StringRef getString() const { 4786 return FExpr->getString().drop_front(Offset); 4787 } 4788 4789 unsigned getByteLength() const { 4790 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4791 } 4792 4793 unsigned getLength() const { return FExpr->getLength() - Offset; } 4794 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4795 4796 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4797 4798 QualType getType() const { return FExpr->getType(); } 4799 4800 bool isAscii() const { return FExpr->isAscii(); } 4801 bool isWide() const { return FExpr->isWide(); } 4802 bool isUTF8() const { return FExpr->isUTF8(); } 4803 bool isUTF16() const { return FExpr->isUTF16(); } 4804 bool isUTF32() const { return FExpr->isUTF32(); } 4805 bool isPascal() const { return FExpr->isPascal(); } 4806 4807 SourceLocation getLocationOfByte( 4808 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4809 const TargetInfo &Target, unsigned *StartToken = nullptr, 4810 unsigned *StartTokenByteOffset = nullptr) const { 4811 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4812 StartToken, StartTokenByteOffset); 4813 } 4814 4815 SourceLocation getLocStart() const LLVM_READONLY { 4816 return FExpr->getLocStart().getLocWithOffset(Offset); 4817 } 4818 4819 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4820 }; 4821 4822 } // namespace 4823 4824 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4825 const Expr *OrigFormatExpr, 4826 ArrayRef<const Expr *> Args, 4827 bool HasVAListArg, unsigned format_idx, 4828 unsigned firstDataArg, 4829 Sema::FormatStringType Type, 4830 bool inFunctionCall, 4831 Sema::VariadicCallType CallType, 4832 llvm::SmallBitVector &CheckedVarArgs, 4833 UncoveredArgHandler &UncoveredArg); 4834 4835 // Determine if an expression is a string literal or constant string. 4836 // If this function returns false on the arguments to a function expecting a 4837 // format string, we will usually need to emit a warning. 4838 // True string literals are then checked by CheckFormatString. 4839 static StringLiteralCheckType 4840 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4841 bool HasVAListArg, unsigned format_idx, 4842 unsigned firstDataArg, Sema::FormatStringType Type, 4843 Sema::VariadicCallType CallType, bool InFunctionCall, 4844 llvm::SmallBitVector &CheckedVarArgs, 4845 UncoveredArgHandler &UncoveredArg, 4846 llvm::APSInt Offset) { 4847 tryAgain: 4848 assert(Offset.isSigned() && "invalid offset"); 4849 4850 if (E->isTypeDependent() || E->isValueDependent()) 4851 return SLCT_NotALiteral; 4852 4853 E = E->IgnoreParenCasts(); 4854 4855 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4856 // Technically -Wformat-nonliteral does not warn about this case. 4857 // The behavior of printf and friends in this case is implementation 4858 // dependent. Ideally if the format string cannot be null then 4859 // it should have a 'nonnull' attribute in the function prototype. 4860 return SLCT_UncheckedLiteral; 4861 4862 switch (E->getStmtClass()) { 4863 case Stmt::BinaryConditionalOperatorClass: 4864 case Stmt::ConditionalOperatorClass: { 4865 // The expression is a literal if both sub-expressions were, and it was 4866 // completely checked only if both sub-expressions were checked. 4867 const AbstractConditionalOperator *C = 4868 cast<AbstractConditionalOperator>(E); 4869 4870 // Determine whether it is necessary to check both sub-expressions, for 4871 // example, because the condition expression is a constant that can be 4872 // evaluated at compile time. 4873 bool CheckLeft = true, CheckRight = true; 4874 4875 bool Cond; 4876 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4877 if (Cond) 4878 CheckRight = false; 4879 else 4880 CheckLeft = false; 4881 } 4882 4883 // We need to maintain the offsets for the right and the left hand side 4884 // separately to check if every possible indexed expression is a valid 4885 // string literal. They might have different offsets for different string 4886 // literals in the end. 4887 StringLiteralCheckType Left; 4888 if (!CheckLeft) 4889 Left = SLCT_UncheckedLiteral; 4890 else { 4891 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4892 HasVAListArg, format_idx, firstDataArg, 4893 Type, CallType, InFunctionCall, 4894 CheckedVarArgs, UncoveredArg, Offset); 4895 if (Left == SLCT_NotALiteral || !CheckRight) { 4896 return Left; 4897 } 4898 } 4899 4900 StringLiteralCheckType Right = 4901 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4902 HasVAListArg, format_idx, firstDataArg, 4903 Type, CallType, InFunctionCall, CheckedVarArgs, 4904 UncoveredArg, Offset); 4905 4906 return (CheckLeft && Left < Right) ? Left : Right; 4907 } 4908 4909 case Stmt::ImplicitCastExprClass: 4910 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4911 goto tryAgain; 4912 4913 case Stmt::OpaqueValueExprClass: 4914 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4915 E = src; 4916 goto tryAgain; 4917 } 4918 return SLCT_NotALiteral; 4919 4920 case Stmt::PredefinedExprClass: 4921 // While __func__, etc., are technically not string literals, they 4922 // cannot contain format specifiers and thus are not a security 4923 // liability. 4924 return SLCT_UncheckedLiteral; 4925 4926 case Stmt::DeclRefExprClass: { 4927 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4928 4929 // As an exception, do not flag errors for variables binding to 4930 // const string literals. 4931 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4932 bool isConstant = false; 4933 QualType T = DR->getType(); 4934 4935 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4936 isConstant = AT->getElementType().isConstant(S.Context); 4937 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4938 isConstant = T.isConstant(S.Context) && 4939 PT->getPointeeType().isConstant(S.Context); 4940 } else if (T->isObjCObjectPointerType()) { 4941 // In ObjC, there is usually no "const ObjectPointer" type, 4942 // so don't check if the pointee type is constant. 4943 isConstant = T.isConstant(S.Context); 4944 } 4945 4946 if (isConstant) { 4947 if (const Expr *Init = VD->getAnyInitializer()) { 4948 // Look through initializers like const char c[] = { "foo" } 4949 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4950 if (InitList->isStringLiteralInit()) 4951 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4952 } 4953 return checkFormatStringExpr(S, Init, Args, 4954 HasVAListArg, format_idx, 4955 firstDataArg, Type, CallType, 4956 /*InFunctionCall*/ false, CheckedVarArgs, 4957 UncoveredArg, Offset); 4958 } 4959 } 4960 4961 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4962 // special check to see if the format string is a function parameter 4963 // of the function calling the printf function. If the function 4964 // has an attribute indicating it is a printf-like function, then we 4965 // should suppress warnings concerning non-literals being used in a call 4966 // to a vprintf function. For example: 4967 // 4968 // void 4969 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4970 // va_list ap; 4971 // va_start(ap, fmt); 4972 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4973 // ... 4974 // } 4975 if (HasVAListArg) { 4976 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4977 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4978 int PVIndex = PV->getFunctionScopeIndex() + 1; 4979 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4980 // adjust for implicit parameter 4981 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4982 if (MD->isInstance()) 4983 ++PVIndex; 4984 // We also check if the formats are compatible. 4985 // We can't pass a 'scanf' string to a 'printf' function. 4986 if (PVIndex == PVFormat->getFormatIdx() && 4987 Type == S.GetFormatStringType(PVFormat)) 4988 return SLCT_UncheckedLiteral; 4989 } 4990 } 4991 } 4992 } 4993 } 4994 4995 return SLCT_NotALiteral; 4996 } 4997 4998 case Stmt::CallExprClass: 4999 case Stmt::CXXMemberCallExprClass: { 5000 const CallExpr *CE = cast<CallExpr>(E); 5001 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 5002 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 5003 unsigned ArgIndex = FA->getFormatIdx(); 5004 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5005 if (MD->isInstance()) 5006 --ArgIndex; 5007 const Expr *Arg = CE->getArg(ArgIndex - 1); 5008 5009 return checkFormatStringExpr(S, Arg, Args, 5010 HasVAListArg, format_idx, firstDataArg, 5011 Type, CallType, InFunctionCall, 5012 CheckedVarArgs, UncoveredArg, Offset); 5013 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 5014 unsigned BuiltinID = FD->getBuiltinID(); 5015 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 5016 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 5017 const Expr *Arg = CE->getArg(0); 5018 return checkFormatStringExpr(S, Arg, Args, 5019 HasVAListArg, format_idx, 5020 firstDataArg, Type, CallType, 5021 InFunctionCall, CheckedVarArgs, 5022 UncoveredArg, Offset); 5023 } 5024 } 5025 } 5026 5027 return SLCT_NotALiteral; 5028 } 5029 case Stmt::ObjCMessageExprClass: { 5030 const auto *ME = cast<ObjCMessageExpr>(E); 5031 if (const auto *ND = ME->getMethodDecl()) { 5032 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 5033 unsigned ArgIndex = FA->getFormatIdx(); 5034 const Expr *Arg = ME->getArg(ArgIndex - 1); 5035 return checkFormatStringExpr( 5036 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 5037 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 5038 } 5039 } 5040 5041 return SLCT_NotALiteral; 5042 } 5043 case Stmt::ObjCStringLiteralClass: 5044 case Stmt::StringLiteralClass: { 5045 const StringLiteral *StrE = nullptr; 5046 5047 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 5048 StrE = ObjCFExpr->getString(); 5049 else 5050 StrE = cast<StringLiteral>(E); 5051 5052 if (StrE) { 5053 if (Offset.isNegative() || Offset > StrE->getLength()) { 5054 // TODO: It would be better to have an explicit warning for out of 5055 // bounds literals. 5056 return SLCT_NotALiteral; 5057 } 5058 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 5059 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 5060 firstDataArg, Type, InFunctionCall, CallType, 5061 CheckedVarArgs, UncoveredArg); 5062 return SLCT_CheckedLiteral; 5063 } 5064 5065 return SLCT_NotALiteral; 5066 } 5067 case Stmt::BinaryOperatorClass: { 5068 llvm::APSInt LResult; 5069 llvm::APSInt RResult; 5070 5071 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 5072 5073 // A string literal + an int offset is still a string literal. 5074 if (BinOp->isAdditiveOp()) { 5075 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 5076 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 5077 5078 if (LIsInt != RIsInt) { 5079 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 5080 5081 if (LIsInt) { 5082 if (BinOpKind == BO_Add) { 5083 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 5084 E = BinOp->getRHS(); 5085 goto tryAgain; 5086 } 5087 } else { 5088 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 5089 E = BinOp->getLHS(); 5090 goto tryAgain; 5091 } 5092 } 5093 } 5094 5095 return SLCT_NotALiteral; 5096 } 5097 case Stmt::UnaryOperatorClass: { 5098 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 5099 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 5100 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 5101 llvm::APSInt IndexResult; 5102 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5103 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5104 E = ASE->getBase(); 5105 goto tryAgain; 5106 } 5107 } 5108 5109 return SLCT_NotALiteral; 5110 } 5111 5112 default: 5113 return SLCT_NotALiteral; 5114 } 5115 } 5116 5117 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5118 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5119 .Case("scanf", FST_Scanf) 5120 .Cases("printf", "printf0", FST_Printf) 5121 .Cases("NSString", "CFString", FST_NSString) 5122 .Case("strftime", FST_Strftime) 5123 .Case("strfmon", FST_Strfmon) 5124 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5125 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5126 .Case("os_trace", FST_OSLog) 5127 .Case("os_log", FST_OSLog) 5128 .Default(FST_Unknown); 5129 } 5130 5131 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5132 /// functions) for correct use of format strings. 5133 /// Returns true if a format string has been fully checked. 5134 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5135 ArrayRef<const Expr *> Args, 5136 bool IsCXXMember, 5137 VariadicCallType CallType, 5138 SourceLocation Loc, SourceRange Range, 5139 llvm::SmallBitVector &CheckedVarArgs) { 5140 FormatStringInfo FSI; 5141 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5142 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5143 FSI.FirstDataArg, GetFormatStringType(Format), 5144 CallType, Loc, Range, CheckedVarArgs); 5145 return false; 5146 } 5147 5148 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5149 bool HasVAListArg, unsigned format_idx, 5150 unsigned firstDataArg, FormatStringType Type, 5151 VariadicCallType CallType, 5152 SourceLocation Loc, SourceRange Range, 5153 llvm::SmallBitVector &CheckedVarArgs) { 5154 // CHECK: printf/scanf-like function is called with no format string. 5155 if (format_idx >= Args.size()) { 5156 Diag(Loc, diag::warn_missing_format_string) << Range; 5157 return false; 5158 } 5159 5160 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5161 5162 // CHECK: format string is not a string literal. 5163 // 5164 // Dynamically generated format strings are difficult to 5165 // automatically vet at compile time. Requiring that format strings 5166 // are string literals: (1) permits the checking of format strings by 5167 // the compiler and thereby (2) can practically remove the source of 5168 // many format string exploits. 5169 5170 // Format string can be either ObjC string (e.g. @"%d") or 5171 // C string (e.g. "%d") 5172 // ObjC string uses the same format specifiers as C string, so we can use 5173 // the same format string checking logic for both ObjC and C strings. 5174 UncoveredArgHandler UncoveredArg; 5175 StringLiteralCheckType CT = 5176 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5177 format_idx, firstDataArg, Type, CallType, 5178 /*IsFunctionCall*/ true, CheckedVarArgs, 5179 UncoveredArg, 5180 /*no string offset*/ llvm::APSInt(64, false) = 0); 5181 5182 // Generate a diagnostic where an uncovered argument is detected. 5183 if (UncoveredArg.hasUncoveredArg()) { 5184 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5185 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5186 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5187 } 5188 5189 if (CT != SLCT_NotALiteral) 5190 // Literal format string found, check done! 5191 return CT == SLCT_CheckedLiteral; 5192 5193 // Strftime is particular as it always uses a single 'time' argument, 5194 // so it is safe to pass a non-literal string. 5195 if (Type == FST_Strftime) 5196 return false; 5197 5198 // Do not emit diag when the string param is a macro expansion and the 5199 // format is either NSString or CFString. This is a hack to prevent 5200 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5201 // which are usually used in place of NS and CF string literals. 5202 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5203 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5204 return false; 5205 5206 // If there are no arguments specified, warn with -Wformat-security, otherwise 5207 // warn only with -Wformat-nonliteral. 5208 if (Args.size() == firstDataArg) { 5209 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5210 << OrigFormatExpr->getSourceRange(); 5211 switch (Type) { 5212 default: 5213 break; 5214 case FST_Kprintf: 5215 case FST_FreeBSDKPrintf: 5216 case FST_Printf: 5217 Diag(FormatLoc, diag::note_format_security_fixit) 5218 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5219 break; 5220 case FST_NSString: 5221 Diag(FormatLoc, diag::note_format_security_fixit) 5222 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5223 break; 5224 } 5225 } else { 5226 Diag(FormatLoc, diag::warn_format_nonliteral) 5227 << OrigFormatExpr->getSourceRange(); 5228 } 5229 return false; 5230 } 5231 5232 namespace { 5233 5234 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5235 protected: 5236 Sema &S; 5237 const FormatStringLiteral *FExpr; 5238 const Expr *OrigFormatExpr; 5239 const Sema::FormatStringType FSType; 5240 const unsigned FirstDataArg; 5241 const unsigned NumDataArgs; 5242 const char *Beg; // Start of format string. 5243 const bool HasVAListArg; 5244 ArrayRef<const Expr *> Args; 5245 unsigned FormatIdx; 5246 llvm::SmallBitVector CoveredArgs; 5247 bool usesPositionalArgs = false; 5248 bool atFirstArg = true; 5249 bool inFunctionCall; 5250 Sema::VariadicCallType CallType; 5251 llvm::SmallBitVector &CheckedVarArgs; 5252 UncoveredArgHandler &UncoveredArg; 5253 5254 public: 5255 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5256 const Expr *origFormatExpr, 5257 const Sema::FormatStringType type, unsigned firstDataArg, 5258 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5259 ArrayRef<const Expr *> Args, unsigned formatIdx, 5260 bool inFunctionCall, Sema::VariadicCallType callType, 5261 llvm::SmallBitVector &CheckedVarArgs, 5262 UncoveredArgHandler &UncoveredArg) 5263 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5264 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5265 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5266 inFunctionCall(inFunctionCall), CallType(callType), 5267 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5268 CoveredArgs.resize(numDataArgs); 5269 CoveredArgs.reset(); 5270 } 5271 5272 void DoneProcessing(); 5273 5274 void HandleIncompleteSpecifier(const char *startSpecifier, 5275 unsigned specifierLen) override; 5276 5277 void HandleInvalidLengthModifier( 5278 const analyze_format_string::FormatSpecifier &FS, 5279 const analyze_format_string::ConversionSpecifier &CS, 5280 const char *startSpecifier, unsigned specifierLen, 5281 unsigned DiagID); 5282 5283 void HandleNonStandardLengthModifier( 5284 const analyze_format_string::FormatSpecifier &FS, 5285 const char *startSpecifier, unsigned specifierLen); 5286 5287 void HandleNonStandardConversionSpecifier( 5288 const analyze_format_string::ConversionSpecifier &CS, 5289 const char *startSpecifier, unsigned specifierLen); 5290 5291 void HandlePosition(const char *startPos, unsigned posLen) override; 5292 5293 void HandleInvalidPosition(const char *startSpecifier, 5294 unsigned specifierLen, 5295 analyze_format_string::PositionContext p) override; 5296 5297 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5298 5299 void HandleNullChar(const char *nullCharacter) override; 5300 5301 template <typename Range> 5302 static void 5303 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5304 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5305 bool IsStringLocation, Range StringRange, 5306 ArrayRef<FixItHint> Fixit = None); 5307 5308 protected: 5309 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5310 const char *startSpec, 5311 unsigned specifierLen, 5312 const char *csStart, unsigned csLen); 5313 5314 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5315 const char *startSpec, 5316 unsigned specifierLen); 5317 5318 SourceRange getFormatStringRange(); 5319 CharSourceRange getSpecifierRange(const char *startSpecifier, 5320 unsigned specifierLen); 5321 SourceLocation getLocationOfByte(const char *x); 5322 5323 const Expr *getDataArg(unsigned i) const; 5324 5325 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5326 const analyze_format_string::ConversionSpecifier &CS, 5327 const char *startSpecifier, unsigned specifierLen, 5328 unsigned argIndex); 5329 5330 template <typename Range> 5331 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5332 bool IsStringLocation, Range StringRange, 5333 ArrayRef<FixItHint> Fixit = None); 5334 }; 5335 5336 } // namespace 5337 5338 SourceRange CheckFormatHandler::getFormatStringRange() { 5339 return OrigFormatExpr->getSourceRange(); 5340 } 5341 5342 CharSourceRange CheckFormatHandler:: 5343 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5344 SourceLocation Start = getLocationOfByte(startSpecifier); 5345 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5346 5347 // Advance the end SourceLocation by one due to half-open ranges. 5348 End = End.getLocWithOffset(1); 5349 5350 return CharSourceRange::getCharRange(Start, End); 5351 } 5352 5353 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5354 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5355 S.getLangOpts(), S.Context.getTargetInfo()); 5356 } 5357 5358 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5359 unsigned specifierLen){ 5360 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5361 getLocationOfByte(startSpecifier), 5362 /*IsStringLocation*/true, 5363 getSpecifierRange(startSpecifier, specifierLen)); 5364 } 5365 5366 void CheckFormatHandler::HandleInvalidLengthModifier( 5367 const analyze_format_string::FormatSpecifier &FS, 5368 const analyze_format_string::ConversionSpecifier &CS, 5369 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5370 using namespace analyze_format_string; 5371 5372 const LengthModifier &LM = FS.getLengthModifier(); 5373 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5374 5375 // See if we know how to fix this length modifier. 5376 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5377 if (FixedLM) { 5378 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5379 getLocationOfByte(LM.getStart()), 5380 /*IsStringLocation*/true, 5381 getSpecifierRange(startSpecifier, specifierLen)); 5382 5383 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5384 << FixedLM->toString() 5385 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5386 5387 } else { 5388 FixItHint Hint; 5389 if (DiagID == diag::warn_format_nonsensical_length) 5390 Hint = FixItHint::CreateRemoval(LMRange); 5391 5392 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5393 getLocationOfByte(LM.getStart()), 5394 /*IsStringLocation*/true, 5395 getSpecifierRange(startSpecifier, specifierLen), 5396 Hint); 5397 } 5398 } 5399 5400 void CheckFormatHandler::HandleNonStandardLengthModifier( 5401 const analyze_format_string::FormatSpecifier &FS, 5402 const char *startSpecifier, unsigned specifierLen) { 5403 using namespace analyze_format_string; 5404 5405 const LengthModifier &LM = FS.getLengthModifier(); 5406 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5407 5408 // See if we know how to fix this length modifier. 5409 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5410 if (FixedLM) { 5411 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5412 << LM.toString() << 0, 5413 getLocationOfByte(LM.getStart()), 5414 /*IsStringLocation*/true, 5415 getSpecifierRange(startSpecifier, specifierLen)); 5416 5417 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5418 << FixedLM->toString() 5419 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5420 5421 } else { 5422 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5423 << LM.toString() << 0, 5424 getLocationOfByte(LM.getStart()), 5425 /*IsStringLocation*/true, 5426 getSpecifierRange(startSpecifier, specifierLen)); 5427 } 5428 } 5429 5430 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5431 const analyze_format_string::ConversionSpecifier &CS, 5432 const char *startSpecifier, unsigned specifierLen) { 5433 using namespace analyze_format_string; 5434 5435 // See if we know how to fix this conversion specifier. 5436 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5437 if (FixedCS) { 5438 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5439 << CS.toString() << /*conversion specifier*/1, 5440 getLocationOfByte(CS.getStart()), 5441 /*IsStringLocation*/true, 5442 getSpecifierRange(startSpecifier, specifierLen)); 5443 5444 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5445 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5446 << FixedCS->toString() 5447 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5448 } else { 5449 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5450 << CS.toString() << /*conversion specifier*/1, 5451 getLocationOfByte(CS.getStart()), 5452 /*IsStringLocation*/true, 5453 getSpecifierRange(startSpecifier, specifierLen)); 5454 } 5455 } 5456 5457 void CheckFormatHandler::HandlePosition(const char *startPos, 5458 unsigned posLen) { 5459 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5460 getLocationOfByte(startPos), 5461 /*IsStringLocation*/true, 5462 getSpecifierRange(startPos, posLen)); 5463 } 5464 5465 void 5466 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5467 analyze_format_string::PositionContext p) { 5468 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5469 << (unsigned) p, 5470 getLocationOfByte(startPos), /*IsStringLocation*/true, 5471 getSpecifierRange(startPos, posLen)); 5472 } 5473 5474 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5475 unsigned posLen) { 5476 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5477 getLocationOfByte(startPos), 5478 /*IsStringLocation*/true, 5479 getSpecifierRange(startPos, posLen)); 5480 } 5481 5482 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5483 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5484 // The presence of a null character is likely an error. 5485 EmitFormatDiagnostic( 5486 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5487 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5488 getFormatStringRange()); 5489 } 5490 } 5491 5492 // Note that this may return NULL if there was an error parsing or building 5493 // one of the argument expressions. 5494 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5495 return Args[FirstDataArg + i]; 5496 } 5497 5498 void CheckFormatHandler::DoneProcessing() { 5499 // Does the number of data arguments exceed the number of 5500 // format conversions in the format string? 5501 if (!HasVAListArg) { 5502 // Find any arguments that weren't covered. 5503 CoveredArgs.flip(); 5504 signed notCoveredArg = CoveredArgs.find_first(); 5505 if (notCoveredArg >= 0) { 5506 assert((unsigned)notCoveredArg < NumDataArgs); 5507 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5508 } else { 5509 UncoveredArg.setAllCovered(); 5510 } 5511 } 5512 } 5513 5514 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5515 const Expr *ArgExpr) { 5516 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5517 "Invalid state"); 5518 5519 if (!ArgExpr) 5520 return; 5521 5522 SourceLocation Loc = ArgExpr->getLocStart(); 5523 5524 if (S.getSourceManager().isInSystemMacro(Loc)) 5525 return; 5526 5527 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5528 for (auto E : DiagnosticExprs) 5529 PDiag << E->getSourceRange(); 5530 5531 CheckFormatHandler::EmitFormatDiagnostic( 5532 S, IsFunctionCall, DiagnosticExprs[0], 5533 PDiag, Loc, /*IsStringLocation*/false, 5534 DiagnosticExprs[0]->getSourceRange()); 5535 } 5536 5537 bool 5538 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5539 SourceLocation Loc, 5540 const char *startSpec, 5541 unsigned specifierLen, 5542 const char *csStart, 5543 unsigned csLen) { 5544 bool keepGoing = true; 5545 if (argIndex < NumDataArgs) { 5546 // Consider the argument coverered, even though the specifier doesn't 5547 // make sense. 5548 CoveredArgs.set(argIndex); 5549 } 5550 else { 5551 // If argIndex exceeds the number of data arguments we 5552 // don't issue a warning because that is just a cascade of warnings (and 5553 // they may have intended '%%' anyway). We don't want to continue processing 5554 // the format string after this point, however, as we will like just get 5555 // gibberish when trying to match arguments. 5556 keepGoing = false; 5557 } 5558 5559 StringRef Specifier(csStart, csLen); 5560 5561 // If the specifier in non-printable, it could be the first byte of a UTF-8 5562 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5563 // hex value. 5564 std::string CodePointStr; 5565 if (!llvm::sys::locale::isPrint(*csStart)) { 5566 llvm::UTF32 CodePoint; 5567 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5568 const llvm::UTF8 *E = 5569 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5570 llvm::ConversionResult Result = 5571 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5572 5573 if (Result != llvm::conversionOK) { 5574 unsigned char FirstChar = *csStart; 5575 CodePoint = (llvm::UTF32)FirstChar; 5576 } 5577 5578 llvm::raw_string_ostream OS(CodePointStr); 5579 if (CodePoint < 256) 5580 OS << "\\x" << llvm::format("%02x", CodePoint); 5581 else if (CodePoint <= 0xFFFF) 5582 OS << "\\u" << llvm::format("%04x", CodePoint); 5583 else 5584 OS << "\\U" << llvm::format("%08x", CodePoint); 5585 OS.flush(); 5586 Specifier = CodePointStr; 5587 } 5588 5589 EmitFormatDiagnostic( 5590 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5591 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5592 5593 return keepGoing; 5594 } 5595 5596 void 5597 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5598 const char *startSpec, 5599 unsigned specifierLen) { 5600 EmitFormatDiagnostic( 5601 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5602 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5603 } 5604 5605 bool 5606 CheckFormatHandler::CheckNumArgs( 5607 const analyze_format_string::FormatSpecifier &FS, 5608 const analyze_format_string::ConversionSpecifier &CS, 5609 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5610 5611 if (argIndex >= NumDataArgs) { 5612 PartialDiagnostic PDiag = FS.usesPositionalArg() 5613 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5614 << (argIndex+1) << NumDataArgs) 5615 : S.PDiag(diag::warn_printf_insufficient_data_args); 5616 EmitFormatDiagnostic( 5617 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5618 getSpecifierRange(startSpecifier, specifierLen)); 5619 5620 // Since more arguments than conversion tokens are given, by extension 5621 // all arguments are covered, so mark this as so. 5622 UncoveredArg.setAllCovered(); 5623 return false; 5624 } 5625 return true; 5626 } 5627 5628 template<typename Range> 5629 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5630 SourceLocation Loc, 5631 bool IsStringLocation, 5632 Range StringRange, 5633 ArrayRef<FixItHint> FixIt) { 5634 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5635 Loc, IsStringLocation, StringRange, FixIt); 5636 } 5637 5638 /// \brief If the format string is not within the funcion call, emit a note 5639 /// so that the function call and string are in diagnostic messages. 5640 /// 5641 /// \param InFunctionCall if true, the format string is within the function 5642 /// call and only one diagnostic message will be produced. Otherwise, an 5643 /// extra note will be emitted pointing to location of the format string. 5644 /// 5645 /// \param ArgumentExpr the expression that is passed as the format string 5646 /// argument in the function call. Used for getting locations when two 5647 /// diagnostics are emitted. 5648 /// 5649 /// \param PDiag the callee should already have provided any strings for the 5650 /// diagnostic message. This function only adds locations and fixits 5651 /// to diagnostics. 5652 /// 5653 /// \param Loc primary location for diagnostic. If two diagnostics are 5654 /// required, one will be at Loc and a new SourceLocation will be created for 5655 /// the other one. 5656 /// 5657 /// \param IsStringLocation if true, Loc points to the format string should be 5658 /// used for the note. Otherwise, Loc points to the argument list and will 5659 /// be used with PDiag. 5660 /// 5661 /// \param StringRange some or all of the string to highlight. This is 5662 /// templated so it can accept either a CharSourceRange or a SourceRange. 5663 /// 5664 /// \param FixIt optional fix it hint for the format string. 5665 template <typename Range> 5666 void CheckFormatHandler::EmitFormatDiagnostic( 5667 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5668 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5669 Range StringRange, ArrayRef<FixItHint> FixIt) { 5670 if (InFunctionCall) { 5671 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5672 D << StringRange; 5673 D << FixIt; 5674 } else { 5675 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5676 << ArgumentExpr->getSourceRange(); 5677 5678 const Sema::SemaDiagnosticBuilder &Note = 5679 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5680 diag::note_format_string_defined); 5681 5682 Note << StringRange; 5683 Note << FixIt; 5684 } 5685 } 5686 5687 //===--- CHECK: Printf format string checking ------------------------------===// 5688 5689 namespace { 5690 5691 class CheckPrintfHandler : public CheckFormatHandler { 5692 public: 5693 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5694 const Expr *origFormatExpr, 5695 const Sema::FormatStringType type, unsigned firstDataArg, 5696 unsigned numDataArgs, bool isObjC, const char *beg, 5697 bool hasVAListArg, ArrayRef<const Expr *> Args, 5698 unsigned formatIdx, bool inFunctionCall, 5699 Sema::VariadicCallType CallType, 5700 llvm::SmallBitVector &CheckedVarArgs, 5701 UncoveredArgHandler &UncoveredArg) 5702 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5703 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5704 inFunctionCall, CallType, CheckedVarArgs, 5705 UncoveredArg) {} 5706 5707 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5708 5709 /// Returns true if '%@' specifiers are allowed in the format string. 5710 bool allowsObjCArg() const { 5711 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5712 FSType == Sema::FST_OSTrace; 5713 } 5714 5715 bool HandleInvalidPrintfConversionSpecifier( 5716 const analyze_printf::PrintfSpecifier &FS, 5717 const char *startSpecifier, 5718 unsigned specifierLen) override; 5719 5720 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5721 const char *startSpecifier, 5722 unsigned specifierLen) override; 5723 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5724 const char *StartSpecifier, 5725 unsigned SpecifierLen, 5726 const Expr *E); 5727 5728 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5729 const char *startSpecifier, unsigned specifierLen); 5730 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5731 const analyze_printf::OptionalAmount &Amt, 5732 unsigned type, 5733 const char *startSpecifier, unsigned specifierLen); 5734 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5735 const analyze_printf::OptionalFlag &flag, 5736 const char *startSpecifier, unsigned specifierLen); 5737 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5738 const analyze_printf::OptionalFlag &ignoredFlag, 5739 const analyze_printf::OptionalFlag &flag, 5740 const char *startSpecifier, unsigned specifierLen); 5741 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5742 const Expr *E); 5743 5744 void HandleEmptyObjCModifierFlag(const char *startFlag, 5745 unsigned flagLen) override; 5746 5747 void HandleInvalidObjCModifierFlag(const char *startFlag, 5748 unsigned flagLen) override; 5749 5750 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5751 const char *flagsEnd, 5752 const char *conversionPosition) 5753 override; 5754 }; 5755 5756 } // namespace 5757 5758 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5759 const analyze_printf::PrintfSpecifier &FS, 5760 const char *startSpecifier, 5761 unsigned specifierLen) { 5762 const analyze_printf::PrintfConversionSpecifier &CS = 5763 FS.getConversionSpecifier(); 5764 5765 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5766 getLocationOfByte(CS.getStart()), 5767 startSpecifier, specifierLen, 5768 CS.getStart(), CS.getLength()); 5769 } 5770 5771 bool CheckPrintfHandler::HandleAmount( 5772 const analyze_format_string::OptionalAmount &Amt, 5773 unsigned k, const char *startSpecifier, 5774 unsigned specifierLen) { 5775 if (Amt.hasDataArgument()) { 5776 if (!HasVAListArg) { 5777 unsigned argIndex = Amt.getArgIndex(); 5778 if (argIndex >= NumDataArgs) { 5779 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5780 << k, 5781 getLocationOfByte(Amt.getStart()), 5782 /*IsStringLocation*/true, 5783 getSpecifierRange(startSpecifier, specifierLen)); 5784 // Don't do any more checking. We will just emit 5785 // spurious errors. 5786 return false; 5787 } 5788 5789 // Type check the data argument. It should be an 'int'. 5790 // Although not in conformance with C99, we also allow the argument to be 5791 // an 'unsigned int' as that is a reasonably safe case. GCC also 5792 // doesn't emit a warning for that case. 5793 CoveredArgs.set(argIndex); 5794 const Expr *Arg = getDataArg(argIndex); 5795 if (!Arg) 5796 return false; 5797 5798 QualType T = Arg->getType(); 5799 5800 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5801 assert(AT.isValid()); 5802 5803 if (!AT.matchesType(S.Context, T)) { 5804 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5805 << k << AT.getRepresentativeTypeName(S.Context) 5806 << T << Arg->getSourceRange(), 5807 getLocationOfByte(Amt.getStart()), 5808 /*IsStringLocation*/true, 5809 getSpecifierRange(startSpecifier, specifierLen)); 5810 // Don't do any more checking. We will just emit 5811 // spurious errors. 5812 return false; 5813 } 5814 } 5815 } 5816 return true; 5817 } 5818 5819 void CheckPrintfHandler::HandleInvalidAmount( 5820 const analyze_printf::PrintfSpecifier &FS, 5821 const analyze_printf::OptionalAmount &Amt, 5822 unsigned type, 5823 const char *startSpecifier, 5824 unsigned specifierLen) { 5825 const analyze_printf::PrintfConversionSpecifier &CS = 5826 FS.getConversionSpecifier(); 5827 5828 FixItHint fixit = 5829 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5830 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5831 Amt.getConstantLength())) 5832 : FixItHint(); 5833 5834 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5835 << type << CS.toString(), 5836 getLocationOfByte(Amt.getStart()), 5837 /*IsStringLocation*/true, 5838 getSpecifierRange(startSpecifier, specifierLen), 5839 fixit); 5840 } 5841 5842 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5843 const analyze_printf::OptionalFlag &flag, 5844 const char *startSpecifier, 5845 unsigned specifierLen) { 5846 // Warn about pointless flag with a fixit removal. 5847 const analyze_printf::PrintfConversionSpecifier &CS = 5848 FS.getConversionSpecifier(); 5849 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5850 << flag.toString() << CS.toString(), 5851 getLocationOfByte(flag.getPosition()), 5852 /*IsStringLocation*/true, 5853 getSpecifierRange(startSpecifier, specifierLen), 5854 FixItHint::CreateRemoval( 5855 getSpecifierRange(flag.getPosition(), 1))); 5856 } 5857 5858 void CheckPrintfHandler::HandleIgnoredFlag( 5859 const analyze_printf::PrintfSpecifier &FS, 5860 const analyze_printf::OptionalFlag &ignoredFlag, 5861 const analyze_printf::OptionalFlag &flag, 5862 const char *startSpecifier, 5863 unsigned specifierLen) { 5864 // Warn about ignored flag with a fixit removal. 5865 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5866 << ignoredFlag.toString() << flag.toString(), 5867 getLocationOfByte(ignoredFlag.getPosition()), 5868 /*IsStringLocation*/true, 5869 getSpecifierRange(startSpecifier, specifierLen), 5870 FixItHint::CreateRemoval( 5871 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5872 } 5873 5874 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5875 unsigned flagLen) { 5876 // Warn about an empty flag. 5877 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5878 getLocationOfByte(startFlag), 5879 /*IsStringLocation*/true, 5880 getSpecifierRange(startFlag, flagLen)); 5881 } 5882 5883 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5884 unsigned flagLen) { 5885 // Warn about an invalid flag. 5886 auto Range = getSpecifierRange(startFlag, flagLen); 5887 StringRef flag(startFlag, flagLen); 5888 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5889 getLocationOfByte(startFlag), 5890 /*IsStringLocation*/true, 5891 Range, FixItHint::CreateRemoval(Range)); 5892 } 5893 5894 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5895 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5896 // Warn about using '[...]' without a '@' conversion. 5897 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5898 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5899 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5900 getLocationOfByte(conversionPosition), 5901 /*IsStringLocation*/true, 5902 Range, FixItHint::CreateRemoval(Range)); 5903 } 5904 5905 // Determines if the specified is a C++ class or struct containing 5906 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5907 // "c_str()"). 5908 template<typename MemberKind> 5909 static llvm::SmallPtrSet<MemberKind*, 1> 5910 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5911 const RecordType *RT = Ty->getAs<RecordType>(); 5912 llvm::SmallPtrSet<MemberKind*, 1> Results; 5913 5914 if (!RT) 5915 return Results; 5916 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5917 if (!RD || !RD->getDefinition()) 5918 return Results; 5919 5920 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5921 Sema::LookupMemberName); 5922 R.suppressDiagnostics(); 5923 5924 // We just need to include all members of the right kind turned up by the 5925 // filter, at this point. 5926 if (S.LookupQualifiedName(R, RT->getDecl())) 5927 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5928 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5929 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5930 Results.insert(FK); 5931 } 5932 return Results; 5933 } 5934 5935 /// Check if we could call '.c_str()' on an object. 5936 /// 5937 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5938 /// allow the call, or if it would be ambiguous). 5939 bool Sema::hasCStrMethod(const Expr *E) { 5940 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 5941 5942 MethodSet Results = 5943 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5944 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5945 MI != ME; ++MI) 5946 if ((*MI)->getMinRequiredArguments() == 0) 5947 return true; 5948 return false; 5949 } 5950 5951 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5952 // better diagnostic if so. AT is assumed to be valid. 5953 // Returns true when a c_str() conversion method is found. 5954 bool CheckPrintfHandler::checkForCStrMembers( 5955 const analyze_printf::ArgType &AT, const Expr *E) { 5956 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 5957 5958 MethodSet Results = 5959 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5960 5961 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5962 MI != ME; ++MI) { 5963 const CXXMethodDecl *Method = *MI; 5964 if (Method->getMinRequiredArguments() == 0 && 5965 AT.matchesType(S.Context, Method->getReturnType())) { 5966 // FIXME: Suggest parens if the expression needs them. 5967 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5968 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5969 << "c_str()" 5970 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5971 return true; 5972 } 5973 } 5974 5975 return false; 5976 } 5977 5978 bool 5979 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5980 &FS, 5981 const char *startSpecifier, 5982 unsigned specifierLen) { 5983 using namespace analyze_format_string; 5984 using namespace analyze_printf; 5985 5986 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5987 5988 if (FS.consumesDataArgument()) { 5989 if (atFirstArg) { 5990 atFirstArg = false; 5991 usesPositionalArgs = FS.usesPositionalArg(); 5992 } 5993 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5994 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5995 startSpecifier, specifierLen); 5996 return false; 5997 } 5998 } 5999 6000 // First check if the field width, precision, and conversion specifier 6001 // have matching data arguments. 6002 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 6003 startSpecifier, specifierLen)) { 6004 return false; 6005 } 6006 6007 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 6008 startSpecifier, specifierLen)) { 6009 return false; 6010 } 6011 6012 if (!CS.consumesDataArgument()) { 6013 // FIXME: Technically specifying a precision or field width here 6014 // makes no sense. Worth issuing a warning at some point. 6015 return true; 6016 } 6017 6018 // Consume the argument. 6019 unsigned argIndex = FS.getArgIndex(); 6020 if (argIndex < NumDataArgs) { 6021 // The check to see if the argIndex is valid will come later. 6022 // We set the bit here because we may exit early from this 6023 // function if we encounter some other error. 6024 CoveredArgs.set(argIndex); 6025 } 6026 6027 // FreeBSD kernel extensions. 6028 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 6029 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 6030 // We need at least two arguments. 6031 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 6032 return false; 6033 6034 // Claim the second argument. 6035 CoveredArgs.set(argIndex + 1); 6036 6037 // Type check the first argument (int for %b, pointer for %D) 6038 const Expr *Ex = getDataArg(argIndex); 6039 const analyze_printf::ArgType &AT = 6040 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 6041 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 6042 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 6043 EmitFormatDiagnostic( 6044 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6045 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 6046 << false << Ex->getSourceRange(), 6047 Ex->getLocStart(), /*IsStringLocation*/false, 6048 getSpecifierRange(startSpecifier, specifierLen)); 6049 6050 // Type check the second argument (char * for both %b and %D) 6051 Ex = getDataArg(argIndex + 1); 6052 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 6053 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 6054 EmitFormatDiagnostic( 6055 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6056 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 6057 << false << Ex->getSourceRange(), 6058 Ex->getLocStart(), /*IsStringLocation*/false, 6059 getSpecifierRange(startSpecifier, specifierLen)); 6060 6061 return true; 6062 } 6063 6064 // Check for using an Objective-C specific conversion specifier 6065 // in a non-ObjC literal. 6066 if (!allowsObjCArg() && CS.isObjCArg()) { 6067 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6068 specifierLen); 6069 } 6070 6071 // %P can only be used with os_log. 6072 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 6073 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6074 specifierLen); 6075 } 6076 6077 // %n is not allowed with os_log. 6078 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 6079 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 6080 getLocationOfByte(CS.getStart()), 6081 /*IsStringLocation*/ false, 6082 getSpecifierRange(startSpecifier, specifierLen)); 6083 6084 return true; 6085 } 6086 6087 // Only scalars are allowed for os_trace. 6088 if (FSType == Sema::FST_OSTrace && 6089 (CS.getKind() == ConversionSpecifier::PArg || 6090 CS.getKind() == ConversionSpecifier::sArg || 6091 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 6092 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6093 specifierLen); 6094 } 6095 6096 // Check for use of public/private annotation outside of os_log(). 6097 if (FSType != Sema::FST_OSLog) { 6098 if (FS.isPublic().isSet()) { 6099 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6100 << "public", 6101 getLocationOfByte(FS.isPublic().getPosition()), 6102 /*IsStringLocation*/ false, 6103 getSpecifierRange(startSpecifier, specifierLen)); 6104 } 6105 if (FS.isPrivate().isSet()) { 6106 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6107 << "private", 6108 getLocationOfByte(FS.isPrivate().getPosition()), 6109 /*IsStringLocation*/ false, 6110 getSpecifierRange(startSpecifier, specifierLen)); 6111 } 6112 } 6113 6114 // Check for invalid use of field width 6115 if (!FS.hasValidFieldWidth()) { 6116 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6117 startSpecifier, specifierLen); 6118 } 6119 6120 // Check for invalid use of precision 6121 if (!FS.hasValidPrecision()) { 6122 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6123 startSpecifier, specifierLen); 6124 } 6125 6126 // Precision is mandatory for %P specifier. 6127 if (CS.getKind() == ConversionSpecifier::PArg && 6128 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6129 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6130 getLocationOfByte(startSpecifier), 6131 /*IsStringLocation*/ false, 6132 getSpecifierRange(startSpecifier, specifierLen)); 6133 } 6134 6135 // Check each flag does not conflict with any other component. 6136 if (!FS.hasValidThousandsGroupingPrefix()) 6137 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6138 if (!FS.hasValidLeadingZeros()) 6139 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6140 if (!FS.hasValidPlusPrefix()) 6141 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6142 if (!FS.hasValidSpacePrefix()) 6143 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6144 if (!FS.hasValidAlternativeForm()) 6145 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6146 if (!FS.hasValidLeftJustified()) 6147 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6148 6149 // Check that flags are not ignored by another flag 6150 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6151 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6152 startSpecifier, specifierLen); 6153 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6154 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6155 startSpecifier, specifierLen); 6156 6157 // Check the length modifier is valid with the given conversion specifier. 6158 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6159 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6160 diag::warn_format_nonsensical_length); 6161 else if (!FS.hasStandardLengthModifier()) 6162 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6163 else if (!FS.hasStandardLengthConversionCombination()) 6164 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6165 diag::warn_format_non_standard_conversion_spec); 6166 6167 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6168 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6169 6170 // The remaining checks depend on the data arguments. 6171 if (HasVAListArg) 6172 return true; 6173 6174 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6175 return false; 6176 6177 const Expr *Arg = getDataArg(argIndex); 6178 if (!Arg) 6179 return true; 6180 6181 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6182 } 6183 6184 static bool requiresParensToAddCast(const Expr *E) { 6185 // FIXME: We should have a general way to reason about operator 6186 // precedence and whether parens are actually needed here. 6187 // Take care of a few common cases where they aren't. 6188 const Expr *Inside = E->IgnoreImpCasts(); 6189 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6190 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6191 6192 switch (Inside->getStmtClass()) { 6193 case Stmt::ArraySubscriptExprClass: 6194 case Stmt::CallExprClass: 6195 case Stmt::CharacterLiteralClass: 6196 case Stmt::CXXBoolLiteralExprClass: 6197 case Stmt::DeclRefExprClass: 6198 case Stmt::FloatingLiteralClass: 6199 case Stmt::IntegerLiteralClass: 6200 case Stmt::MemberExprClass: 6201 case Stmt::ObjCArrayLiteralClass: 6202 case Stmt::ObjCBoolLiteralExprClass: 6203 case Stmt::ObjCBoxedExprClass: 6204 case Stmt::ObjCDictionaryLiteralClass: 6205 case Stmt::ObjCEncodeExprClass: 6206 case Stmt::ObjCIvarRefExprClass: 6207 case Stmt::ObjCMessageExprClass: 6208 case Stmt::ObjCPropertyRefExprClass: 6209 case Stmt::ObjCStringLiteralClass: 6210 case Stmt::ObjCSubscriptRefExprClass: 6211 case Stmt::ParenExprClass: 6212 case Stmt::StringLiteralClass: 6213 case Stmt::UnaryOperatorClass: 6214 return false; 6215 default: 6216 return true; 6217 } 6218 } 6219 6220 static std::pair<QualType, StringRef> 6221 shouldNotPrintDirectly(const ASTContext &Context, 6222 QualType IntendedTy, 6223 const Expr *E) { 6224 // Use a 'while' to peel off layers of typedefs. 6225 QualType TyTy = IntendedTy; 6226 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6227 StringRef Name = UserTy->getDecl()->getName(); 6228 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6229 .Case("CFIndex", Context.getNSIntegerType()) 6230 .Case("NSInteger", Context.getNSIntegerType()) 6231 .Case("NSUInteger", Context.getNSUIntegerType()) 6232 .Case("SInt32", Context.IntTy) 6233 .Case("UInt32", Context.UnsignedIntTy) 6234 .Default(QualType()); 6235 6236 if (!CastTy.isNull()) 6237 return std::make_pair(CastTy, Name); 6238 6239 TyTy = UserTy->desugar(); 6240 } 6241 6242 // Strip parens if necessary. 6243 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6244 return shouldNotPrintDirectly(Context, 6245 PE->getSubExpr()->getType(), 6246 PE->getSubExpr()); 6247 6248 // If this is a conditional expression, then its result type is constructed 6249 // via usual arithmetic conversions and thus there might be no necessary 6250 // typedef sugar there. Recurse to operands to check for NSInteger & 6251 // Co. usage condition. 6252 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6253 QualType TrueTy, FalseTy; 6254 StringRef TrueName, FalseName; 6255 6256 std::tie(TrueTy, TrueName) = 6257 shouldNotPrintDirectly(Context, 6258 CO->getTrueExpr()->getType(), 6259 CO->getTrueExpr()); 6260 std::tie(FalseTy, FalseName) = 6261 shouldNotPrintDirectly(Context, 6262 CO->getFalseExpr()->getType(), 6263 CO->getFalseExpr()); 6264 6265 if (TrueTy == FalseTy) 6266 return std::make_pair(TrueTy, TrueName); 6267 else if (TrueTy.isNull()) 6268 return std::make_pair(FalseTy, FalseName); 6269 else if (FalseTy.isNull()) 6270 return std::make_pair(TrueTy, TrueName); 6271 } 6272 6273 return std::make_pair(QualType(), StringRef()); 6274 } 6275 6276 bool 6277 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6278 const char *StartSpecifier, 6279 unsigned SpecifierLen, 6280 const Expr *E) { 6281 using namespace analyze_format_string; 6282 using namespace analyze_printf; 6283 6284 // Now type check the data expression that matches the 6285 // format specifier. 6286 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6287 if (!AT.isValid()) 6288 return true; 6289 6290 QualType ExprTy = E->getType(); 6291 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6292 ExprTy = TET->getUnderlyingExpr()->getType(); 6293 } 6294 6295 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6296 6297 if (match == analyze_printf::ArgType::Match) { 6298 return true; 6299 } 6300 6301 // Look through argument promotions for our error message's reported type. 6302 // This includes the integral and floating promotions, but excludes array 6303 // and function pointer decay; seeing that an argument intended to be a 6304 // string has type 'char [6]' is probably more confusing than 'char *'. 6305 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6306 if (ICE->getCastKind() == CK_IntegralCast || 6307 ICE->getCastKind() == CK_FloatingCast) { 6308 E = ICE->getSubExpr(); 6309 ExprTy = E->getType(); 6310 6311 // Check if we didn't match because of an implicit cast from a 'char' 6312 // or 'short' to an 'int'. This is done because printf is a varargs 6313 // function. 6314 if (ICE->getType() == S.Context.IntTy || 6315 ICE->getType() == S.Context.UnsignedIntTy) { 6316 // All further checking is done on the subexpression. 6317 if (AT.matchesType(S.Context, ExprTy)) 6318 return true; 6319 } 6320 } 6321 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6322 // Special case for 'a', which has type 'int' in C. 6323 // Note, however, that we do /not/ want to treat multibyte constants like 6324 // 'MooV' as characters! This form is deprecated but still exists. 6325 if (ExprTy == S.Context.IntTy) 6326 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6327 ExprTy = S.Context.CharTy; 6328 } 6329 6330 // Look through enums to their underlying type. 6331 bool IsEnum = false; 6332 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6333 ExprTy = EnumTy->getDecl()->getIntegerType(); 6334 IsEnum = true; 6335 } 6336 6337 // %C in an Objective-C context prints a unichar, not a wchar_t. 6338 // If the argument is an integer of some kind, believe the %C and suggest 6339 // a cast instead of changing the conversion specifier. 6340 QualType IntendedTy = ExprTy; 6341 if (isObjCContext() && 6342 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6343 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6344 !ExprTy->isCharType()) { 6345 // 'unichar' is defined as a typedef of unsigned short, but we should 6346 // prefer using the typedef if it is visible. 6347 IntendedTy = S.Context.UnsignedShortTy; 6348 6349 // While we are here, check if the value is an IntegerLiteral that happens 6350 // to be within the valid range. 6351 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6352 const llvm::APInt &V = IL->getValue(); 6353 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6354 return true; 6355 } 6356 6357 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6358 Sema::LookupOrdinaryName); 6359 if (S.LookupName(Result, S.getCurScope())) { 6360 NamedDecl *ND = Result.getFoundDecl(); 6361 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6362 if (TD->getUnderlyingType() == IntendedTy) 6363 IntendedTy = S.Context.getTypedefType(TD); 6364 } 6365 } 6366 } 6367 6368 // Special-case some of Darwin's platform-independence types by suggesting 6369 // casts to primitive types that are known to be large enough. 6370 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6371 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6372 QualType CastTy; 6373 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6374 if (!CastTy.isNull()) { 6375 IntendedTy = CastTy; 6376 ShouldNotPrintDirectly = true; 6377 } 6378 } 6379 6380 // We may be able to offer a FixItHint if it is a supported type. 6381 PrintfSpecifier fixedFS = FS; 6382 bool success = 6383 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6384 6385 if (success) { 6386 // Get the fix string from the fixed format specifier 6387 SmallString<16> buf; 6388 llvm::raw_svector_ostream os(buf); 6389 fixedFS.toString(os); 6390 6391 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6392 6393 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6394 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6395 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6396 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6397 } 6398 // In this case, the specifier is wrong and should be changed to match 6399 // the argument. 6400 EmitFormatDiagnostic(S.PDiag(diag) 6401 << AT.getRepresentativeTypeName(S.Context) 6402 << IntendedTy << IsEnum << E->getSourceRange(), 6403 E->getLocStart(), 6404 /*IsStringLocation*/ false, SpecRange, 6405 FixItHint::CreateReplacement(SpecRange, os.str())); 6406 } else { 6407 // The canonical type for formatting this value is different from the 6408 // actual type of the expression. (This occurs, for example, with Darwin's 6409 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6410 // should be printed as 'long' for 64-bit compatibility.) 6411 // Rather than emitting a normal format/argument mismatch, we want to 6412 // add a cast to the recommended type (and correct the format string 6413 // if necessary). 6414 SmallString<16> CastBuf; 6415 llvm::raw_svector_ostream CastFix(CastBuf); 6416 CastFix << "("; 6417 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6418 CastFix << ")"; 6419 6420 SmallVector<FixItHint,4> Hints; 6421 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 6422 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6423 6424 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6425 // If there's already a cast present, just replace it. 6426 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6427 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6428 6429 } else if (!requiresParensToAddCast(E)) { 6430 // If the expression has high enough precedence, 6431 // just write the C-style cast. 6432 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6433 CastFix.str())); 6434 } else { 6435 // Otherwise, add parens around the expression as well as the cast. 6436 CastFix << "("; 6437 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6438 CastFix.str())); 6439 6440 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6441 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6442 } 6443 6444 if (ShouldNotPrintDirectly) { 6445 // The expression has a type that should not be printed directly. 6446 // We extract the name from the typedef because we don't want to show 6447 // the underlying type in the diagnostic. 6448 StringRef Name; 6449 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6450 Name = TypedefTy->getDecl()->getName(); 6451 else 6452 Name = CastTyName; 6453 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6454 << Name << IntendedTy << IsEnum 6455 << E->getSourceRange(), 6456 E->getLocStart(), /*IsStringLocation=*/false, 6457 SpecRange, Hints); 6458 } else { 6459 // In this case, the expression could be printed using a different 6460 // specifier, but we've decided that the specifier is probably correct 6461 // and we should cast instead. Just use the normal warning message. 6462 EmitFormatDiagnostic( 6463 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6464 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6465 << E->getSourceRange(), 6466 E->getLocStart(), /*IsStringLocation*/false, 6467 SpecRange, Hints); 6468 } 6469 } 6470 } else { 6471 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6472 SpecifierLen); 6473 // Since the warning for passing non-POD types to variadic functions 6474 // was deferred until now, we emit a warning for non-POD 6475 // arguments here. 6476 switch (S.isValidVarArgType(ExprTy)) { 6477 case Sema::VAK_Valid: 6478 case Sema::VAK_ValidInCXX11: { 6479 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6480 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6481 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6482 } 6483 6484 EmitFormatDiagnostic( 6485 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6486 << IsEnum << CSR << E->getSourceRange(), 6487 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6488 break; 6489 } 6490 case Sema::VAK_Undefined: 6491 case Sema::VAK_MSVCUndefined: 6492 EmitFormatDiagnostic( 6493 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6494 << S.getLangOpts().CPlusPlus11 6495 << ExprTy 6496 << CallType 6497 << AT.getRepresentativeTypeName(S.Context) 6498 << CSR 6499 << E->getSourceRange(), 6500 E->getLocStart(), /*IsStringLocation*/false, CSR); 6501 checkForCStrMembers(AT, E); 6502 break; 6503 6504 case Sema::VAK_Invalid: 6505 if (ExprTy->isObjCObjectType()) 6506 EmitFormatDiagnostic( 6507 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6508 << S.getLangOpts().CPlusPlus11 6509 << ExprTy 6510 << CallType 6511 << AT.getRepresentativeTypeName(S.Context) 6512 << CSR 6513 << E->getSourceRange(), 6514 E->getLocStart(), /*IsStringLocation*/false, CSR); 6515 else 6516 // FIXME: If this is an initializer list, suggest removing the braces 6517 // or inserting a cast to the target type. 6518 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6519 << isa<InitListExpr>(E) << ExprTy << CallType 6520 << AT.getRepresentativeTypeName(S.Context) 6521 << E->getSourceRange(); 6522 break; 6523 } 6524 6525 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6526 "format string specifier index out of range"); 6527 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6528 } 6529 6530 return true; 6531 } 6532 6533 //===--- CHECK: Scanf format string checking ------------------------------===// 6534 6535 namespace { 6536 6537 class CheckScanfHandler : public CheckFormatHandler { 6538 public: 6539 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6540 const Expr *origFormatExpr, Sema::FormatStringType type, 6541 unsigned firstDataArg, unsigned numDataArgs, 6542 const char *beg, bool hasVAListArg, 6543 ArrayRef<const Expr *> Args, unsigned formatIdx, 6544 bool inFunctionCall, Sema::VariadicCallType CallType, 6545 llvm::SmallBitVector &CheckedVarArgs, 6546 UncoveredArgHandler &UncoveredArg) 6547 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6548 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6549 inFunctionCall, CallType, CheckedVarArgs, 6550 UncoveredArg) {} 6551 6552 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6553 const char *startSpecifier, 6554 unsigned specifierLen) override; 6555 6556 bool HandleInvalidScanfConversionSpecifier( 6557 const analyze_scanf::ScanfSpecifier &FS, 6558 const char *startSpecifier, 6559 unsigned specifierLen) override; 6560 6561 void HandleIncompleteScanList(const char *start, const char *end) override; 6562 }; 6563 6564 } // namespace 6565 6566 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6567 const char *end) { 6568 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6569 getLocationOfByte(end), /*IsStringLocation*/true, 6570 getSpecifierRange(start, end - start)); 6571 } 6572 6573 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6574 const analyze_scanf::ScanfSpecifier &FS, 6575 const char *startSpecifier, 6576 unsigned specifierLen) { 6577 const analyze_scanf::ScanfConversionSpecifier &CS = 6578 FS.getConversionSpecifier(); 6579 6580 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6581 getLocationOfByte(CS.getStart()), 6582 startSpecifier, specifierLen, 6583 CS.getStart(), CS.getLength()); 6584 } 6585 6586 bool CheckScanfHandler::HandleScanfSpecifier( 6587 const analyze_scanf::ScanfSpecifier &FS, 6588 const char *startSpecifier, 6589 unsigned specifierLen) { 6590 using namespace analyze_scanf; 6591 using namespace analyze_format_string; 6592 6593 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6594 6595 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6596 // be used to decide if we are using positional arguments consistently. 6597 if (FS.consumesDataArgument()) { 6598 if (atFirstArg) { 6599 atFirstArg = false; 6600 usesPositionalArgs = FS.usesPositionalArg(); 6601 } 6602 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6603 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6604 startSpecifier, specifierLen); 6605 return false; 6606 } 6607 } 6608 6609 // Check if the field with is non-zero. 6610 const OptionalAmount &Amt = FS.getFieldWidth(); 6611 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6612 if (Amt.getConstantAmount() == 0) { 6613 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6614 Amt.getConstantLength()); 6615 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6616 getLocationOfByte(Amt.getStart()), 6617 /*IsStringLocation*/true, R, 6618 FixItHint::CreateRemoval(R)); 6619 } 6620 } 6621 6622 if (!FS.consumesDataArgument()) { 6623 // FIXME: Technically specifying a precision or field width here 6624 // makes no sense. Worth issuing a warning at some point. 6625 return true; 6626 } 6627 6628 // Consume the argument. 6629 unsigned argIndex = FS.getArgIndex(); 6630 if (argIndex < NumDataArgs) { 6631 // The check to see if the argIndex is valid will come later. 6632 // We set the bit here because we may exit early from this 6633 // function if we encounter some other error. 6634 CoveredArgs.set(argIndex); 6635 } 6636 6637 // Check the length modifier is valid with the given conversion specifier. 6638 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6639 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6640 diag::warn_format_nonsensical_length); 6641 else if (!FS.hasStandardLengthModifier()) 6642 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6643 else if (!FS.hasStandardLengthConversionCombination()) 6644 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6645 diag::warn_format_non_standard_conversion_spec); 6646 6647 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6648 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6649 6650 // The remaining checks depend on the data arguments. 6651 if (HasVAListArg) 6652 return true; 6653 6654 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6655 return false; 6656 6657 // Check that the argument type matches the format specifier. 6658 const Expr *Ex = getDataArg(argIndex); 6659 if (!Ex) 6660 return true; 6661 6662 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6663 6664 if (!AT.isValid()) { 6665 return true; 6666 } 6667 6668 analyze_format_string::ArgType::MatchKind match = 6669 AT.matchesType(S.Context, Ex->getType()); 6670 if (match == analyze_format_string::ArgType::Match) { 6671 return true; 6672 } 6673 6674 ScanfSpecifier fixedFS = FS; 6675 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6676 S.getLangOpts(), S.Context); 6677 6678 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6679 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6680 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6681 } 6682 6683 if (success) { 6684 // Get the fix string from the fixed format specifier. 6685 SmallString<128> buf; 6686 llvm::raw_svector_ostream os(buf); 6687 fixedFS.toString(os); 6688 6689 EmitFormatDiagnostic( 6690 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6691 << Ex->getType() << false << Ex->getSourceRange(), 6692 Ex->getLocStart(), 6693 /*IsStringLocation*/ false, 6694 getSpecifierRange(startSpecifier, specifierLen), 6695 FixItHint::CreateReplacement( 6696 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6697 } else { 6698 EmitFormatDiagnostic(S.PDiag(diag) 6699 << AT.getRepresentativeTypeName(S.Context) 6700 << Ex->getType() << false << Ex->getSourceRange(), 6701 Ex->getLocStart(), 6702 /*IsStringLocation*/ false, 6703 getSpecifierRange(startSpecifier, specifierLen)); 6704 } 6705 6706 return true; 6707 } 6708 6709 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6710 const Expr *OrigFormatExpr, 6711 ArrayRef<const Expr *> Args, 6712 bool HasVAListArg, unsigned format_idx, 6713 unsigned firstDataArg, 6714 Sema::FormatStringType Type, 6715 bool inFunctionCall, 6716 Sema::VariadicCallType CallType, 6717 llvm::SmallBitVector &CheckedVarArgs, 6718 UncoveredArgHandler &UncoveredArg) { 6719 // CHECK: is the format string a wide literal? 6720 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6721 CheckFormatHandler::EmitFormatDiagnostic( 6722 S, inFunctionCall, Args[format_idx], 6723 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6724 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6725 return; 6726 } 6727 6728 // Str - The format string. NOTE: this is NOT null-terminated! 6729 StringRef StrRef = FExpr->getString(); 6730 const char *Str = StrRef.data(); 6731 // Account for cases where the string literal is truncated in a declaration. 6732 const ConstantArrayType *T = 6733 S.Context.getAsConstantArrayType(FExpr->getType()); 6734 assert(T && "String literal not of constant array type!"); 6735 size_t TypeSize = T->getSize().getZExtValue(); 6736 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6737 const unsigned numDataArgs = Args.size() - firstDataArg; 6738 6739 // Emit a warning if the string literal is truncated and does not contain an 6740 // embedded null character. 6741 if (TypeSize <= StrRef.size() && 6742 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6743 CheckFormatHandler::EmitFormatDiagnostic( 6744 S, inFunctionCall, Args[format_idx], 6745 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6746 FExpr->getLocStart(), 6747 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6748 return; 6749 } 6750 6751 // CHECK: empty format string? 6752 if (StrLen == 0 && numDataArgs > 0) { 6753 CheckFormatHandler::EmitFormatDiagnostic( 6754 S, inFunctionCall, Args[format_idx], 6755 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6756 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6757 return; 6758 } 6759 6760 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6761 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6762 Type == Sema::FST_OSTrace) { 6763 CheckPrintfHandler H( 6764 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6765 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6766 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6767 CheckedVarArgs, UncoveredArg); 6768 6769 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6770 S.getLangOpts(), 6771 S.Context.getTargetInfo(), 6772 Type == Sema::FST_FreeBSDKPrintf)) 6773 H.DoneProcessing(); 6774 } else if (Type == Sema::FST_Scanf) { 6775 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6776 numDataArgs, Str, HasVAListArg, Args, format_idx, 6777 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6778 6779 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6780 S.getLangOpts(), 6781 S.Context.getTargetInfo())) 6782 H.DoneProcessing(); 6783 } // TODO: handle other formats 6784 } 6785 6786 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6787 // Str - The format string. NOTE: this is NOT null-terminated! 6788 StringRef StrRef = FExpr->getString(); 6789 const char *Str = StrRef.data(); 6790 // Account for cases where the string literal is truncated in a declaration. 6791 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6792 assert(T && "String literal not of constant array type!"); 6793 size_t TypeSize = T->getSize().getZExtValue(); 6794 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6795 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6796 getLangOpts(), 6797 Context.getTargetInfo()); 6798 } 6799 6800 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6801 6802 // Returns the related absolute value function that is larger, of 0 if one 6803 // does not exist. 6804 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6805 switch (AbsFunction) { 6806 default: 6807 return 0; 6808 6809 case Builtin::BI__builtin_abs: 6810 return Builtin::BI__builtin_labs; 6811 case Builtin::BI__builtin_labs: 6812 return Builtin::BI__builtin_llabs; 6813 case Builtin::BI__builtin_llabs: 6814 return 0; 6815 6816 case Builtin::BI__builtin_fabsf: 6817 return Builtin::BI__builtin_fabs; 6818 case Builtin::BI__builtin_fabs: 6819 return Builtin::BI__builtin_fabsl; 6820 case Builtin::BI__builtin_fabsl: 6821 return 0; 6822 6823 case Builtin::BI__builtin_cabsf: 6824 return Builtin::BI__builtin_cabs; 6825 case Builtin::BI__builtin_cabs: 6826 return Builtin::BI__builtin_cabsl; 6827 case Builtin::BI__builtin_cabsl: 6828 return 0; 6829 6830 case Builtin::BIabs: 6831 return Builtin::BIlabs; 6832 case Builtin::BIlabs: 6833 return Builtin::BIllabs; 6834 case Builtin::BIllabs: 6835 return 0; 6836 6837 case Builtin::BIfabsf: 6838 return Builtin::BIfabs; 6839 case Builtin::BIfabs: 6840 return Builtin::BIfabsl; 6841 case Builtin::BIfabsl: 6842 return 0; 6843 6844 case Builtin::BIcabsf: 6845 return Builtin::BIcabs; 6846 case Builtin::BIcabs: 6847 return Builtin::BIcabsl; 6848 case Builtin::BIcabsl: 6849 return 0; 6850 } 6851 } 6852 6853 // Returns the argument type of the absolute value function. 6854 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6855 unsigned AbsType) { 6856 if (AbsType == 0) 6857 return QualType(); 6858 6859 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6860 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6861 if (Error != ASTContext::GE_None) 6862 return QualType(); 6863 6864 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6865 if (!FT) 6866 return QualType(); 6867 6868 if (FT->getNumParams() != 1) 6869 return QualType(); 6870 6871 return FT->getParamType(0); 6872 } 6873 6874 // Returns the best absolute value function, or zero, based on type and 6875 // current absolute value function. 6876 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6877 unsigned AbsFunctionKind) { 6878 unsigned BestKind = 0; 6879 uint64_t ArgSize = Context.getTypeSize(ArgType); 6880 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6881 Kind = getLargerAbsoluteValueFunction(Kind)) { 6882 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6883 if (Context.getTypeSize(ParamType) >= ArgSize) { 6884 if (BestKind == 0) 6885 BestKind = Kind; 6886 else if (Context.hasSameType(ParamType, ArgType)) { 6887 BestKind = Kind; 6888 break; 6889 } 6890 } 6891 } 6892 return BestKind; 6893 } 6894 6895 enum AbsoluteValueKind { 6896 AVK_Integer, 6897 AVK_Floating, 6898 AVK_Complex 6899 }; 6900 6901 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6902 if (T->isIntegralOrEnumerationType()) 6903 return AVK_Integer; 6904 if (T->isRealFloatingType()) 6905 return AVK_Floating; 6906 if (T->isAnyComplexType()) 6907 return AVK_Complex; 6908 6909 llvm_unreachable("Type not integer, floating, or complex"); 6910 } 6911 6912 // Changes the absolute value function to a different type. Preserves whether 6913 // the function is a builtin. 6914 static unsigned changeAbsFunction(unsigned AbsKind, 6915 AbsoluteValueKind ValueKind) { 6916 switch (ValueKind) { 6917 case AVK_Integer: 6918 switch (AbsKind) { 6919 default: 6920 return 0; 6921 case Builtin::BI__builtin_fabsf: 6922 case Builtin::BI__builtin_fabs: 6923 case Builtin::BI__builtin_fabsl: 6924 case Builtin::BI__builtin_cabsf: 6925 case Builtin::BI__builtin_cabs: 6926 case Builtin::BI__builtin_cabsl: 6927 return Builtin::BI__builtin_abs; 6928 case Builtin::BIfabsf: 6929 case Builtin::BIfabs: 6930 case Builtin::BIfabsl: 6931 case Builtin::BIcabsf: 6932 case Builtin::BIcabs: 6933 case Builtin::BIcabsl: 6934 return Builtin::BIabs; 6935 } 6936 case AVK_Floating: 6937 switch (AbsKind) { 6938 default: 6939 return 0; 6940 case Builtin::BI__builtin_abs: 6941 case Builtin::BI__builtin_labs: 6942 case Builtin::BI__builtin_llabs: 6943 case Builtin::BI__builtin_cabsf: 6944 case Builtin::BI__builtin_cabs: 6945 case Builtin::BI__builtin_cabsl: 6946 return Builtin::BI__builtin_fabsf; 6947 case Builtin::BIabs: 6948 case Builtin::BIlabs: 6949 case Builtin::BIllabs: 6950 case Builtin::BIcabsf: 6951 case Builtin::BIcabs: 6952 case Builtin::BIcabsl: 6953 return Builtin::BIfabsf; 6954 } 6955 case AVK_Complex: 6956 switch (AbsKind) { 6957 default: 6958 return 0; 6959 case Builtin::BI__builtin_abs: 6960 case Builtin::BI__builtin_labs: 6961 case Builtin::BI__builtin_llabs: 6962 case Builtin::BI__builtin_fabsf: 6963 case Builtin::BI__builtin_fabs: 6964 case Builtin::BI__builtin_fabsl: 6965 return Builtin::BI__builtin_cabsf; 6966 case Builtin::BIabs: 6967 case Builtin::BIlabs: 6968 case Builtin::BIllabs: 6969 case Builtin::BIfabsf: 6970 case Builtin::BIfabs: 6971 case Builtin::BIfabsl: 6972 return Builtin::BIcabsf; 6973 } 6974 } 6975 llvm_unreachable("Unable to convert function"); 6976 } 6977 6978 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6979 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6980 if (!FnInfo) 6981 return 0; 6982 6983 switch (FDecl->getBuiltinID()) { 6984 default: 6985 return 0; 6986 case Builtin::BI__builtin_abs: 6987 case Builtin::BI__builtin_fabs: 6988 case Builtin::BI__builtin_fabsf: 6989 case Builtin::BI__builtin_fabsl: 6990 case Builtin::BI__builtin_labs: 6991 case Builtin::BI__builtin_llabs: 6992 case Builtin::BI__builtin_cabs: 6993 case Builtin::BI__builtin_cabsf: 6994 case Builtin::BI__builtin_cabsl: 6995 case Builtin::BIabs: 6996 case Builtin::BIlabs: 6997 case Builtin::BIllabs: 6998 case Builtin::BIfabs: 6999 case Builtin::BIfabsf: 7000 case Builtin::BIfabsl: 7001 case Builtin::BIcabs: 7002 case Builtin::BIcabsf: 7003 case Builtin::BIcabsl: 7004 return FDecl->getBuiltinID(); 7005 } 7006 llvm_unreachable("Unknown Builtin type"); 7007 } 7008 7009 // If the replacement is valid, emit a note with replacement function. 7010 // Additionally, suggest including the proper header if not already included. 7011 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 7012 unsigned AbsKind, QualType ArgType) { 7013 bool EmitHeaderHint = true; 7014 const char *HeaderName = nullptr; 7015 const char *FunctionName = nullptr; 7016 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 7017 FunctionName = "std::abs"; 7018 if (ArgType->isIntegralOrEnumerationType()) { 7019 HeaderName = "cstdlib"; 7020 } else if (ArgType->isRealFloatingType()) { 7021 HeaderName = "cmath"; 7022 } else { 7023 llvm_unreachable("Invalid Type"); 7024 } 7025 7026 // Lookup all std::abs 7027 if (NamespaceDecl *Std = S.getStdNamespace()) { 7028 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 7029 R.suppressDiagnostics(); 7030 S.LookupQualifiedName(R, Std); 7031 7032 for (const auto *I : R) { 7033 const FunctionDecl *FDecl = nullptr; 7034 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 7035 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 7036 } else { 7037 FDecl = dyn_cast<FunctionDecl>(I); 7038 } 7039 if (!FDecl) 7040 continue; 7041 7042 // Found std::abs(), check that they are the right ones. 7043 if (FDecl->getNumParams() != 1) 7044 continue; 7045 7046 // Check that the parameter type can handle the argument. 7047 QualType ParamType = FDecl->getParamDecl(0)->getType(); 7048 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 7049 S.Context.getTypeSize(ArgType) <= 7050 S.Context.getTypeSize(ParamType)) { 7051 // Found a function, don't need the header hint. 7052 EmitHeaderHint = false; 7053 break; 7054 } 7055 } 7056 } 7057 } else { 7058 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 7059 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 7060 7061 if (HeaderName) { 7062 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 7063 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 7064 R.suppressDiagnostics(); 7065 S.LookupName(R, S.getCurScope()); 7066 7067 if (R.isSingleResult()) { 7068 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 7069 if (FD && FD->getBuiltinID() == AbsKind) { 7070 EmitHeaderHint = false; 7071 } else { 7072 return; 7073 } 7074 } else if (!R.empty()) { 7075 return; 7076 } 7077 } 7078 } 7079 7080 S.Diag(Loc, diag::note_replace_abs_function) 7081 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 7082 7083 if (!HeaderName) 7084 return; 7085 7086 if (!EmitHeaderHint) 7087 return; 7088 7089 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 7090 << FunctionName; 7091 } 7092 7093 template <std::size_t StrLen> 7094 static bool IsStdFunction(const FunctionDecl *FDecl, 7095 const char (&Str)[StrLen]) { 7096 if (!FDecl) 7097 return false; 7098 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 7099 return false; 7100 if (!FDecl->isInStdNamespace()) 7101 return false; 7102 7103 return true; 7104 } 7105 7106 // Warn when using the wrong abs() function. 7107 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7108 const FunctionDecl *FDecl) { 7109 if (Call->getNumArgs() != 1) 7110 return; 7111 7112 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7113 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7114 if (AbsKind == 0 && !IsStdAbs) 7115 return; 7116 7117 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7118 QualType ParamType = Call->getArg(0)->getType(); 7119 7120 // Unsigned types cannot be negative. Suggest removing the absolute value 7121 // function call. 7122 if (ArgType->isUnsignedIntegerType()) { 7123 const char *FunctionName = 7124 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7125 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7126 Diag(Call->getExprLoc(), diag::note_remove_abs) 7127 << FunctionName 7128 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7129 return; 7130 } 7131 7132 // Taking the absolute value of a pointer is very suspicious, they probably 7133 // wanted to index into an array, dereference a pointer, call a function, etc. 7134 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7135 unsigned DiagType = 0; 7136 if (ArgType->isFunctionType()) 7137 DiagType = 1; 7138 else if (ArgType->isArrayType()) 7139 DiagType = 2; 7140 7141 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7142 return; 7143 } 7144 7145 // std::abs has overloads which prevent most of the absolute value problems 7146 // from occurring. 7147 if (IsStdAbs) 7148 return; 7149 7150 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7151 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7152 7153 // The argument and parameter are the same kind. Check if they are the right 7154 // size. 7155 if (ArgValueKind == ParamValueKind) { 7156 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7157 return; 7158 7159 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7160 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7161 << FDecl << ArgType << ParamType; 7162 7163 if (NewAbsKind == 0) 7164 return; 7165 7166 emitReplacement(*this, Call->getExprLoc(), 7167 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7168 return; 7169 } 7170 7171 // ArgValueKind != ParamValueKind 7172 // The wrong type of absolute value function was used. Attempt to find the 7173 // proper one. 7174 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7175 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7176 if (NewAbsKind == 0) 7177 return; 7178 7179 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7180 << FDecl << ParamValueKind << ArgValueKind; 7181 7182 emitReplacement(*this, Call->getExprLoc(), 7183 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7184 } 7185 7186 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7187 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7188 const FunctionDecl *FDecl) { 7189 if (!Call || !FDecl) return; 7190 7191 // Ignore template specializations and macros. 7192 if (inTemplateInstantiation()) return; 7193 if (Call->getExprLoc().isMacroID()) return; 7194 7195 // Only care about the one template argument, two function parameter std::max 7196 if (Call->getNumArgs() != 2) return; 7197 if (!IsStdFunction(FDecl, "max")) return; 7198 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7199 if (!ArgList) return; 7200 if (ArgList->size() != 1) return; 7201 7202 // Check that template type argument is unsigned integer. 7203 const auto& TA = ArgList->get(0); 7204 if (TA.getKind() != TemplateArgument::Type) return; 7205 QualType ArgType = TA.getAsType(); 7206 if (!ArgType->isUnsignedIntegerType()) return; 7207 7208 // See if either argument is a literal zero. 7209 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7210 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7211 if (!MTE) return false; 7212 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7213 if (!Num) return false; 7214 if (Num->getValue() != 0) return false; 7215 return true; 7216 }; 7217 7218 const Expr *FirstArg = Call->getArg(0); 7219 const Expr *SecondArg = Call->getArg(1); 7220 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7221 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7222 7223 // Only warn when exactly one argument is zero. 7224 if (IsFirstArgZero == IsSecondArgZero) return; 7225 7226 SourceRange FirstRange = FirstArg->getSourceRange(); 7227 SourceRange SecondRange = SecondArg->getSourceRange(); 7228 7229 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7230 7231 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7232 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7233 7234 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7235 SourceRange RemovalRange; 7236 if (IsFirstArgZero) { 7237 RemovalRange = SourceRange(FirstRange.getBegin(), 7238 SecondRange.getBegin().getLocWithOffset(-1)); 7239 } else { 7240 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7241 SecondRange.getEnd()); 7242 } 7243 7244 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7245 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7246 << FixItHint::CreateRemoval(RemovalRange); 7247 } 7248 7249 //===--- CHECK: Standard memory functions ---------------------------------===// 7250 7251 /// \brief Takes the expression passed to the size_t parameter of functions 7252 /// such as memcmp, strncat, etc and warns if it's a comparison. 7253 /// 7254 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7255 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7256 IdentifierInfo *FnName, 7257 SourceLocation FnLoc, 7258 SourceLocation RParenLoc) { 7259 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7260 if (!Size) 7261 return false; 7262 7263 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 7264 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 7265 return false; 7266 7267 SourceRange SizeRange = Size->getSourceRange(); 7268 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7269 << SizeRange << FnName; 7270 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7271 << FnName << FixItHint::CreateInsertion( 7272 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7273 << FixItHint::CreateRemoval(RParenLoc); 7274 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7275 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7276 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7277 ")"); 7278 7279 return true; 7280 } 7281 7282 /// \brief Determine whether the given type is or contains a dynamic class type 7283 /// (e.g., whether it has a vtable). 7284 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7285 bool &IsContained) { 7286 // Look through array types while ignoring qualifiers. 7287 const Type *Ty = T->getBaseElementTypeUnsafe(); 7288 IsContained = false; 7289 7290 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7291 RD = RD ? RD->getDefinition() : nullptr; 7292 if (!RD || RD->isInvalidDecl()) 7293 return nullptr; 7294 7295 if (RD->isDynamicClass()) 7296 return RD; 7297 7298 // Check all the fields. If any bases were dynamic, the class is dynamic. 7299 // It's impossible for a class to transitively contain itself by value, so 7300 // infinite recursion is impossible. 7301 for (auto *FD : RD->fields()) { 7302 bool SubContained; 7303 if (const CXXRecordDecl *ContainedRD = 7304 getContainedDynamicClass(FD->getType(), SubContained)) { 7305 IsContained = true; 7306 return ContainedRD; 7307 } 7308 } 7309 7310 return nullptr; 7311 } 7312 7313 /// \brief If E is a sizeof expression, returns its argument expression, 7314 /// otherwise returns NULL. 7315 static const Expr *getSizeOfExprArg(const Expr *E) { 7316 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7317 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7318 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType()) 7319 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7320 7321 return nullptr; 7322 } 7323 7324 /// \brief If E is a sizeof expression, returns its argument type. 7325 static QualType getSizeOfArgType(const Expr *E) { 7326 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7327 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7328 if (SizeOf->getKind() == UETT_SizeOf) 7329 return SizeOf->getTypeOfArgument(); 7330 7331 return QualType(); 7332 } 7333 7334 /// \brief Check for dangerous or invalid arguments to memset(). 7335 /// 7336 /// This issues warnings on known problematic, dangerous or unspecified 7337 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7338 /// function calls. 7339 /// 7340 /// \param Call The call expression to diagnose. 7341 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7342 unsigned BId, 7343 IdentifierInfo *FnName) { 7344 assert(BId != 0); 7345 7346 // It is possible to have a non-standard definition of memset. Validate 7347 // we have enough arguments, and if not, abort further checking. 7348 unsigned ExpectedNumArgs = 7349 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7350 if (Call->getNumArgs() < ExpectedNumArgs) 7351 return; 7352 7353 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7354 BId == Builtin::BIstrndup ? 1 : 2); 7355 unsigned LenArg = 7356 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7357 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7358 7359 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7360 Call->getLocStart(), Call->getRParenLoc())) 7361 return; 7362 7363 // We have special checking when the length is a sizeof expression. 7364 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7365 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7366 llvm::FoldingSetNodeID SizeOfArgID; 7367 7368 // Although widely used, 'bzero' is not a standard function. Be more strict 7369 // with the argument types before allowing diagnostics and only allow the 7370 // form bzero(ptr, sizeof(...)). 7371 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7372 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7373 return; 7374 7375 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7376 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7377 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7378 7379 QualType DestTy = Dest->getType(); 7380 QualType PointeeTy; 7381 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7382 PointeeTy = DestPtrTy->getPointeeType(); 7383 7384 // Never warn about void type pointers. This can be used to suppress 7385 // false positives. 7386 if (PointeeTy->isVoidType()) 7387 continue; 7388 7389 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7390 // actually comparing the expressions for equality. Because computing the 7391 // expression IDs can be expensive, we only do this if the diagnostic is 7392 // enabled. 7393 if (SizeOfArg && 7394 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7395 SizeOfArg->getExprLoc())) { 7396 // We only compute IDs for expressions if the warning is enabled, and 7397 // cache the sizeof arg's ID. 7398 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7399 SizeOfArg->Profile(SizeOfArgID, Context, true); 7400 llvm::FoldingSetNodeID DestID; 7401 Dest->Profile(DestID, Context, true); 7402 if (DestID == SizeOfArgID) { 7403 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7404 // over sizeof(src) as well. 7405 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7406 StringRef ReadableName = FnName->getName(); 7407 7408 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7409 if (UnaryOp->getOpcode() == UO_AddrOf) 7410 ActionIdx = 1; // If its an address-of operator, just remove it. 7411 if (!PointeeTy->isIncompleteType() && 7412 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7413 ActionIdx = 2; // If the pointee's size is sizeof(char), 7414 // suggest an explicit length. 7415 7416 // If the function is defined as a builtin macro, do not show macro 7417 // expansion. 7418 SourceLocation SL = SizeOfArg->getExprLoc(); 7419 SourceRange DSR = Dest->getSourceRange(); 7420 SourceRange SSR = SizeOfArg->getSourceRange(); 7421 SourceManager &SM = getSourceManager(); 7422 7423 if (SM.isMacroArgExpansion(SL)) { 7424 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7425 SL = SM.getSpellingLoc(SL); 7426 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7427 SM.getSpellingLoc(DSR.getEnd())); 7428 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7429 SM.getSpellingLoc(SSR.getEnd())); 7430 } 7431 7432 DiagRuntimeBehavior(SL, SizeOfArg, 7433 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7434 << ReadableName 7435 << PointeeTy 7436 << DestTy 7437 << DSR 7438 << SSR); 7439 DiagRuntimeBehavior(SL, SizeOfArg, 7440 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7441 << ActionIdx 7442 << SSR); 7443 7444 break; 7445 } 7446 } 7447 7448 // Also check for cases where the sizeof argument is the exact same 7449 // type as the memory argument, and where it points to a user-defined 7450 // record type. 7451 if (SizeOfArgTy != QualType()) { 7452 if (PointeeTy->isRecordType() && 7453 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7454 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7455 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7456 << FnName << SizeOfArgTy << ArgIdx 7457 << PointeeTy << Dest->getSourceRange() 7458 << LenExpr->getSourceRange()); 7459 break; 7460 } 7461 } 7462 } else if (DestTy->isArrayType()) { 7463 PointeeTy = DestTy; 7464 } 7465 7466 if (PointeeTy == QualType()) 7467 continue; 7468 7469 // Always complain about dynamic classes. 7470 bool IsContained; 7471 if (const CXXRecordDecl *ContainedRD = 7472 getContainedDynamicClass(PointeeTy, IsContained)) { 7473 7474 unsigned OperationType = 0; 7475 // "overwritten" if we're warning about the destination for any call 7476 // but memcmp; otherwise a verb appropriate to the call. 7477 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7478 if (BId == Builtin::BImemcpy) 7479 OperationType = 1; 7480 else if(BId == Builtin::BImemmove) 7481 OperationType = 2; 7482 else if (BId == Builtin::BImemcmp) 7483 OperationType = 3; 7484 } 7485 7486 DiagRuntimeBehavior( 7487 Dest->getExprLoc(), Dest, 7488 PDiag(diag::warn_dyn_class_memaccess) 7489 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7490 << FnName << IsContained << ContainedRD << OperationType 7491 << Call->getCallee()->getSourceRange()); 7492 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7493 BId != Builtin::BImemset) 7494 DiagRuntimeBehavior( 7495 Dest->getExprLoc(), Dest, 7496 PDiag(diag::warn_arc_object_memaccess) 7497 << ArgIdx << FnName << PointeeTy 7498 << Call->getCallee()->getSourceRange()); 7499 else 7500 continue; 7501 7502 DiagRuntimeBehavior( 7503 Dest->getExprLoc(), Dest, 7504 PDiag(diag::note_bad_memaccess_silence) 7505 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7506 break; 7507 } 7508 } 7509 7510 // A little helper routine: ignore addition and subtraction of integer literals. 7511 // This intentionally does not ignore all integer constant expressions because 7512 // we don't want to remove sizeof(). 7513 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7514 Ex = Ex->IgnoreParenCasts(); 7515 7516 while (true) { 7517 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7518 if (!BO || !BO->isAdditiveOp()) 7519 break; 7520 7521 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7522 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7523 7524 if (isa<IntegerLiteral>(RHS)) 7525 Ex = LHS; 7526 else if (isa<IntegerLiteral>(LHS)) 7527 Ex = RHS; 7528 else 7529 break; 7530 } 7531 7532 return Ex; 7533 } 7534 7535 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7536 ASTContext &Context) { 7537 // Only handle constant-sized or VLAs, but not flexible members. 7538 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7539 // Only issue the FIXIT for arrays of size > 1. 7540 if (CAT->getSize().getSExtValue() <= 1) 7541 return false; 7542 } else if (!Ty->isVariableArrayType()) { 7543 return false; 7544 } 7545 return true; 7546 } 7547 7548 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7549 // be the size of the source, instead of the destination. 7550 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7551 IdentifierInfo *FnName) { 7552 7553 // Don't crash if the user has the wrong number of arguments 7554 unsigned NumArgs = Call->getNumArgs(); 7555 if ((NumArgs != 3) && (NumArgs != 4)) 7556 return; 7557 7558 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7559 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7560 const Expr *CompareWithSrc = nullptr; 7561 7562 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7563 Call->getLocStart(), Call->getRParenLoc())) 7564 return; 7565 7566 // Look for 'strlcpy(dst, x, sizeof(x))' 7567 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7568 CompareWithSrc = Ex; 7569 else { 7570 // Look for 'strlcpy(dst, x, strlen(x))' 7571 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7572 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7573 SizeCall->getNumArgs() == 1) 7574 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7575 } 7576 } 7577 7578 if (!CompareWithSrc) 7579 return; 7580 7581 // Determine if the argument to sizeof/strlen is equal to the source 7582 // argument. In principle there's all kinds of things you could do 7583 // here, for instance creating an == expression and evaluating it with 7584 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7585 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7586 if (!SrcArgDRE) 7587 return; 7588 7589 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7590 if (!CompareWithSrcDRE || 7591 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7592 return; 7593 7594 const Expr *OriginalSizeArg = Call->getArg(2); 7595 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7596 << OriginalSizeArg->getSourceRange() << FnName; 7597 7598 // Output a FIXIT hint if the destination is an array (rather than a 7599 // pointer to an array). This could be enhanced to handle some 7600 // pointers if we know the actual size, like if DstArg is 'array+2' 7601 // we could say 'sizeof(array)-2'. 7602 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7603 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7604 return; 7605 7606 SmallString<128> sizeString; 7607 llvm::raw_svector_ostream OS(sizeString); 7608 OS << "sizeof("; 7609 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7610 OS << ")"; 7611 7612 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7613 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7614 OS.str()); 7615 } 7616 7617 /// Check if two expressions refer to the same declaration. 7618 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7619 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7620 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7621 return D1->getDecl() == D2->getDecl(); 7622 return false; 7623 } 7624 7625 static const Expr *getStrlenExprArg(const Expr *E) { 7626 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7627 const FunctionDecl *FD = CE->getDirectCallee(); 7628 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7629 return nullptr; 7630 return CE->getArg(0)->IgnoreParenCasts(); 7631 } 7632 return nullptr; 7633 } 7634 7635 // Warn on anti-patterns as the 'size' argument to strncat. 7636 // The correct size argument should look like following: 7637 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7638 void Sema::CheckStrncatArguments(const CallExpr *CE, 7639 IdentifierInfo *FnName) { 7640 // Don't crash if the user has the wrong number of arguments. 7641 if (CE->getNumArgs() < 3) 7642 return; 7643 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7644 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7645 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7646 7647 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7648 CE->getRParenLoc())) 7649 return; 7650 7651 // Identify common expressions, which are wrongly used as the size argument 7652 // to strncat and may lead to buffer overflows. 7653 unsigned PatternType = 0; 7654 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7655 // - sizeof(dst) 7656 if (referToTheSameDecl(SizeOfArg, DstArg)) 7657 PatternType = 1; 7658 // - sizeof(src) 7659 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7660 PatternType = 2; 7661 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7662 if (BE->getOpcode() == BO_Sub) { 7663 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7664 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7665 // - sizeof(dst) - strlen(dst) 7666 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7667 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7668 PatternType = 1; 7669 // - sizeof(src) - (anything) 7670 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7671 PatternType = 2; 7672 } 7673 } 7674 7675 if (PatternType == 0) 7676 return; 7677 7678 // Generate the diagnostic. 7679 SourceLocation SL = LenArg->getLocStart(); 7680 SourceRange SR = LenArg->getSourceRange(); 7681 SourceManager &SM = getSourceManager(); 7682 7683 // If the function is defined as a builtin macro, do not show macro expansion. 7684 if (SM.isMacroArgExpansion(SL)) { 7685 SL = SM.getSpellingLoc(SL); 7686 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7687 SM.getSpellingLoc(SR.getEnd())); 7688 } 7689 7690 // Check if the destination is an array (rather than a pointer to an array). 7691 QualType DstTy = DstArg->getType(); 7692 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7693 Context); 7694 if (!isKnownSizeArray) { 7695 if (PatternType == 1) 7696 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7697 else 7698 Diag(SL, diag::warn_strncat_src_size) << SR; 7699 return; 7700 } 7701 7702 if (PatternType == 1) 7703 Diag(SL, diag::warn_strncat_large_size) << SR; 7704 else 7705 Diag(SL, diag::warn_strncat_src_size) << SR; 7706 7707 SmallString<128> sizeString; 7708 llvm::raw_svector_ostream OS(sizeString); 7709 OS << "sizeof("; 7710 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7711 OS << ") - "; 7712 OS << "strlen("; 7713 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7714 OS << ") - 1"; 7715 7716 Diag(SL, diag::note_strncat_wrong_size) 7717 << FixItHint::CreateReplacement(SR, OS.str()); 7718 } 7719 7720 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7721 7722 static const Expr *EvalVal(const Expr *E, 7723 SmallVectorImpl<const DeclRefExpr *> &refVars, 7724 const Decl *ParentDecl); 7725 static const Expr *EvalAddr(const Expr *E, 7726 SmallVectorImpl<const DeclRefExpr *> &refVars, 7727 const Decl *ParentDecl); 7728 7729 /// CheckReturnStackAddr - Check if a return statement returns the address 7730 /// of a stack variable. 7731 static void 7732 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7733 SourceLocation ReturnLoc) { 7734 const Expr *stackE = nullptr; 7735 SmallVector<const DeclRefExpr *, 8> refVars; 7736 7737 // Perform checking for returned stack addresses, local blocks, 7738 // label addresses or references to temporaries. 7739 if (lhsType->isPointerType() || 7740 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7741 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7742 } else if (lhsType->isReferenceType()) { 7743 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7744 } 7745 7746 if (!stackE) 7747 return; // Nothing suspicious was found. 7748 7749 // Parameters are initialized in the calling scope, so taking the address 7750 // of a parameter reference doesn't need a warning. 7751 for (auto *DRE : refVars) 7752 if (isa<ParmVarDecl>(DRE->getDecl())) 7753 return; 7754 7755 SourceLocation diagLoc; 7756 SourceRange diagRange; 7757 if (refVars.empty()) { 7758 diagLoc = stackE->getLocStart(); 7759 diagRange = stackE->getSourceRange(); 7760 } else { 7761 // We followed through a reference variable. 'stackE' contains the 7762 // problematic expression but we will warn at the return statement pointing 7763 // at the reference variable. We will later display the "trail" of 7764 // reference variables using notes. 7765 diagLoc = refVars[0]->getLocStart(); 7766 diagRange = refVars[0]->getSourceRange(); 7767 } 7768 7769 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7770 // address of local var 7771 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7772 << DR->getDecl()->getDeclName() << diagRange; 7773 } else if (isa<BlockExpr>(stackE)) { // local block. 7774 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7775 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7776 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7777 } else { // local temporary. 7778 // If there is an LValue->RValue conversion, then the value of the 7779 // reference type is used, not the reference. 7780 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7781 if (ICE->getCastKind() == CK_LValueToRValue) { 7782 return; 7783 } 7784 } 7785 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7786 << lhsType->isReferenceType() << diagRange; 7787 } 7788 7789 // Display the "trail" of reference variables that we followed until we 7790 // found the problematic expression using notes. 7791 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7792 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7793 // If this var binds to another reference var, show the range of the next 7794 // var, otherwise the var binds to the problematic expression, in which case 7795 // show the range of the expression. 7796 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7797 : stackE->getSourceRange(); 7798 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7799 << VD->getDeclName() << range; 7800 } 7801 } 7802 7803 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7804 /// check if the expression in a return statement evaluates to an address 7805 /// to a location on the stack, a local block, an address of a label, or a 7806 /// reference to local temporary. The recursion is used to traverse the 7807 /// AST of the return expression, with recursion backtracking when we 7808 /// encounter a subexpression that (1) clearly does not lead to one of the 7809 /// above problematic expressions (2) is something we cannot determine leads to 7810 /// a problematic expression based on such local checking. 7811 /// 7812 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7813 /// the expression that they point to. Such variables are added to the 7814 /// 'refVars' vector so that we know what the reference variable "trail" was. 7815 /// 7816 /// EvalAddr processes expressions that are pointers that are used as 7817 /// references (and not L-values). EvalVal handles all other values. 7818 /// At the base case of the recursion is a check for the above problematic 7819 /// expressions. 7820 /// 7821 /// This implementation handles: 7822 /// 7823 /// * pointer-to-pointer casts 7824 /// * implicit conversions from array references to pointers 7825 /// * taking the address of fields 7826 /// * arbitrary interplay between "&" and "*" operators 7827 /// * pointer arithmetic from an address of a stack variable 7828 /// * taking the address of an array element where the array is on the stack 7829 static const Expr *EvalAddr(const Expr *E, 7830 SmallVectorImpl<const DeclRefExpr *> &refVars, 7831 const Decl *ParentDecl) { 7832 if (E->isTypeDependent()) 7833 return nullptr; 7834 7835 // We should only be called for evaluating pointer expressions. 7836 assert((E->getType()->isAnyPointerType() || 7837 E->getType()->isBlockPointerType() || 7838 E->getType()->isObjCQualifiedIdType()) && 7839 "EvalAddr only works on pointers"); 7840 7841 E = E->IgnoreParens(); 7842 7843 // Our "symbolic interpreter" is just a dispatch off the currently 7844 // viewed AST node. We then recursively traverse the AST by calling 7845 // EvalAddr and EvalVal appropriately. 7846 switch (E->getStmtClass()) { 7847 case Stmt::DeclRefExprClass: { 7848 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7849 7850 // If we leave the immediate function, the lifetime isn't about to end. 7851 if (DR->refersToEnclosingVariableOrCapture()) 7852 return nullptr; 7853 7854 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7855 // If this is a reference variable, follow through to the expression that 7856 // it points to. 7857 if (V->hasLocalStorage() && 7858 V->getType()->isReferenceType() && V->hasInit()) { 7859 // Add the reference variable to the "trail". 7860 refVars.push_back(DR); 7861 return EvalAddr(V->getInit(), refVars, ParentDecl); 7862 } 7863 7864 return nullptr; 7865 } 7866 7867 case Stmt::UnaryOperatorClass: { 7868 // The only unary operator that make sense to handle here 7869 // is AddrOf. All others don't make sense as pointers. 7870 const UnaryOperator *U = cast<UnaryOperator>(E); 7871 7872 if (U->getOpcode() == UO_AddrOf) 7873 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7874 return nullptr; 7875 } 7876 7877 case Stmt::BinaryOperatorClass: { 7878 // Handle pointer arithmetic. All other binary operators are not valid 7879 // in this context. 7880 const BinaryOperator *B = cast<BinaryOperator>(E); 7881 BinaryOperatorKind op = B->getOpcode(); 7882 7883 if (op != BO_Add && op != BO_Sub) 7884 return nullptr; 7885 7886 const Expr *Base = B->getLHS(); 7887 7888 // Determine which argument is the real pointer base. It could be 7889 // the RHS argument instead of the LHS. 7890 if (!Base->getType()->isPointerType()) 7891 Base = B->getRHS(); 7892 7893 assert(Base->getType()->isPointerType()); 7894 return EvalAddr(Base, refVars, ParentDecl); 7895 } 7896 7897 // For conditional operators we need to see if either the LHS or RHS are 7898 // valid DeclRefExpr*s. If one of them is valid, we return it. 7899 case Stmt::ConditionalOperatorClass: { 7900 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7901 7902 // Handle the GNU extension for missing LHS. 7903 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7904 if (const Expr *LHSExpr = C->getLHS()) { 7905 // In C++, we can have a throw-expression, which has 'void' type. 7906 if (!LHSExpr->getType()->isVoidType()) 7907 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7908 return LHS; 7909 } 7910 7911 // In C++, we can have a throw-expression, which has 'void' type. 7912 if (C->getRHS()->getType()->isVoidType()) 7913 return nullptr; 7914 7915 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7916 } 7917 7918 case Stmt::BlockExprClass: 7919 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7920 return E; // local block. 7921 return nullptr; 7922 7923 case Stmt::AddrLabelExprClass: 7924 return E; // address of label. 7925 7926 case Stmt::ExprWithCleanupsClass: 7927 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7928 ParentDecl); 7929 7930 // For casts, we need to handle conversions from arrays to 7931 // pointer values, and pointer-to-pointer conversions. 7932 case Stmt::ImplicitCastExprClass: 7933 case Stmt::CStyleCastExprClass: 7934 case Stmt::CXXFunctionalCastExprClass: 7935 case Stmt::ObjCBridgedCastExprClass: 7936 case Stmt::CXXStaticCastExprClass: 7937 case Stmt::CXXDynamicCastExprClass: 7938 case Stmt::CXXConstCastExprClass: 7939 case Stmt::CXXReinterpretCastExprClass: { 7940 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7941 switch (cast<CastExpr>(E)->getCastKind()) { 7942 case CK_LValueToRValue: 7943 case CK_NoOp: 7944 case CK_BaseToDerived: 7945 case CK_DerivedToBase: 7946 case CK_UncheckedDerivedToBase: 7947 case CK_Dynamic: 7948 case CK_CPointerToObjCPointerCast: 7949 case CK_BlockPointerToObjCPointerCast: 7950 case CK_AnyPointerToBlockPointerCast: 7951 return EvalAddr(SubExpr, refVars, ParentDecl); 7952 7953 case CK_ArrayToPointerDecay: 7954 return EvalVal(SubExpr, refVars, ParentDecl); 7955 7956 case CK_BitCast: 7957 if (SubExpr->getType()->isAnyPointerType() || 7958 SubExpr->getType()->isBlockPointerType() || 7959 SubExpr->getType()->isObjCQualifiedIdType()) 7960 return EvalAddr(SubExpr, refVars, ParentDecl); 7961 else 7962 return nullptr; 7963 7964 default: 7965 return nullptr; 7966 } 7967 } 7968 7969 case Stmt::MaterializeTemporaryExprClass: 7970 if (const Expr *Result = 7971 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7972 refVars, ParentDecl)) 7973 return Result; 7974 return E; 7975 7976 // Everything else: we simply don't reason about them. 7977 default: 7978 return nullptr; 7979 } 7980 } 7981 7982 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7983 /// See the comments for EvalAddr for more details. 7984 static const Expr *EvalVal(const Expr *E, 7985 SmallVectorImpl<const DeclRefExpr *> &refVars, 7986 const Decl *ParentDecl) { 7987 do { 7988 // We should only be called for evaluating non-pointer expressions, or 7989 // expressions with a pointer type that are not used as references but 7990 // instead 7991 // are l-values (e.g., DeclRefExpr with a pointer type). 7992 7993 // Our "symbolic interpreter" is just a dispatch off the currently 7994 // viewed AST node. We then recursively traverse the AST by calling 7995 // EvalAddr and EvalVal appropriately. 7996 7997 E = E->IgnoreParens(); 7998 switch (E->getStmtClass()) { 7999 case Stmt::ImplicitCastExprClass: { 8000 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 8001 if (IE->getValueKind() == VK_LValue) { 8002 E = IE->getSubExpr(); 8003 continue; 8004 } 8005 return nullptr; 8006 } 8007 8008 case Stmt::ExprWithCleanupsClass: 8009 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8010 ParentDecl); 8011 8012 case Stmt::DeclRefExprClass: { 8013 // When we hit a DeclRefExpr we are looking at code that refers to a 8014 // variable's name. If it's not a reference variable we check if it has 8015 // local storage within the function, and if so, return the expression. 8016 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8017 8018 // If we leave the immediate function, the lifetime isn't about to end. 8019 if (DR->refersToEnclosingVariableOrCapture()) 8020 return nullptr; 8021 8022 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 8023 // Check if it refers to itself, e.g. "int& i = i;". 8024 if (V == ParentDecl) 8025 return DR; 8026 8027 if (V->hasLocalStorage()) { 8028 if (!V->getType()->isReferenceType()) 8029 return DR; 8030 8031 // Reference variable, follow through to the expression that 8032 // it points to. 8033 if (V->hasInit()) { 8034 // Add the reference variable to the "trail". 8035 refVars.push_back(DR); 8036 return EvalVal(V->getInit(), refVars, V); 8037 } 8038 } 8039 } 8040 8041 return nullptr; 8042 } 8043 8044 case Stmt::UnaryOperatorClass: { 8045 // The only unary operator that make sense to handle here 8046 // is Deref. All others don't resolve to a "name." This includes 8047 // handling all sorts of rvalues passed to a unary operator. 8048 const UnaryOperator *U = cast<UnaryOperator>(E); 8049 8050 if (U->getOpcode() == UO_Deref) 8051 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 8052 8053 return nullptr; 8054 } 8055 8056 case Stmt::ArraySubscriptExprClass: { 8057 // Array subscripts are potential references to data on the stack. We 8058 // retrieve the DeclRefExpr* for the array variable if it indeed 8059 // has local storage. 8060 const auto *ASE = cast<ArraySubscriptExpr>(E); 8061 if (ASE->isTypeDependent()) 8062 return nullptr; 8063 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 8064 } 8065 8066 case Stmt::OMPArraySectionExprClass: { 8067 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 8068 ParentDecl); 8069 } 8070 8071 case Stmt::ConditionalOperatorClass: { 8072 // For conditional operators we need to see if either the LHS or RHS are 8073 // non-NULL Expr's. If one is non-NULL, we return it. 8074 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8075 8076 // Handle the GNU extension for missing LHS. 8077 if (const Expr *LHSExpr = C->getLHS()) { 8078 // In C++, we can have a throw-expression, which has 'void' type. 8079 if (!LHSExpr->getType()->isVoidType()) 8080 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 8081 return LHS; 8082 } 8083 8084 // In C++, we can have a throw-expression, which has 'void' type. 8085 if (C->getRHS()->getType()->isVoidType()) 8086 return nullptr; 8087 8088 return EvalVal(C->getRHS(), refVars, ParentDecl); 8089 } 8090 8091 // Accesses to members are potential references to data on the stack. 8092 case Stmt::MemberExprClass: { 8093 const MemberExpr *M = cast<MemberExpr>(E); 8094 8095 // Check for indirect access. We only want direct field accesses. 8096 if (M->isArrow()) 8097 return nullptr; 8098 8099 // Check whether the member type is itself a reference, in which case 8100 // we're not going to refer to the member, but to what the member refers 8101 // to. 8102 if (M->getMemberDecl()->getType()->isReferenceType()) 8103 return nullptr; 8104 8105 return EvalVal(M->getBase(), refVars, ParentDecl); 8106 } 8107 8108 case Stmt::MaterializeTemporaryExprClass: 8109 if (const Expr *Result = 8110 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8111 refVars, ParentDecl)) 8112 return Result; 8113 return E; 8114 8115 default: 8116 // Check that we don't return or take the address of a reference to a 8117 // temporary. This is only useful in C++. 8118 if (!E->isTypeDependent() && E->isRValue()) 8119 return E; 8120 8121 // Everything else: we simply don't reason about them. 8122 return nullptr; 8123 } 8124 } while (true); 8125 } 8126 8127 void 8128 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8129 SourceLocation ReturnLoc, 8130 bool isObjCMethod, 8131 const AttrVec *Attrs, 8132 const FunctionDecl *FD) { 8133 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8134 8135 // Check if the return value is null but should not be. 8136 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8137 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8138 CheckNonNullExpr(*this, RetValExp)) 8139 Diag(ReturnLoc, diag::warn_null_ret) 8140 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8141 8142 // C++11 [basic.stc.dynamic.allocation]p4: 8143 // If an allocation function declared with a non-throwing 8144 // exception-specification fails to allocate storage, it shall return 8145 // a null pointer. Any other allocation function that fails to allocate 8146 // storage shall indicate failure only by throwing an exception [...] 8147 if (FD) { 8148 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8149 if (Op == OO_New || Op == OO_Array_New) { 8150 const FunctionProtoType *Proto 8151 = FD->getType()->castAs<FunctionProtoType>(); 8152 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 8153 CheckNonNullExpr(*this, RetValExp)) 8154 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8155 << FD << getLangOpts().CPlusPlus11; 8156 } 8157 } 8158 } 8159 8160 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8161 8162 /// Check for comparisons of floating point operands using != and ==. 8163 /// Issue a warning if these are no self-comparisons, as they are not likely 8164 /// to do what the programmer intended. 8165 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8166 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8167 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8168 8169 // Special case: check for x == x (which is OK). 8170 // Do not emit warnings for such cases. 8171 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8172 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8173 if (DRL->getDecl() == DRR->getDecl()) 8174 return; 8175 8176 // Special case: check for comparisons against literals that can be exactly 8177 // represented by APFloat. In such cases, do not emit a warning. This 8178 // is a heuristic: often comparison against such literals are used to 8179 // detect if a value in a variable has not changed. This clearly can 8180 // lead to false negatives. 8181 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8182 if (FLL->isExact()) 8183 return; 8184 } else 8185 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8186 if (FLR->isExact()) 8187 return; 8188 8189 // Check for comparisons with builtin types. 8190 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8191 if (CL->getBuiltinCallee()) 8192 return; 8193 8194 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8195 if (CR->getBuiltinCallee()) 8196 return; 8197 8198 // Emit the diagnostic. 8199 Diag(Loc, diag::warn_floatingpoint_eq) 8200 << LHS->getSourceRange() << RHS->getSourceRange(); 8201 } 8202 8203 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8204 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8205 8206 namespace { 8207 8208 /// Structure recording the 'active' range of an integer-valued 8209 /// expression. 8210 struct IntRange { 8211 /// The number of bits active in the int. 8212 unsigned Width; 8213 8214 /// True if the int is known not to have negative values. 8215 bool NonNegative; 8216 8217 IntRange(unsigned Width, bool NonNegative) 8218 : Width(Width), NonNegative(NonNegative) {} 8219 8220 /// Returns the range of the bool type. 8221 static IntRange forBoolType() { 8222 return IntRange(1, true); 8223 } 8224 8225 /// Returns the range of an opaque value of the given integral type. 8226 static IntRange forValueOfType(ASTContext &C, QualType T) { 8227 return forValueOfCanonicalType(C, 8228 T->getCanonicalTypeInternal().getTypePtr()); 8229 } 8230 8231 /// Returns the range of an opaque value of a canonical integral type. 8232 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8233 assert(T->isCanonicalUnqualified()); 8234 8235 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8236 T = VT->getElementType().getTypePtr(); 8237 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8238 T = CT->getElementType().getTypePtr(); 8239 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8240 T = AT->getValueType().getTypePtr(); 8241 8242 if (!C.getLangOpts().CPlusPlus) { 8243 // For enum types in C code, use the underlying datatype. 8244 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8245 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 8246 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8247 // For enum types in C++, use the known bit width of the enumerators. 8248 EnumDecl *Enum = ET->getDecl(); 8249 // In C++11, enums can have a fixed underlying type. Use this type to 8250 // compute the range. 8251 if (Enum->isFixed()) { 8252 return IntRange(C.getIntWidth(QualType(T, 0)), 8253 !ET->isSignedIntegerOrEnumerationType()); 8254 } 8255 8256 unsigned NumPositive = Enum->getNumPositiveBits(); 8257 unsigned NumNegative = Enum->getNumNegativeBits(); 8258 8259 if (NumNegative == 0) 8260 return IntRange(NumPositive, true/*NonNegative*/); 8261 else 8262 return IntRange(std::max(NumPositive + 1, NumNegative), 8263 false/*NonNegative*/); 8264 } 8265 8266 const BuiltinType *BT = cast<BuiltinType>(T); 8267 assert(BT->isInteger()); 8268 8269 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8270 } 8271 8272 /// Returns the "target" range of a canonical integral type, i.e. 8273 /// the range of values expressible in the type. 8274 /// 8275 /// This matches forValueOfCanonicalType except that enums have the 8276 /// full range of their type, not the range of their enumerators. 8277 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8278 assert(T->isCanonicalUnqualified()); 8279 8280 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8281 T = VT->getElementType().getTypePtr(); 8282 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8283 T = CT->getElementType().getTypePtr(); 8284 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8285 T = AT->getValueType().getTypePtr(); 8286 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8287 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8288 8289 const BuiltinType *BT = cast<BuiltinType>(T); 8290 assert(BT->isInteger()); 8291 8292 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8293 } 8294 8295 /// Returns the supremum of two ranges: i.e. their conservative merge. 8296 static IntRange join(IntRange L, IntRange R) { 8297 return IntRange(std::max(L.Width, R.Width), 8298 L.NonNegative && R.NonNegative); 8299 } 8300 8301 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8302 static IntRange meet(IntRange L, IntRange R) { 8303 return IntRange(std::min(L.Width, R.Width), 8304 L.NonNegative || R.NonNegative); 8305 } 8306 }; 8307 8308 } // namespace 8309 8310 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 8311 unsigned MaxWidth) { 8312 if (value.isSigned() && value.isNegative()) 8313 return IntRange(value.getMinSignedBits(), false); 8314 8315 if (value.getBitWidth() > MaxWidth) 8316 value = value.trunc(MaxWidth); 8317 8318 // isNonNegative() just checks the sign bit without considering 8319 // signedness. 8320 return IntRange(value.getActiveBits(), true); 8321 } 8322 8323 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8324 unsigned MaxWidth) { 8325 if (result.isInt()) 8326 return GetValueRange(C, result.getInt(), MaxWidth); 8327 8328 if (result.isVector()) { 8329 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8330 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8331 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8332 R = IntRange::join(R, El); 8333 } 8334 return R; 8335 } 8336 8337 if (result.isComplexInt()) { 8338 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8339 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8340 return IntRange::join(R, I); 8341 } 8342 8343 // This can happen with lossless casts to intptr_t of "based" lvalues. 8344 // Assume it might use arbitrary bits. 8345 // FIXME: The only reason we need to pass the type in here is to get 8346 // the sign right on this one case. It would be nice if APValue 8347 // preserved this. 8348 assert(result.isLValue() || result.isAddrLabelDiff()); 8349 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8350 } 8351 8352 static QualType GetExprType(const Expr *E) { 8353 QualType Ty = E->getType(); 8354 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8355 Ty = AtomicRHS->getValueType(); 8356 return Ty; 8357 } 8358 8359 /// Pseudo-evaluate the given integer expression, estimating the 8360 /// range of values it might take. 8361 /// 8362 /// \param MaxWidth - the width to which the value will be truncated 8363 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8364 E = E->IgnoreParens(); 8365 8366 // Try a full evaluation first. 8367 Expr::EvalResult result; 8368 if (E->EvaluateAsRValue(result, C)) 8369 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8370 8371 // I think we only want to look through implicit casts here; if the 8372 // user has an explicit widening cast, we should treat the value as 8373 // being of the new, wider type. 8374 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8375 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8376 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8377 8378 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8379 8380 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8381 CE->getCastKind() == CK_BooleanToSignedIntegral; 8382 8383 // Assume that non-integer casts can span the full range of the type. 8384 if (!isIntegerCast) 8385 return OutputTypeRange; 8386 8387 IntRange SubRange 8388 = GetExprRange(C, CE->getSubExpr(), 8389 std::min(MaxWidth, OutputTypeRange.Width)); 8390 8391 // Bail out if the subexpr's range is as wide as the cast type. 8392 if (SubRange.Width >= OutputTypeRange.Width) 8393 return OutputTypeRange; 8394 8395 // Otherwise, we take the smaller width, and we're non-negative if 8396 // either the output type or the subexpr is. 8397 return IntRange(SubRange.Width, 8398 SubRange.NonNegative || OutputTypeRange.NonNegative); 8399 } 8400 8401 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8402 // If we can fold the condition, just take that operand. 8403 bool CondResult; 8404 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8405 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8406 : CO->getFalseExpr(), 8407 MaxWidth); 8408 8409 // Otherwise, conservatively merge. 8410 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8411 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8412 return IntRange::join(L, R); 8413 } 8414 8415 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8416 switch (BO->getOpcode()) { 8417 case BO_Cmp: 8418 llvm_unreachable("builtin <=> should have class type"); 8419 8420 // Boolean-valued operations are single-bit and positive. 8421 case BO_LAnd: 8422 case BO_LOr: 8423 case BO_LT: 8424 case BO_GT: 8425 case BO_LE: 8426 case BO_GE: 8427 case BO_EQ: 8428 case BO_NE: 8429 return IntRange::forBoolType(); 8430 8431 // The type of the assignments is the type of the LHS, so the RHS 8432 // is not necessarily the same type. 8433 case BO_MulAssign: 8434 case BO_DivAssign: 8435 case BO_RemAssign: 8436 case BO_AddAssign: 8437 case BO_SubAssign: 8438 case BO_XorAssign: 8439 case BO_OrAssign: 8440 // TODO: bitfields? 8441 return IntRange::forValueOfType(C, GetExprType(E)); 8442 8443 // Simple assignments just pass through the RHS, which will have 8444 // been coerced to the LHS type. 8445 case BO_Assign: 8446 // TODO: bitfields? 8447 return GetExprRange(C, BO->getRHS(), MaxWidth); 8448 8449 // Operations with opaque sources are black-listed. 8450 case BO_PtrMemD: 8451 case BO_PtrMemI: 8452 return IntRange::forValueOfType(C, GetExprType(E)); 8453 8454 // Bitwise-and uses the *infinum* of the two source ranges. 8455 case BO_And: 8456 case BO_AndAssign: 8457 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8458 GetExprRange(C, BO->getRHS(), MaxWidth)); 8459 8460 // Left shift gets black-listed based on a judgement call. 8461 case BO_Shl: 8462 // ...except that we want to treat '1 << (blah)' as logically 8463 // positive. It's an important idiom. 8464 if (IntegerLiteral *I 8465 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8466 if (I->getValue() == 1) { 8467 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8468 return IntRange(R.Width, /*NonNegative*/ true); 8469 } 8470 } 8471 LLVM_FALLTHROUGH; 8472 8473 case BO_ShlAssign: 8474 return IntRange::forValueOfType(C, GetExprType(E)); 8475 8476 // Right shift by a constant can narrow its left argument. 8477 case BO_Shr: 8478 case BO_ShrAssign: { 8479 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8480 8481 // If the shift amount is a positive constant, drop the width by 8482 // that much. 8483 llvm::APSInt shift; 8484 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8485 shift.isNonNegative()) { 8486 unsigned zext = shift.getZExtValue(); 8487 if (zext >= L.Width) 8488 L.Width = (L.NonNegative ? 0 : 1); 8489 else 8490 L.Width -= zext; 8491 } 8492 8493 return L; 8494 } 8495 8496 // Comma acts as its right operand. 8497 case BO_Comma: 8498 return GetExprRange(C, BO->getRHS(), MaxWidth); 8499 8500 // Black-list pointer subtractions. 8501 case BO_Sub: 8502 if (BO->getLHS()->getType()->isPointerType()) 8503 return IntRange::forValueOfType(C, GetExprType(E)); 8504 break; 8505 8506 // The width of a division result is mostly determined by the size 8507 // of the LHS. 8508 case BO_Div: { 8509 // Don't 'pre-truncate' the operands. 8510 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8511 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8512 8513 // If the divisor is constant, use that. 8514 llvm::APSInt divisor; 8515 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8516 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8517 if (log2 >= L.Width) 8518 L.Width = (L.NonNegative ? 0 : 1); 8519 else 8520 L.Width = std::min(L.Width - log2, MaxWidth); 8521 return L; 8522 } 8523 8524 // Otherwise, just use the LHS's width. 8525 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8526 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8527 } 8528 8529 // The result of a remainder can't be larger than the result of 8530 // either side. 8531 case BO_Rem: { 8532 // Don't 'pre-truncate' the operands. 8533 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8534 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8535 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8536 8537 IntRange meet = IntRange::meet(L, R); 8538 meet.Width = std::min(meet.Width, MaxWidth); 8539 return meet; 8540 } 8541 8542 // The default behavior is okay for these. 8543 case BO_Mul: 8544 case BO_Add: 8545 case BO_Xor: 8546 case BO_Or: 8547 break; 8548 } 8549 8550 // The default case is to treat the operation as if it were closed 8551 // on the narrowest type that encompasses both operands. 8552 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8553 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8554 return IntRange::join(L, R); 8555 } 8556 8557 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8558 switch (UO->getOpcode()) { 8559 // Boolean-valued operations are white-listed. 8560 case UO_LNot: 8561 return IntRange::forBoolType(); 8562 8563 // Operations with opaque sources are black-listed. 8564 case UO_Deref: 8565 case UO_AddrOf: // should be impossible 8566 return IntRange::forValueOfType(C, GetExprType(E)); 8567 8568 default: 8569 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8570 } 8571 } 8572 8573 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8574 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8575 8576 if (const auto *BitField = E->getSourceBitField()) 8577 return IntRange(BitField->getBitWidthValue(C), 8578 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8579 8580 return IntRange::forValueOfType(C, GetExprType(E)); 8581 } 8582 8583 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 8584 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8585 } 8586 8587 /// Checks whether the given value, which currently has the given 8588 /// source semantics, has the same value when coerced through the 8589 /// target semantics. 8590 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 8591 const llvm::fltSemantics &Src, 8592 const llvm::fltSemantics &Tgt) { 8593 llvm::APFloat truncated = value; 8594 8595 bool ignored; 8596 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8597 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8598 8599 return truncated.bitwiseIsEqual(value); 8600 } 8601 8602 /// Checks whether the given value, which currently has the given 8603 /// source semantics, has the same value when coerced through the 8604 /// target semantics. 8605 /// 8606 /// The value might be a vector of floats (or a complex number). 8607 static bool IsSameFloatAfterCast(const APValue &value, 8608 const llvm::fltSemantics &Src, 8609 const llvm::fltSemantics &Tgt) { 8610 if (value.isFloat()) 8611 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8612 8613 if (value.isVector()) { 8614 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8615 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8616 return false; 8617 return true; 8618 } 8619 8620 assert(value.isComplexFloat()); 8621 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8622 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8623 } 8624 8625 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8626 8627 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 8628 // Suppress cases where we are comparing against an enum constant. 8629 if (const DeclRefExpr *DR = 8630 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8631 if (isa<EnumConstantDecl>(DR->getDecl())) 8632 return true; 8633 8634 // Suppress cases where the '0' value is expanded from a macro. 8635 if (E->getLocStart().isMacroID()) 8636 return true; 8637 8638 return false; 8639 } 8640 8641 static bool isKnownToHaveUnsignedValue(Expr *E) { 8642 return E->getType()->isIntegerType() && 8643 (!E->getType()->isSignedIntegerType() || 8644 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 8645 } 8646 8647 namespace { 8648 /// The promoted range of values of a type. In general this has the 8649 /// following structure: 8650 /// 8651 /// |-----------| . . . |-----------| 8652 /// ^ ^ ^ ^ 8653 /// Min HoleMin HoleMax Max 8654 /// 8655 /// ... where there is only a hole if a signed type is promoted to unsigned 8656 /// (in which case Min and Max are the smallest and largest representable 8657 /// values). 8658 struct PromotedRange { 8659 // Min, or HoleMax if there is a hole. 8660 llvm::APSInt PromotedMin; 8661 // Max, or HoleMin if there is a hole. 8662 llvm::APSInt PromotedMax; 8663 8664 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 8665 if (R.Width == 0) 8666 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 8667 else if (R.Width >= BitWidth && !Unsigned) { 8668 // Promotion made the type *narrower*. This happens when promoting 8669 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 8670 // Treat all values of 'signed int' as being in range for now. 8671 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 8672 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 8673 } else { 8674 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 8675 .extOrTrunc(BitWidth); 8676 PromotedMin.setIsUnsigned(Unsigned); 8677 8678 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 8679 .extOrTrunc(BitWidth); 8680 PromotedMax.setIsUnsigned(Unsigned); 8681 } 8682 } 8683 8684 // Determine whether this range is contiguous (has no hole). 8685 bool isContiguous() const { return PromotedMin <= PromotedMax; } 8686 8687 // Where a constant value is within the range. 8688 enum ComparisonResult { 8689 LT = 0x1, 8690 LE = 0x2, 8691 GT = 0x4, 8692 GE = 0x8, 8693 EQ = 0x10, 8694 NE = 0x20, 8695 InRangeFlag = 0x40, 8696 8697 Less = LE | LT | NE, 8698 Min = LE | InRangeFlag, 8699 InRange = InRangeFlag, 8700 Max = GE | InRangeFlag, 8701 Greater = GE | GT | NE, 8702 8703 OnlyValue = LE | GE | EQ | InRangeFlag, 8704 InHole = NE 8705 }; 8706 8707 ComparisonResult compare(const llvm::APSInt &Value) const { 8708 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 8709 Value.isUnsigned() == PromotedMin.isUnsigned()); 8710 if (!isContiguous()) { 8711 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 8712 if (Value.isMinValue()) return Min; 8713 if (Value.isMaxValue()) return Max; 8714 if (Value >= PromotedMin) return InRange; 8715 if (Value <= PromotedMax) return InRange; 8716 return InHole; 8717 } 8718 8719 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 8720 case -1: return Less; 8721 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 8722 case 1: 8723 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 8724 case -1: return InRange; 8725 case 0: return Max; 8726 case 1: return Greater; 8727 } 8728 } 8729 8730 llvm_unreachable("impossible compare result"); 8731 } 8732 8733 static llvm::Optional<StringRef> 8734 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 8735 if (Op == BO_Cmp) { 8736 ComparisonResult LTFlag = LT, GTFlag = GT; 8737 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 8738 8739 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 8740 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 8741 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 8742 return llvm::None; 8743 } 8744 8745 ComparisonResult TrueFlag, FalseFlag; 8746 if (Op == BO_EQ) { 8747 TrueFlag = EQ; 8748 FalseFlag = NE; 8749 } else if (Op == BO_NE) { 8750 TrueFlag = NE; 8751 FalseFlag = EQ; 8752 } else { 8753 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 8754 TrueFlag = LT; 8755 FalseFlag = GE; 8756 } else { 8757 TrueFlag = GT; 8758 FalseFlag = LE; 8759 } 8760 if (Op == BO_GE || Op == BO_LE) 8761 std::swap(TrueFlag, FalseFlag); 8762 } 8763 if (R & TrueFlag) 8764 return StringRef("true"); 8765 if (R & FalseFlag) 8766 return StringRef("false"); 8767 return llvm::None; 8768 } 8769 }; 8770 } 8771 8772 static bool HasEnumType(Expr *E) { 8773 // Strip off implicit integral promotions. 8774 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8775 if (ICE->getCastKind() != CK_IntegralCast && 8776 ICE->getCastKind() != CK_NoOp) 8777 break; 8778 E = ICE->getSubExpr(); 8779 } 8780 8781 return E->getType()->isEnumeralType(); 8782 } 8783 8784 static int classifyConstantValue(Expr *Constant) { 8785 // The values of this enumeration are used in the diagnostics 8786 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 8787 enum ConstantValueKind { 8788 Miscellaneous = 0, 8789 LiteralTrue, 8790 LiteralFalse 8791 }; 8792 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 8793 return BL->getValue() ? ConstantValueKind::LiteralTrue 8794 : ConstantValueKind::LiteralFalse; 8795 return ConstantValueKind::Miscellaneous; 8796 } 8797 8798 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 8799 Expr *Constant, Expr *Other, 8800 const llvm::APSInt &Value, 8801 bool RhsConstant) { 8802 if (S.inTemplateInstantiation()) 8803 return false; 8804 8805 Expr *OriginalOther = Other; 8806 8807 Constant = Constant->IgnoreParenImpCasts(); 8808 Other = Other->IgnoreParenImpCasts(); 8809 8810 // Suppress warnings on tautological comparisons between values of the same 8811 // enumeration type. There are only two ways we could warn on this: 8812 // - If the constant is outside the range of representable values of 8813 // the enumeration. In such a case, we should warn about the cast 8814 // to enumeration type, not about the comparison. 8815 // - If the constant is the maximum / minimum in-range value. For an 8816 // enumeratin type, such comparisons can be meaningful and useful. 8817 if (Constant->getType()->isEnumeralType() && 8818 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 8819 return false; 8820 8821 // TODO: Investigate using GetExprRange() to get tighter bounds 8822 // on the bit ranges. 8823 QualType OtherT = Other->getType(); 8824 if (const auto *AT = OtherT->getAs<AtomicType>()) 8825 OtherT = AT->getValueType(); 8826 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8827 8828 // Whether we're treating Other as being a bool because of the form of 8829 // expression despite it having another type (typically 'int' in C). 8830 bool OtherIsBooleanDespiteType = 8831 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 8832 if (OtherIsBooleanDespiteType) 8833 OtherRange = IntRange::forBoolType(); 8834 8835 // Determine the promoted range of the other type and see if a comparison of 8836 // the constant against that range is tautological. 8837 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 8838 Value.isUnsigned()); 8839 auto Cmp = OtherPromotedRange.compare(Value); 8840 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 8841 if (!Result) 8842 return false; 8843 8844 // Suppress the diagnostic for an in-range comparison if the constant comes 8845 // from a macro or enumerator. We don't want to diagnose 8846 // 8847 // some_long_value <= INT_MAX 8848 // 8849 // when sizeof(int) == sizeof(long). 8850 bool InRange = Cmp & PromotedRange::InRangeFlag; 8851 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 8852 return false; 8853 8854 // If this is a comparison to an enum constant, include that 8855 // constant in the diagnostic. 8856 const EnumConstantDecl *ED = nullptr; 8857 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8858 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8859 8860 // Should be enough for uint128 (39 decimal digits) 8861 SmallString<64> PrettySourceValue; 8862 llvm::raw_svector_ostream OS(PrettySourceValue); 8863 if (ED) 8864 OS << '\'' << *ED << "' (" << Value << ")"; 8865 else 8866 OS << Value; 8867 8868 // FIXME: We use a somewhat different formatting for the in-range cases and 8869 // cases involving boolean values for historical reasons. We should pick a 8870 // consistent way of presenting these diagnostics. 8871 if (!InRange || Other->isKnownToHaveBooleanValue()) { 8872 S.DiagRuntimeBehavior( 8873 E->getOperatorLoc(), E, 8874 S.PDiag(!InRange ? diag::warn_out_of_range_compare 8875 : diag::warn_tautological_bool_compare) 8876 << OS.str() << classifyConstantValue(Constant) 8877 << OtherT << OtherIsBooleanDespiteType << *Result 8878 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8879 } else { 8880 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 8881 ? (HasEnumType(OriginalOther) 8882 ? diag::warn_unsigned_enum_always_true_comparison 8883 : diag::warn_unsigned_always_true_comparison) 8884 : diag::warn_tautological_constant_compare; 8885 8886 S.Diag(E->getOperatorLoc(), Diag) 8887 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 8888 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8889 } 8890 8891 return true; 8892 } 8893 8894 /// Analyze the operands of the given comparison. Implements the 8895 /// fallback case from AnalyzeComparison. 8896 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8897 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8898 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8899 } 8900 8901 /// \brief Implements -Wsign-compare. 8902 /// 8903 /// \param E the binary operator to check for warnings 8904 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8905 // The type the comparison is being performed in. 8906 QualType T = E->getLHS()->getType(); 8907 8908 // Only analyze comparison operators where both sides have been converted to 8909 // the same type. 8910 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8911 return AnalyzeImpConvsInComparison(S, E); 8912 8913 // Don't analyze value-dependent comparisons directly. 8914 if (E->isValueDependent()) 8915 return AnalyzeImpConvsInComparison(S, E); 8916 8917 Expr *LHS = E->getLHS(); 8918 Expr *RHS = E->getRHS(); 8919 8920 if (T->isIntegralType(S.Context)) { 8921 llvm::APSInt RHSValue; 8922 llvm::APSInt LHSValue; 8923 8924 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 8925 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 8926 8927 // We don't care about expressions whose result is a constant. 8928 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8929 return AnalyzeImpConvsInComparison(S, E); 8930 8931 // We only care about expressions where just one side is literal 8932 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 8933 // Is the constant on the RHS or LHS? 8934 const bool RhsConstant = IsRHSIntegralLiteral; 8935 Expr *Const = RhsConstant ? RHS : LHS; 8936 Expr *Other = RhsConstant ? LHS : RHS; 8937 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 8938 8939 // Check whether an integer constant comparison results in a value 8940 // of 'true' or 'false'. 8941 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 8942 return AnalyzeImpConvsInComparison(S, E); 8943 } 8944 } 8945 8946 if (!T->hasUnsignedIntegerRepresentation()) { 8947 // We don't do anything special if this isn't an unsigned integral 8948 // comparison: we're only interested in integral comparisons, and 8949 // signed comparisons only happen in cases we don't care to warn about. 8950 return AnalyzeImpConvsInComparison(S, E); 8951 } 8952 8953 LHS = LHS->IgnoreParenImpCasts(); 8954 RHS = RHS->IgnoreParenImpCasts(); 8955 8956 // Check to see if one of the (unmodified) operands is of different 8957 // signedness. 8958 Expr *signedOperand, *unsignedOperand; 8959 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8960 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8961 "unsigned comparison between two signed integer expressions?"); 8962 signedOperand = LHS; 8963 unsignedOperand = RHS; 8964 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8965 signedOperand = RHS; 8966 unsignedOperand = LHS; 8967 } else { 8968 return AnalyzeImpConvsInComparison(S, E); 8969 } 8970 8971 // Otherwise, calculate the effective range of the signed operand. 8972 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8973 8974 // Go ahead and analyze implicit conversions in the operands. Note 8975 // that we skip the implicit conversions on both sides. 8976 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8977 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8978 8979 // If the signed range is non-negative, -Wsign-compare won't fire. 8980 if (signedRange.NonNegative) 8981 return; 8982 8983 // For (in)equality comparisons, if the unsigned operand is a 8984 // constant which cannot collide with a overflowed signed operand, 8985 // then reinterpreting the signed operand as unsigned will not 8986 // change the result of the comparison. 8987 if (E->isEqualityOp()) { 8988 unsigned comparisonWidth = S.Context.getIntWidth(T); 8989 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8990 8991 // We should never be unable to prove that the unsigned operand is 8992 // non-negative. 8993 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8994 8995 if (unsignedRange.Width < comparisonWidth) 8996 return; 8997 } 8998 8999 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 9000 S.PDiag(diag::warn_mixed_sign_comparison) 9001 << LHS->getType() << RHS->getType() 9002 << LHS->getSourceRange() << RHS->getSourceRange()); 9003 } 9004 9005 /// Analyzes an attempt to assign the given value to a bitfield. 9006 /// 9007 /// Returns true if there was something fishy about the attempt. 9008 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 9009 SourceLocation InitLoc) { 9010 assert(Bitfield->isBitField()); 9011 if (Bitfield->isInvalidDecl()) 9012 return false; 9013 9014 // White-list bool bitfields. 9015 QualType BitfieldType = Bitfield->getType(); 9016 if (BitfieldType->isBooleanType()) 9017 return false; 9018 9019 if (BitfieldType->isEnumeralType()) { 9020 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 9021 // If the underlying enum type was not explicitly specified as an unsigned 9022 // type and the enum contain only positive values, MSVC++ will cause an 9023 // inconsistency by storing this as a signed type. 9024 if (S.getLangOpts().CPlusPlus11 && 9025 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 9026 BitfieldEnumDecl->getNumPositiveBits() > 0 && 9027 BitfieldEnumDecl->getNumNegativeBits() == 0) { 9028 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 9029 << BitfieldEnumDecl->getNameAsString(); 9030 } 9031 } 9032 9033 if (Bitfield->getType()->isBooleanType()) 9034 return false; 9035 9036 // Ignore value- or type-dependent expressions. 9037 if (Bitfield->getBitWidth()->isValueDependent() || 9038 Bitfield->getBitWidth()->isTypeDependent() || 9039 Init->isValueDependent() || 9040 Init->isTypeDependent()) 9041 return false; 9042 9043 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 9044 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 9045 9046 llvm::APSInt Value; 9047 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 9048 Expr::SE_AllowSideEffects)) { 9049 // The RHS is not constant. If the RHS has an enum type, make sure the 9050 // bitfield is wide enough to hold all the values of the enum without 9051 // truncation. 9052 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 9053 EnumDecl *ED = EnumTy->getDecl(); 9054 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 9055 9056 // Enum types are implicitly signed on Windows, so check if there are any 9057 // negative enumerators to see if the enum was intended to be signed or 9058 // not. 9059 bool SignedEnum = ED->getNumNegativeBits() > 0; 9060 9061 // Check for surprising sign changes when assigning enum values to a 9062 // bitfield of different signedness. If the bitfield is signed and we 9063 // have exactly the right number of bits to store this unsigned enum, 9064 // suggest changing the enum to an unsigned type. This typically happens 9065 // on Windows where unfixed enums always use an underlying type of 'int'. 9066 unsigned DiagID = 0; 9067 if (SignedEnum && !SignedBitfield) { 9068 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 9069 } else if (SignedBitfield && !SignedEnum && 9070 ED->getNumPositiveBits() == FieldWidth) { 9071 DiagID = diag::warn_signed_bitfield_enum_conversion; 9072 } 9073 9074 if (DiagID) { 9075 S.Diag(InitLoc, DiagID) << Bitfield << ED; 9076 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 9077 SourceRange TypeRange = 9078 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 9079 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 9080 << SignedEnum << TypeRange; 9081 } 9082 9083 // Compute the required bitwidth. If the enum has negative values, we need 9084 // one more bit than the normal number of positive bits to represent the 9085 // sign bit. 9086 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 9087 ED->getNumNegativeBits()) 9088 : ED->getNumPositiveBits(); 9089 9090 // Check the bitwidth. 9091 if (BitsNeeded > FieldWidth) { 9092 Expr *WidthExpr = Bitfield->getBitWidth(); 9093 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 9094 << Bitfield << ED; 9095 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 9096 << BitsNeeded << ED << WidthExpr->getSourceRange(); 9097 } 9098 } 9099 9100 return false; 9101 } 9102 9103 unsigned OriginalWidth = Value.getBitWidth(); 9104 9105 if (!Value.isSigned() || Value.isNegative()) 9106 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 9107 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 9108 OriginalWidth = Value.getMinSignedBits(); 9109 9110 if (OriginalWidth <= FieldWidth) 9111 return false; 9112 9113 // Compute the value which the bitfield will contain. 9114 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 9115 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 9116 9117 // Check whether the stored value is equal to the original value. 9118 TruncatedValue = TruncatedValue.extend(OriginalWidth); 9119 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 9120 return false; 9121 9122 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9123 // therefore don't strictly fit into a signed bitfield of width 1. 9124 if (FieldWidth == 1 && Value == 1) 9125 return false; 9126 9127 std::string PrettyValue = Value.toString(10); 9128 std::string PrettyTrunc = TruncatedValue.toString(10); 9129 9130 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9131 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9132 << Init->getSourceRange(); 9133 9134 return true; 9135 } 9136 9137 /// Analyze the given simple or compound assignment for warning-worthy 9138 /// operations. 9139 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9140 // Just recurse on the LHS. 9141 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9142 9143 // We want to recurse on the RHS as normal unless we're assigning to 9144 // a bitfield. 9145 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9146 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9147 E->getOperatorLoc())) { 9148 // Recurse, ignoring any implicit conversions on the RHS. 9149 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9150 E->getOperatorLoc()); 9151 } 9152 } 9153 9154 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9155 } 9156 9157 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9158 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9159 SourceLocation CContext, unsigned diag, 9160 bool pruneControlFlow = false) { 9161 if (pruneControlFlow) { 9162 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9163 S.PDiag(diag) 9164 << SourceType << T << E->getSourceRange() 9165 << SourceRange(CContext)); 9166 return; 9167 } 9168 S.Diag(E->getExprLoc(), diag) 9169 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9170 } 9171 9172 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9173 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 9174 SourceLocation CContext, 9175 unsigned diag, bool pruneControlFlow = false) { 9176 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9177 } 9178 9179 9180 /// Diagnose an implicit cast from a floating point value to an integer value. 9181 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9182 SourceLocation CContext) { 9183 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9184 const bool PruneWarnings = S.inTemplateInstantiation(); 9185 9186 Expr *InnerE = E->IgnoreParenImpCasts(); 9187 // We also want to warn on, e.g., "int i = -1.234" 9188 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9189 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9190 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9191 9192 const bool IsLiteral = 9193 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9194 9195 llvm::APFloat Value(0.0); 9196 bool IsConstant = 9197 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9198 if (!IsConstant) { 9199 return DiagnoseImpCast(S, E, T, CContext, 9200 diag::warn_impcast_float_integer, PruneWarnings); 9201 } 9202 9203 bool isExact = false; 9204 9205 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9206 T->hasUnsignedIntegerRepresentation()); 9207 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 9208 &isExact) == llvm::APFloat::opOK && 9209 isExact) { 9210 if (IsLiteral) return; 9211 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9212 PruneWarnings); 9213 } 9214 9215 unsigned DiagID = 0; 9216 if (IsLiteral) { 9217 // Warn on floating point literal to integer. 9218 DiagID = diag::warn_impcast_literal_float_to_integer; 9219 } else if (IntegerValue == 0) { 9220 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9221 return DiagnoseImpCast(S, E, T, CContext, 9222 diag::warn_impcast_float_integer, PruneWarnings); 9223 } 9224 // Warn on non-zero to zero conversion. 9225 DiagID = diag::warn_impcast_float_to_integer_zero; 9226 } else { 9227 if (IntegerValue.isUnsigned()) { 9228 if (!IntegerValue.isMaxValue()) { 9229 return DiagnoseImpCast(S, E, T, CContext, 9230 diag::warn_impcast_float_integer, PruneWarnings); 9231 } 9232 } else { // IntegerValue.isSigned() 9233 if (!IntegerValue.isMaxSignedValue() && 9234 !IntegerValue.isMinSignedValue()) { 9235 return DiagnoseImpCast(S, E, T, CContext, 9236 diag::warn_impcast_float_integer, PruneWarnings); 9237 } 9238 } 9239 // Warn on evaluatable floating point expression to integer conversion. 9240 DiagID = diag::warn_impcast_float_to_integer; 9241 } 9242 9243 // FIXME: Force the precision of the source value down so we don't print 9244 // digits which are usually useless (we don't really care here if we 9245 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9246 // would automatically print the shortest representation, but it's a bit 9247 // tricky to implement. 9248 SmallString<16> PrettySourceValue; 9249 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9250 precision = (precision * 59 + 195) / 196; 9251 Value.toString(PrettySourceValue, precision); 9252 9253 SmallString<16> PrettyTargetValue; 9254 if (IsBool) 9255 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9256 else 9257 IntegerValue.toString(PrettyTargetValue); 9258 9259 if (PruneWarnings) { 9260 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9261 S.PDiag(DiagID) 9262 << E->getType() << T.getUnqualifiedType() 9263 << PrettySourceValue << PrettyTargetValue 9264 << E->getSourceRange() << SourceRange(CContext)); 9265 } else { 9266 S.Diag(E->getExprLoc(), DiagID) 9267 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9268 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9269 } 9270 } 9271 9272 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 9273 IntRange Range) { 9274 if (!Range.Width) return "0"; 9275 9276 llvm::APSInt ValueInRange = Value; 9277 ValueInRange.setIsSigned(!Range.NonNegative); 9278 ValueInRange = ValueInRange.trunc(Range.Width); 9279 return ValueInRange.toString(10); 9280 } 9281 9282 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9283 if (!isa<ImplicitCastExpr>(Ex)) 9284 return false; 9285 9286 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9287 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9288 const Type *Source = 9289 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9290 if (Target->isDependentType()) 9291 return false; 9292 9293 const BuiltinType *FloatCandidateBT = 9294 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9295 const Type *BoolCandidateType = ToBool ? Target : Source; 9296 9297 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9298 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9299 } 9300 9301 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9302 SourceLocation CC) { 9303 unsigned NumArgs = TheCall->getNumArgs(); 9304 for (unsigned i = 0; i < NumArgs; ++i) { 9305 Expr *CurrA = TheCall->getArg(i); 9306 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9307 continue; 9308 9309 bool IsSwapped = ((i > 0) && 9310 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9311 IsSwapped |= ((i < (NumArgs - 1)) && 9312 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9313 if (IsSwapped) { 9314 // Warn on this floating-point to bool conversion. 9315 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9316 CurrA->getType(), CC, 9317 diag::warn_impcast_floating_point_to_bool); 9318 } 9319 } 9320 } 9321 9322 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 9323 SourceLocation CC) { 9324 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9325 E->getExprLoc())) 9326 return; 9327 9328 // Don't warn on functions which have return type nullptr_t. 9329 if (isa<CallExpr>(E)) 9330 return; 9331 9332 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9333 const Expr::NullPointerConstantKind NullKind = 9334 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9335 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9336 return; 9337 9338 // Return if target type is a safe conversion. 9339 if (T->isAnyPointerType() || T->isBlockPointerType() || 9340 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9341 return; 9342 9343 SourceLocation Loc = E->getSourceRange().getBegin(); 9344 9345 // Venture through the macro stacks to get to the source of macro arguments. 9346 // The new location is a better location than the complete location that was 9347 // passed in. 9348 while (S.SourceMgr.isMacroArgExpansion(Loc)) 9349 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 9350 9351 while (S.SourceMgr.isMacroArgExpansion(CC)) 9352 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 9353 9354 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9355 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9356 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9357 Loc, S.SourceMgr, S.getLangOpts()); 9358 if (MacroName == "NULL") 9359 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 9360 } 9361 9362 // Only warn if the null and context location are in the same macro expansion. 9363 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9364 return; 9365 9366 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9367 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 9368 << FixItHint::CreateReplacement(Loc, 9369 S.getFixItZeroLiteralForType(T, Loc)); 9370 } 9371 9372 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9373 ObjCArrayLiteral *ArrayLiteral); 9374 9375 static void 9376 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9377 ObjCDictionaryLiteral *DictionaryLiteral); 9378 9379 /// Check a single element within a collection literal against the 9380 /// target element type. 9381 static void checkObjCCollectionLiteralElement(Sema &S, 9382 QualType TargetElementType, 9383 Expr *Element, 9384 unsigned ElementKind) { 9385 // Skip a bitcast to 'id' or qualified 'id'. 9386 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9387 if (ICE->getCastKind() == CK_BitCast && 9388 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9389 Element = ICE->getSubExpr(); 9390 } 9391 9392 QualType ElementType = Element->getType(); 9393 ExprResult ElementResult(Element); 9394 if (ElementType->getAs<ObjCObjectPointerType>() && 9395 S.CheckSingleAssignmentConstraints(TargetElementType, 9396 ElementResult, 9397 false, false) 9398 != Sema::Compatible) { 9399 S.Diag(Element->getLocStart(), 9400 diag::warn_objc_collection_literal_element) 9401 << ElementType << ElementKind << TargetElementType 9402 << Element->getSourceRange(); 9403 } 9404 9405 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9406 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9407 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9408 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9409 } 9410 9411 /// Check an Objective-C array literal being converted to the given 9412 /// target type. 9413 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9414 ObjCArrayLiteral *ArrayLiteral) { 9415 if (!S.NSArrayDecl) 9416 return; 9417 9418 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9419 if (!TargetObjCPtr) 9420 return; 9421 9422 if (TargetObjCPtr->isUnspecialized() || 9423 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9424 != S.NSArrayDecl->getCanonicalDecl()) 9425 return; 9426 9427 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9428 if (TypeArgs.size() != 1) 9429 return; 9430 9431 QualType TargetElementType = TypeArgs[0]; 9432 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9433 checkObjCCollectionLiteralElement(S, TargetElementType, 9434 ArrayLiteral->getElement(I), 9435 0); 9436 } 9437 } 9438 9439 /// Check an Objective-C dictionary literal being converted to the given 9440 /// target type. 9441 static void 9442 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9443 ObjCDictionaryLiteral *DictionaryLiteral) { 9444 if (!S.NSDictionaryDecl) 9445 return; 9446 9447 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9448 if (!TargetObjCPtr) 9449 return; 9450 9451 if (TargetObjCPtr->isUnspecialized() || 9452 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9453 != S.NSDictionaryDecl->getCanonicalDecl()) 9454 return; 9455 9456 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9457 if (TypeArgs.size() != 2) 9458 return; 9459 9460 QualType TargetKeyType = TypeArgs[0]; 9461 QualType TargetObjectType = TypeArgs[1]; 9462 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9463 auto Element = DictionaryLiteral->getKeyValueElement(I); 9464 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9465 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9466 } 9467 } 9468 9469 // Helper function to filter out cases for constant width constant conversion. 9470 // Don't warn on char array initialization or for non-decimal values. 9471 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9472 SourceLocation CC) { 9473 // If initializing from a constant, and the constant starts with '0', 9474 // then it is a binary, octal, or hexadecimal. Allow these constants 9475 // to fill all the bits, even if there is a sign change. 9476 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9477 const char FirstLiteralCharacter = 9478 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9479 if (FirstLiteralCharacter == '0') 9480 return false; 9481 } 9482 9483 // If the CC location points to a '{', and the type is char, then assume 9484 // assume it is an array initialization. 9485 if (CC.isValid() && T->isCharType()) { 9486 const char FirstContextCharacter = 9487 S.getSourceManager().getCharacterData(CC)[0]; 9488 if (FirstContextCharacter == '{') 9489 return false; 9490 } 9491 9492 return true; 9493 } 9494 9495 static void 9496 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 9497 bool *ICContext = nullptr) { 9498 if (E->isTypeDependent() || E->isValueDependent()) return; 9499 9500 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9501 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9502 if (Source == Target) return; 9503 if (Target->isDependentType()) return; 9504 9505 // If the conversion context location is invalid don't complain. We also 9506 // don't want to emit a warning if the issue occurs from the expansion of 9507 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9508 // delay this check as long as possible. Once we detect we are in that 9509 // scenario, we just return. 9510 if (CC.isInvalid()) 9511 return; 9512 9513 // Diagnose implicit casts to bool. 9514 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9515 if (isa<StringLiteral>(E)) 9516 // Warn on string literal to bool. Checks for string literals in logical 9517 // and expressions, for instance, assert(0 && "error here"), are 9518 // prevented by a check in AnalyzeImplicitConversions(). 9519 return DiagnoseImpCast(S, E, T, CC, 9520 diag::warn_impcast_string_literal_to_bool); 9521 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9522 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9523 // This covers the literal expressions that evaluate to Objective-C 9524 // objects. 9525 return DiagnoseImpCast(S, E, T, CC, 9526 diag::warn_impcast_objective_c_literal_to_bool); 9527 } 9528 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9529 // Warn on pointer to bool conversion that is always true. 9530 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9531 SourceRange(CC)); 9532 } 9533 } 9534 9535 // Check implicit casts from Objective-C collection literals to specialized 9536 // collection types, e.g., NSArray<NSString *> *. 9537 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9538 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9539 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9540 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9541 9542 // Strip vector types. 9543 if (isa<VectorType>(Source)) { 9544 if (!isa<VectorType>(Target)) { 9545 if (S.SourceMgr.isInSystemMacro(CC)) 9546 return; 9547 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9548 } 9549 9550 // If the vector cast is cast between two vectors of the same size, it is 9551 // a bitcast, not a conversion. 9552 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9553 return; 9554 9555 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9556 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9557 } 9558 if (auto VecTy = dyn_cast<VectorType>(Target)) 9559 Target = VecTy->getElementType().getTypePtr(); 9560 9561 // Strip complex types. 9562 if (isa<ComplexType>(Source)) { 9563 if (!isa<ComplexType>(Target)) { 9564 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 9565 return; 9566 9567 return DiagnoseImpCast(S, E, T, CC, 9568 S.getLangOpts().CPlusPlus 9569 ? diag::err_impcast_complex_scalar 9570 : diag::warn_impcast_complex_scalar); 9571 } 9572 9573 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9574 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9575 } 9576 9577 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9578 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9579 9580 // If the source is floating point... 9581 if (SourceBT && SourceBT->isFloatingPoint()) { 9582 // ...and the target is floating point... 9583 if (TargetBT && TargetBT->isFloatingPoint()) { 9584 // ...then warn if we're dropping FP rank. 9585 9586 // Builtin FP kinds are ordered by increasing FP rank. 9587 if (SourceBT->getKind() > TargetBT->getKind()) { 9588 // Don't warn about float constants that are precisely 9589 // representable in the target type. 9590 Expr::EvalResult result; 9591 if (E->EvaluateAsRValue(result, S.Context)) { 9592 // Value might be a float, a float vector, or a float complex. 9593 if (IsSameFloatAfterCast(result.Val, 9594 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9595 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9596 return; 9597 } 9598 9599 if (S.SourceMgr.isInSystemMacro(CC)) 9600 return; 9601 9602 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9603 } 9604 // ... or possibly if we're increasing rank, too 9605 else if (TargetBT->getKind() > SourceBT->getKind()) { 9606 if (S.SourceMgr.isInSystemMacro(CC)) 9607 return; 9608 9609 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9610 } 9611 return; 9612 } 9613 9614 // If the target is integral, always warn. 9615 if (TargetBT && TargetBT->isInteger()) { 9616 if (S.SourceMgr.isInSystemMacro(CC)) 9617 return; 9618 9619 DiagnoseFloatingImpCast(S, E, T, CC); 9620 } 9621 9622 // Detect the case where a call result is converted from floating-point to 9623 // to bool, and the final argument to the call is converted from bool, to 9624 // discover this typo: 9625 // 9626 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9627 // 9628 // FIXME: This is an incredibly special case; is there some more general 9629 // way to detect this class of misplaced-parentheses bug? 9630 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9631 // Check last argument of function call to see if it is an 9632 // implicit cast from a type matching the type the result 9633 // is being cast to. 9634 CallExpr *CEx = cast<CallExpr>(E); 9635 if (unsigned NumArgs = CEx->getNumArgs()) { 9636 Expr *LastA = CEx->getArg(NumArgs - 1); 9637 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9638 if (isa<ImplicitCastExpr>(LastA) && 9639 InnerE->getType()->isBooleanType()) { 9640 // Warn on this floating-point to bool conversion 9641 DiagnoseImpCast(S, E, T, CC, 9642 diag::warn_impcast_floating_point_to_bool); 9643 } 9644 } 9645 } 9646 return; 9647 } 9648 9649 DiagnoseNullConversion(S, E, T, CC); 9650 9651 S.DiscardMisalignedMemberAddress(Target, E); 9652 9653 if (!Source->isIntegerType() || !Target->isIntegerType()) 9654 return; 9655 9656 // TODO: remove this early return once the false positives for constant->bool 9657 // in templates, macros, etc, are reduced or removed. 9658 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9659 return; 9660 9661 IntRange SourceRange = GetExprRange(S.Context, E); 9662 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9663 9664 if (SourceRange.Width > TargetRange.Width) { 9665 // If the source is a constant, use a default-on diagnostic. 9666 // TODO: this should happen for bitfield stores, too. 9667 llvm::APSInt Value(32); 9668 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9669 if (S.SourceMgr.isInSystemMacro(CC)) 9670 return; 9671 9672 std::string PrettySourceValue = Value.toString(10); 9673 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9674 9675 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9676 S.PDiag(diag::warn_impcast_integer_precision_constant) 9677 << PrettySourceValue << PrettyTargetValue 9678 << E->getType() << T << E->getSourceRange() 9679 << clang::SourceRange(CC)); 9680 return; 9681 } 9682 9683 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9684 if (S.SourceMgr.isInSystemMacro(CC)) 9685 return; 9686 9687 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9688 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9689 /* pruneControlFlow */ true); 9690 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9691 } 9692 9693 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9694 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9695 // Warn when doing a signed to signed conversion, warn if the positive 9696 // source value is exactly the width of the target type, which will 9697 // cause a negative value to be stored. 9698 9699 llvm::APSInt Value; 9700 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9701 !S.SourceMgr.isInSystemMacro(CC)) { 9702 if (isSameWidthConstantConversion(S, E, T, CC)) { 9703 std::string PrettySourceValue = Value.toString(10); 9704 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9705 9706 S.DiagRuntimeBehavior( 9707 E->getExprLoc(), E, 9708 S.PDiag(diag::warn_impcast_integer_precision_constant) 9709 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9710 << E->getSourceRange() << clang::SourceRange(CC)); 9711 return; 9712 } 9713 } 9714 9715 // Fall through for non-constants to give a sign conversion warning. 9716 } 9717 9718 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9719 (!TargetRange.NonNegative && SourceRange.NonNegative && 9720 SourceRange.Width == TargetRange.Width)) { 9721 if (S.SourceMgr.isInSystemMacro(CC)) 9722 return; 9723 9724 unsigned DiagID = diag::warn_impcast_integer_sign; 9725 9726 // Traditionally, gcc has warned about this under -Wsign-compare. 9727 // We also want to warn about it in -Wconversion. 9728 // So if -Wconversion is off, use a completely identical diagnostic 9729 // in the sign-compare group. 9730 // The conditional-checking code will 9731 if (ICContext) { 9732 DiagID = diag::warn_impcast_integer_sign_conditional; 9733 *ICContext = true; 9734 } 9735 9736 return DiagnoseImpCast(S, E, T, CC, DiagID); 9737 } 9738 9739 // Diagnose conversions between different enumeration types. 9740 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9741 // type, to give us better diagnostics. 9742 QualType SourceType = E->getType(); 9743 if (!S.getLangOpts().CPlusPlus) { 9744 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9745 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9746 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9747 SourceType = S.Context.getTypeDeclType(Enum); 9748 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9749 } 9750 } 9751 9752 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9753 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9754 if (SourceEnum->getDecl()->hasNameForLinkage() && 9755 TargetEnum->getDecl()->hasNameForLinkage() && 9756 SourceEnum != TargetEnum) { 9757 if (S.SourceMgr.isInSystemMacro(CC)) 9758 return; 9759 9760 return DiagnoseImpCast(S, E, SourceType, T, CC, 9761 diag::warn_impcast_different_enum_types); 9762 } 9763 } 9764 9765 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9766 SourceLocation CC, QualType T); 9767 9768 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9769 SourceLocation CC, bool &ICContext) { 9770 E = E->IgnoreParenImpCasts(); 9771 9772 if (isa<ConditionalOperator>(E)) 9773 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9774 9775 AnalyzeImplicitConversions(S, E, CC); 9776 if (E->getType() != T) 9777 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9778 } 9779 9780 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9781 SourceLocation CC, QualType T) { 9782 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9783 9784 bool Suspicious = false; 9785 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9786 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9787 9788 // If -Wconversion would have warned about either of the candidates 9789 // for a signedness conversion to the context type... 9790 if (!Suspicious) return; 9791 9792 // ...but it's currently ignored... 9793 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9794 return; 9795 9796 // ...then check whether it would have warned about either of the 9797 // candidates for a signedness conversion to the condition type. 9798 if (E->getType() == T) return; 9799 9800 Suspicious = false; 9801 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9802 E->getType(), CC, &Suspicious); 9803 if (!Suspicious) 9804 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9805 E->getType(), CC, &Suspicious); 9806 } 9807 9808 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9809 /// Input argument E is a logical expression. 9810 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9811 if (S.getLangOpts().Bool) 9812 return; 9813 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9814 } 9815 9816 /// AnalyzeImplicitConversions - Find and report any interesting 9817 /// implicit conversions in the given expression. There are a couple 9818 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9819 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 9820 SourceLocation CC) { 9821 QualType T = OrigE->getType(); 9822 Expr *E = OrigE->IgnoreParenImpCasts(); 9823 9824 if (E->isTypeDependent() || E->isValueDependent()) 9825 return; 9826 9827 // For conditional operators, we analyze the arguments as if they 9828 // were being fed directly into the output. 9829 if (isa<ConditionalOperator>(E)) { 9830 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9831 CheckConditionalOperator(S, CO, CC, T); 9832 return; 9833 } 9834 9835 // Check implicit argument conversions for function calls. 9836 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9837 CheckImplicitArgumentConversions(S, Call, CC); 9838 9839 // Go ahead and check any implicit conversions we might have skipped. 9840 // The non-canonical typecheck is just an optimization; 9841 // CheckImplicitConversion will filter out dead implicit conversions. 9842 if (E->getType() != T) 9843 CheckImplicitConversion(S, E, T, CC); 9844 9845 // Now continue drilling into this expression. 9846 9847 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9848 // The bound subexpressions in a PseudoObjectExpr are not reachable 9849 // as transitive children. 9850 // FIXME: Use a more uniform representation for this. 9851 for (auto *SE : POE->semantics()) 9852 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9853 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9854 } 9855 9856 // Skip past explicit casts. 9857 if (isa<ExplicitCastExpr>(E)) { 9858 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9859 return AnalyzeImplicitConversions(S, E, CC); 9860 } 9861 9862 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9863 // Do a somewhat different check with comparison operators. 9864 if (BO->isComparisonOp()) 9865 return AnalyzeComparison(S, BO); 9866 9867 // And with simple assignments. 9868 if (BO->getOpcode() == BO_Assign) 9869 return AnalyzeAssignment(S, BO); 9870 } 9871 9872 // These break the otherwise-useful invariant below. Fortunately, 9873 // we don't really need to recurse into them, because any internal 9874 // expressions should have been analyzed already when they were 9875 // built into statements. 9876 if (isa<StmtExpr>(E)) return; 9877 9878 // Don't descend into unevaluated contexts. 9879 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9880 9881 // Now just recurse over the expression's children. 9882 CC = E->getExprLoc(); 9883 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9884 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9885 for (Stmt *SubStmt : E->children()) { 9886 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9887 if (!ChildExpr) 9888 continue; 9889 9890 if (IsLogicalAndOperator && 9891 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9892 // Ignore checking string literals that are in logical and operators. 9893 // This is a common pattern for asserts. 9894 continue; 9895 AnalyzeImplicitConversions(S, ChildExpr, CC); 9896 } 9897 9898 if (BO && BO->isLogicalOp()) { 9899 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9900 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9901 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9902 9903 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9904 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9905 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9906 } 9907 9908 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9909 if (U->getOpcode() == UO_LNot) 9910 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9911 } 9912 9913 /// Diagnose integer type and any valid implicit convertion to it. 9914 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 9915 // Taking into account implicit conversions, 9916 // allow any integer. 9917 if (!E->getType()->isIntegerType()) { 9918 S.Diag(E->getLocStart(), 9919 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9920 return true; 9921 } 9922 // Potentially emit standard warnings for implicit conversions if enabled 9923 // using -Wconversion. 9924 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 9925 return false; 9926 } 9927 9928 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9929 // Returns true when emitting a warning about taking the address of a reference. 9930 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9931 const PartialDiagnostic &PD) { 9932 E = E->IgnoreParenImpCasts(); 9933 9934 const FunctionDecl *FD = nullptr; 9935 9936 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9937 if (!DRE->getDecl()->getType()->isReferenceType()) 9938 return false; 9939 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9940 if (!M->getMemberDecl()->getType()->isReferenceType()) 9941 return false; 9942 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9943 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9944 return false; 9945 FD = Call->getDirectCallee(); 9946 } else { 9947 return false; 9948 } 9949 9950 SemaRef.Diag(E->getExprLoc(), PD); 9951 9952 // If possible, point to location of function. 9953 if (FD) { 9954 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9955 } 9956 9957 return true; 9958 } 9959 9960 // Returns true if the SourceLocation is expanded from any macro body. 9961 // Returns false if the SourceLocation is invalid, is from not in a macro 9962 // expansion, or is from expanded from a top-level macro argument. 9963 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9964 if (Loc.isInvalid()) 9965 return false; 9966 9967 while (Loc.isMacroID()) { 9968 if (SM.isMacroBodyExpansion(Loc)) 9969 return true; 9970 Loc = SM.getImmediateMacroCallerLoc(Loc); 9971 } 9972 9973 return false; 9974 } 9975 9976 /// \brief Diagnose pointers that are always non-null. 9977 /// \param E the expression containing the pointer 9978 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9979 /// compared to a null pointer 9980 /// \param IsEqual True when the comparison is equal to a null pointer 9981 /// \param Range Extra SourceRange to highlight in the diagnostic 9982 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9983 Expr::NullPointerConstantKind NullKind, 9984 bool IsEqual, SourceRange Range) { 9985 if (!E) 9986 return; 9987 9988 // Don't warn inside macros. 9989 if (E->getExprLoc().isMacroID()) { 9990 const SourceManager &SM = getSourceManager(); 9991 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9992 IsInAnyMacroBody(SM, Range.getBegin())) 9993 return; 9994 } 9995 E = E->IgnoreImpCasts(); 9996 9997 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9998 9999 if (isa<CXXThisExpr>(E)) { 10000 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 10001 : diag::warn_this_bool_conversion; 10002 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 10003 return; 10004 } 10005 10006 bool IsAddressOf = false; 10007 10008 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10009 if (UO->getOpcode() != UO_AddrOf) 10010 return; 10011 IsAddressOf = true; 10012 E = UO->getSubExpr(); 10013 } 10014 10015 if (IsAddressOf) { 10016 unsigned DiagID = IsCompare 10017 ? diag::warn_address_of_reference_null_compare 10018 : diag::warn_address_of_reference_bool_conversion; 10019 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 10020 << IsEqual; 10021 if (CheckForReference(*this, E, PD)) { 10022 return; 10023 } 10024 } 10025 10026 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 10027 bool IsParam = isa<NonNullAttr>(NonnullAttr); 10028 std::string Str; 10029 llvm::raw_string_ostream S(Str); 10030 E->printPretty(S, nullptr, getPrintingPolicy()); 10031 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 10032 : diag::warn_cast_nonnull_to_bool; 10033 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 10034 << E->getSourceRange() << Range << IsEqual; 10035 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 10036 }; 10037 10038 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 10039 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 10040 if (auto *Callee = Call->getDirectCallee()) { 10041 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 10042 ComplainAboutNonnullParamOrCall(A); 10043 return; 10044 } 10045 } 10046 } 10047 10048 // Expect to find a single Decl. Skip anything more complicated. 10049 ValueDecl *D = nullptr; 10050 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 10051 D = R->getDecl(); 10052 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10053 D = M->getMemberDecl(); 10054 } 10055 10056 // Weak Decls can be null. 10057 if (!D || D->isWeak()) 10058 return; 10059 10060 // Check for parameter decl with nonnull attribute 10061 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 10062 if (getCurFunction() && 10063 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 10064 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 10065 ComplainAboutNonnullParamOrCall(A); 10066 return; 10067 } 10068 10069 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 10070 auto ParamIter = llvm::find(FD->parameters(), PV); 10071 assert(ParamIter != FD->param_end()); 10072 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 10073 10074 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 10075 if (!NonNull->args_size()) { 10076 ComplainAboutNonnullParamOrCall(NonNull); 10077 return; 10078 } 10079 10080 for (unsigned ArgNo : NonNull->args()) { 10081 if (ArgNo == ParamNo) { 10082 ComplainAboutNonnullParamOrCall(NonNull); 10083 return; 10084 } 10085 } 10086 } 10087 } 10088 } 10089 } 10090 10091 QualType T = D->getType(); 10092 const bool IsArray = T->isArrayType(); 10093 const bool IsFunction = T->isFunctionType(); 10094 10095 // Address of function is used to silence the function warning. 10096 if (IsAddressOf && IsFunction) { 10097 return; 10098 } 10099 10100 // Found nothing. 10101 if (!IsAddressOf && !IsFunction && !IsArray) 10102 return; 10103 10104 // Pretty print the expression for the diagnostic. 10105 std::string Str; 10106 llvm::raw_string_ostream S(Str); 10107 E->printPretty(S, nullptr, getPrintingPolicy()); 10108 10109 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 10110 : diag::warn_impcast_pointer_to_bool; 10111 enum { 10112 AddressOf, 10113 FunctionPointer, 10114 ArrayPointer 10115 } DiagType; 10116 if (IsAddressOf) 10117 DiagType = AddressOf; 10118 else if (IsFunction) 10119 DiagType = FunctionPointer; 10120 else if (IsArray) 10121 DiagType = ArrayPointer; 10122 else 10123 llvm_unreachable("Could not determine diagnostic."); 10124 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 10125 << Range << IsEqual; 10126 10127 if (!IsFunction) 10128 return; 10129 10130 // Suggest '&' to silence the function warning. 10131 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10132 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10133 10134 // Check to see if '()' fixit should be emitted. 10135 QualType ReturnType; 10136 UnresolvedSet<4> NonTemplateOverloads; 10137 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10138 if (ReturnType.isNull()) 10139 return; 10140 10141 if (IsCompare) { 10142 // There are two cases here. If there is null constant, the only suggest 10143 // for a pointer return type. If the null is 0, then suggest if the return 10144 // type is a pointer or an integer type. 10145 if (!ReturnType->isPointerType()) { 10146 if (NullKind == Expr::NPCK_ZeroExpression || 10147 NullKind == Expr::NPCK_ZeroLiteral) { 10148 if (!ReturnType->isIntegerType()) 10149 return; 10150 } else { 10151 return; 10152 } 10153 } 10154 } else { // !IsCompare 10155 // For function to bool, only suggest if the function pointer has bool 10156 // return type. 10157 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10158 return; 10159 } 10160 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10161 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10162 } 10163 10164 /// Diagnoses "dangerous" implicit conversions within the given 10165 /// expression (which is a full expression). Implements -Wconversion 10166 /// and -Wsign-compare. 10167 /// 10168 /// \param CC the "context" location of the implicit conversion, i.e. 10169 /// the most location of the syntactic entity requiring the implicit 10170 /// conversion 10171 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10172 // Don't diagnose in unevaluated contexts. 10173 if (isUnevaluatedContext()) 10174 return; 10175 10176 // Don't diagnose for value- or type-dependent expressions. 10177 if (E->isTypeDependent() || E->isValueDependent()) 10178 return; 10179 10180 // Check for array bounds violations in cases where the check isn't triggered 10181 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10182 // ArraySubscriptExpr is on the RHS of a variable initialization. 10183 CheckArrayAccess(E); 10184 10185 // This is not the right CC for (e.g.) a variable initialization. 10186 AnalyzeImplicitConversions(*this, E, CC); 10187 } 10188 10189 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10190 /// Input argument E is a logical expression. 10191 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10192 ::CheckBoolLikeConversion(*this, E, CC); 10193 } 10194 10195 /// Diagnose when expression is an integer constant expression and its evaluation 10196 /// results in integer overflow 10197 void Sema::CheckForIntOverflow (Expr *E) { 10198 // Use a work list to deal with nested struct initializers. 10199 SmallVector<Expr *, 2> Exprs(1, E); 10200 10201 do { 10202 Expr *E = Exprs.pop_back_val(); 10203 10204 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 10205 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10206 continue; 10207 } 10208 10209 if (auto InitList = dyn_cast<InitListExpr>(E)) 10210 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10211 10212 if (isa<ObjCBoxedExpr>(E)) 10213 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10214 } while (!Exprs.empty()); 10215 } 10216 10217 namespace { 10218 10219 /// \brief Visitor for expressions which looks for unsequenced operations on the 10220 /// same object. 10221 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10222 using Base = EvaluatedExprVisitor<SequenceChecker>; 10223 10224 /// \brief A tree of sequenced regions within an expression. Two regions are 10225 /// unsequenced if one is an ancestor or a descendent of the other. When we 10226 /// finish processing an expression with sequencing, such as a comma 10227 /// expression, we fold its tree nodes into its parent, since they are 10228 /// unsequenced with respect to nodes we will visit later. 10229 class SequenceTree { 10230 struct Value { 10231 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10232 unsigned Parent : 31; 10233 unsigned Merged : 1; 10234 }; 10235 SmallVector<Value, 8> Values; 10236 10237 public: 10238 /// \brief A region within an expression which may be sequenced with respect 10239 /// to some other region. 10240 class Seq { 10241 friend class SequenceTree; 10242 10243 unsigned Index = 0; 10244 10245 explicit Seq(unsigned N) : Index(N) {} 10246 10247 public: 10248 Seq() = default; 10249 }; 10250 10251 SequenceTree() { Values.push_back(Value(0)); } 10252 Seq root() const { return Seq(0); } 10253 10254 /// \brief Create a new sequence of operations, which is an unsequenced 10255 /// subset of \p Parent. This sequence of operations is sequenced with 10256 /// respect to other children of \p Parent. 10257 Seq allocate(Seq Parent) { 10258 Values.push_back(Value(Parent.Index)); 10259 return Seq(Values.size() - 1); 10260 } 10261 10262 /// \brief Merge a sequence of operations into its parent. 10263 void merge(Seq S) { 10264 Values[S.Index].Merged = true; 10265 } 10266 10267 /// \brief Determine whether two operations are unsequenced. This operation 10268 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10269 /// should have been merged into its parent as appropriate. 10270 bool isUnsequenced(Seq Cur, Seq Old) { 10271 unsigned C = representative(Cur.Index); 10272 unsigned Target = representative(Old.Index); 10273 while (C >= Target) { 10274 if (C == Target) 10275 return true; 10276 C = Values[C].Parent; 10277 } 10278 return false; 10279 } 10280 10281 private: 10282 /// \brief Pick a representative for a sequence. 10283 unsigned representative(unsigned K) { 10284 if (Values[K].Merged) 10285 // Perform path compression as we go. 10286 return Values[K].Parent = representative(Values[K].Parent); 10287 return K; 10288 } 10289 }; 10290 10291 /// An object for which we can track unsequenced uses. 10292 using Object = NamedDecl *; 10293 10294 /// Different flavors of object usage which we track. We only track the 10295 /// least-sequenced usage of each kind. 10296 enum UsageKind { 10297 /// A read of an object. Multiple unsequenced reads are OK. 10298 UK_Use, 10299 10300 /// A modification of an object which is sequenced before the value 10301 /// computation of the expression, such as ++n in C++. 10302 UK_ModAsValue, 10303 10304 /// A modification of an object which is not sequenced before the value 10305 /// computation of the expression, such as n++. 10306 UK_ModAsSideEffect, 10307 10308 UK_Count = UK_ModAsSideEffect + 1 10309 }; 10310 10311 struct Usage { 10312 Expr *Use = nullptr; 10313 SequenceTree::Seq Seq; 10314 10315 Usage() = default; 10316 }; 10317 10318 struct UsageInfo { 10319 Usage Uses[UK_Count]; 10320 10321 /// Have we issued a diagnostic for this variable already? 10322 bool Diagnosed = false; 10323 10324 UsageInfo() = default; 10325 }; 10326 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 10327 10328 Sema &SemaRef; 10329 10330 /// Sequenced regions within the expression. 10331 SequenceTree Tree; 10332 10333 /// Declaration modifications and references which we have seen. 10334 UsageInfoMap UsageMap; 10335 10336 /// The region we are currently within. 10337 SequenceTree::Seq Region; 10338 10339 /// Filled in with declarations which were modified as a side-effect 10340 /// (that is, post-increment operations). 10341 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 10342 10343 /// Expressions to check later. We defer checking these to reduce 10344 /// stack usage. 10345 SmallVectorImpl<Expr *> &WorkList; 10346 10347 /// RAII object wrapping the visitation of a sequenced subexpression of an 10348 /// expression. At the end of this process, the side-effects of the evaluation 10349 /// become sequenced with respect to the value computation of the result, so 10350 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10351 /// UK_ModAsValue. 10352 struct SequencedSubexpression { 10353 SequencedSubexpression(SequenceChecker &Self) 10354 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 10355 Self.ModAsSideEffect = &ModAsSideEffect; 10356 } 10357 10358 ~SequencedSubexpression() { 10359 for (auto &M : llvm::reverse(ModAsSideEffect)) { 10360 UsageInfo &U = Self.UsageMap[M.first]; 10361 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 10362 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 10363 SideEffectUsage = M.second; 10364 } 10365 Self.ModAsSideEffect = OldModAsSideEffect; 10366 } 10367 10368 SequenceChecker &Self; 10369 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 10370 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 10371 }; 10372 10373 /// RAII object wrapping the visitation of a subexpression which we might 10374 /// choose to evaluate as a constant. If any subexpression is evaluated and 10375 /// found to be non-constant, this allows us to suppress the evaluation of 10376 /// the outer expression. 10377 class EvaluationTracker { 10378 public: 10379 EvaluationTracker(SequenceChecker &Self) 10380 : Self(Self), Prev(Self.EvalTracker) { 10381 Self.EvalTracker = this; 10382 } 10383 10384 ~EvaluationTracker() { 10385 Self.EvalTracker = Prev; 10386 if (Prev) 10387 Prev->EvalOK &= EvalOK; 10388 } 10389 10390 bool evaluate(const Expr *E, bool &Result) { 10391 if (!EvalOK || E->isValueDependent()) 10392 return false; 10393 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 10394 return EvalOK; 10395 } 10396 10397 private: 10398 SequenceChecker &Self; 10399 EvaluationTracker *Prev; 10400 bool EvalOK = true; 10401 } *EvalTracker = nullptr; 10402 10403 /// \brief Find the object which is produced by the specified expression, 10404 /// if any. 10405 Object getObject(Expr *E, bool Mod) const { 10406 E = E->IgnoreParenCasts(); 10407 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10408 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 10409 return getObject(UO->getSubExpr(), Mod); 10410 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10411 if (BO->getOpcode() == BO_Comma) 10412 return getObject(BO->getRHS(), Mod); 10413 if (Mod && BO->isAssignmentOp()) 10414 return getObject(BO->getLHS(), Mod); 10415 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10416 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 10417 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 10418 return ME->getMemberDecl(); 10419 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10420 // FIXME: If this is a reference, map through to its value. 10421 return DRE->getDecl(); 10422 return nullptr; 10423 } 10424 10425 /// \brief Note that an object was modified or used by an expression. 10426 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 10427 Usage &U = UI.Uses[UK]; 10428 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 10429 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 10430 ModAsSideEffect->push_back(std::make_pair(O, U)); 10431 U.Use = Ref; 10432 U.Seq = Region; 10433 } 10434 } 10435 10436 /// \brief Check whether a modification or use conflicts with a prior usage. 10437 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 10438 bool IsModMod) { 10439 if (UI.Diagnosed) 10440 return; 10441 10442 const Usage &U = UI.Uses[OtherKind]; 10443 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 10444 return; 10445 10446 Expr *Mod = U.Use; 10447 Expr *ModOrUse = Ref; 10448 if (OtherKind == UK_Use) 10449 std::swap(Mod, ModOrUse); 10450 10451 SemaRef.Diag(Mod->getExprLoc(), 10452 IsModMod ? diag::warn_unsequenced_mod_mod 10453 : diag::warn_unsequenced_mod_use) 10454 << O << SourceRange(ModOrUse->getExprLoc()); 10455 UI.Diagnosed = true; 10456 } 10457 10458 void notePreUse(Object O, Expr *Use) { 10459 UsageInfo &U = UsageMap[O]; 10460 // Uses conflict with other modifications. 10461 checkUsage(O, U, Use, UK_ModAsValue, false); 10462 } 10463 10464 void notePostUse(Object O, Expr *Use) { 10465 UsageInfo &U = UsageMap[O]; 10466 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 10467 addUsage(U, O, Use, UK_Use); 10468 } 10469 10470 void notePreMod(Object O, Expr *Mod) { 10471 UsageInfo &U = UsageMap[O]; 10472 // Modifications conflict with other modifications and with uses. 10473 checkUsage(O, U, Mod, UK_ModAsValue, true); 10474 checkUsage(O, U, Mod, UK_Use, false); 10475 } 10476 10477 void notePostMod(Object O, Expr *Use, UsageKind UK) { 10478 UsageInfo &U = UsageMap[O]; 10479 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 10480 addUsage(U, O, Use, UK); 10481 } 10482 10483 public: 10484 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 10485 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 10486 Visit(E); 10487 } 10488 10489 void VisitStmt(Stmt *S) { 10490 // Skip all statements which aren't expressions for now. 10491 } 10492 10493 void VisitExpr(Expr *E) { 10494 // By default, just recurse to evaluated subexpressions. 10495 Base::VisitStmt(E); 10496 } 10497 10498 void VisitCastExpr(CastExpr *E) { 10499 Object O = Object(); 10500 if (E->getCastKind() == CK_LValueToRValue) 10501 O = getObject(E->getSubExpr(), false); 10502 10503 if (O) 10504 notePreUse(O, E); 10505 VisitExpr(E); 10506 if (O) 10507 notePostUse(O, E); 10508 } 10509 10510 void VisitBinComma(BinaryOperator *BO) { 10511 // C++11 [expr.comma]p1: 10512 // Every value computation and side effect associated with the left 10513 // expression is sequenced before every value computation and side 10514 // effect associated with the right expression. 10515 SequenceTree::Seq LHS = Tree.allocate(Region); 10516 SequenceTree::Seq RHS = Tree.allocate(Region); 10517 SequenceTree::Seq OldRegion = Region; 10518 10519 { 10520 SequencedSubexpression SeqLHS(*this); 10521 Region = LHS; 10522 Visit(BO->getLHS()); 10523 } 10524 10525 Region = RHS; 10526 Visit(BO->getRHS()); 10527 10528 Region = OldRegion; 10529 10530 // Forget that LHS and RHS are sequenced. They are both unsequenced 10531 // with respect to other stuff. 10532 Tree.merge(LHS); 10533 Tree.merge(RHS); 10534 } 10535 10536 void VisitBinAssign(BinaryOperator *BO) { 10537 // The modification is sequenced after the value computation of the LHS 10538 // and RHS, so check it before inspecting the operands and update the 10539 // map afterwards. 10540 Object O = getObject(BO->getLHS(), true); 10541 if (!O) 10542 return VisitExpr(BO); 10543 10544 notePreMod(O, BO); 10545 10546 // C++11 [expr.ass]p7: 10547 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 10548 // only once. 10549 // 10550 // Therefore, for a compound assignment operator, O is considered used 10551 // everywhere except within the evaluation of E1 itself. 10552 if (isa<CompoundAssignOperator>(BO)) 10553 notePreUse(O, BO); 10554 10555 Visit(BO->getLHS()); 10556 10557 if (isa<CompoundAssignOperator>(BO)) 10558 notePostUse(O, BO); 10559 10560 Visit(BO->getRHS()); 10561 10562 // C++11 [expr.ass]p1: 10563 // the assignment is sequenced [...] before the value computation of the 10564 // assignment expression. 10565 // C11 6.5.16/3 has no such rule. 10566 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10567 : UK_ModAsSideEffect); 10568 } 10569 10570 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 10571 VisitBinAssign(CAO); 10572 } 10573 10574 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10575 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10576 void VisitUnaryPreIncDec(UnaryOperator *UO) { 10577 Object O = getObject(UO->getSubExpr(), true); 10578 if (!O) 10579 return VisitExpr(UO); 10580 10581 notePreMod(O, UO); 10582 Visit(UO->getSubExpr()); 10583 // C++11 [expr.pre.incr]p1: 10584 // the expression ++x is equivalent to x+=1 10585 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10586 : UK_ModAsSideEffect); 10587 } 10588 10589 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10590 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10591 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10592 Object O = getObject(UO->getSubExpr(), true); 10593 if (!O) 10594 return VisitExpr(UO); 10595 10596 notePreMod(O, UO); 10597 Visit(UO->getSubExpr()); 10598 notePostMod(O, UO, UK_ModAsSideEffect); 10599 } 10600 10601 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10602 void VisitBinLOr(BinaryOperator *BO) { 10603 // The side-effects of the LHS of an '&&' are sequenced before the 10604 // value computation of the RHS, and hence before the value computation 10605 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10606 // as if they were unconditionally sequenced. 10607 EvaluationTracker Eval(*this); 10608 { 10609 SequencedSubexpression Sequenced(*this); 10610 Visit(BO->getLHS()); 10611 } 10612 10613 bool Result; 10614 if (Eval.evaluate(BO->getLHS(), Result)) { 10615 if (!Result) 10616 Visit(BO->getRHS()); 10617 } else { 10618 // Check for unsequenced operations in the RHS, treating it as an 10619 // entirely separate evaluation. 10620 // 10621 // FIXME: If there are operations in the RHS which are unsequenced 10622 // with respect to operations outside the RHS, and those operations 10623 // are unconditionally evaluated, diagnose them. 10624 WorkList.push_back(BO->getRHS()); 10625 } 10626 } 10627 void VisitBinLAnd(BinaryOperator *BO) { 10628 EvaluationTracker Eval(*this); 10629 { 10630 SequencedSubexpression Sequenced(*this); 10631 Visit(BO->getLHS()); 10632 } 10633 10634 bool Result; 10635 if (Eval.evaluate(BO->getLHS(), Result)) { 10636 if (Result) 10637 Visit(BO->getRHS()); 10638 } else { 10639 WorkList.push_back(BO->getRHS()); 10640 } 10641 } 10642 10643 // Only visit the condition, unless we can be sure which subexpression will 10644 // be chosen. 10645 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10646 EvaluationTracker Eval(*this); 10647 { 10648 SequencedSubexpression Sequenced(*this); 10649 Visit(CO->getCond()); 10650 } 10651 10652 bool Result; 10653 if (Eval.evaluate(CO->getCond(), Result)) 10654 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10655 else { 10656 WorkList.push_back(CO->getTrueExpr()); 10657 WorkList.push_back(CO->getFalseExpr()); 10658 } 10659 } 10660 10661 void VisitCallExpr(CallExpr *CE) { 10662 // C++11 [intro.execution]p15: 10663 // When calling a function [...], every value computation and side effect 10664 // associated with any argument expression, or with the postfix expression 10665 // designating the called function, is sequenced before execution of every 10666 // expression or statement in the body of the function [and thus before 10667 // the value computation of its result]. 10668 SequencedSubexpression Sequenced(*this); 10669 Base::VisitCallExpr(CE); 10670 10671 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10672 } 10673 10674 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10675 // This is a call, so all subexpressions are sequenced before the result. 10676 SequencedSubexpression Sequenced(*this); 10677 10678 if (!CCE->isListInitialization()) 10679 return VisitExpr(CCE); 10680 10681 // In C++11, list initializations are sequenced. 10682 SmallVector<SequenceTree::Seq, 32> Elts; 10683 SequenceTree::Seq Parent = Region; 10684 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10685 E = CCE->arg_end(); 10686 I != E; ++I) { 10687 Region = Tree.allocate(Parent); 10688 Elts.push_back(Region); 10689 Visit(*I); 10690 } 10691 10692 // Forget that the initializers are sequenced. 10693 Region = Parent; 10694 for (unsigned I = 0; I < Elts.size(); ++I) 10695 Tree.merge(Elts[I]); 10696 } 10697 10698 void VisitInitListExpr(InitListExpr *ILE) { 10699 if (!SemaRef.getLangOpts().CPlusPlus11) 10700 return VisitExpr(ILE); 10701 10702 // In C++11, list initializations are sequenced. 10703 SmallVector<SequenceTree::Seq, 32> Elts; 10704 SequenceTree::Seq Parent = Region; 10705 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10706 Expr *E = ILE->getInit(I); 10707 if (!E) continue; 10708 Region = Tree.allocate(Parent); 10709 Elts.push_back(Region); 10710 Visit(E); 10711 } 10712 10713 // Forget that the initializers are sequenced. 10714 Region = Parent; 10715 for (unsigned I = 0; I < Elts.size(); ++I) 10716 Tree.merge(Elts[I]); 10717 } 10718 }; 10719 10720 } // namespace 10721 10722 void Sema::CheckUnsequencedOperations(Expr *E) { 10723 SmallVector<Expr *, 8> WorkList; 10724 WorkList.push_back(E); 10725 while (!WorkList.empty()) { 10726 Expr *Item = WorkList.pop_back_val(); 10727 SequenceChecker(*this, Item, WorkList); 10728 } 10729 } 10730 10731 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10732 bool IsConstexpr) { 10733 CheckImplicitConversions(E, CheckLoc); 10734 if (!E->isInstantiationDependent()) 10735 CheckUnsequencedOperations(E); 10736 if (!IsConstexpr && !E->isValueDependent()) 10737 CheckForIntOverflow(E); 10738 DiagnoseMisalignedMembers(); 10739 } 10740 10741 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10742 FieldDecl *BitField, 10743 Expr *Init) { 10744 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10745 } 10746 10747 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10748 SourceLocation Loc) { 10749 if (!PType->isVariablyModifiedType()) 10750 return; 10751 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10752 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10753 return; 10754 } 10755 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10756 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10757 return; 10758 } 10759 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10760 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10761 return; 10762 } 10763 10764 const ArrayType *AT = S.Context.getAsArrayType(PType); 10765 if (!AT) 10766 return; 10767 10768 if (AT->getSizeModifier() != ArrayType::Star) { 10769 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10770 return; 10771 } 10772 10773 S.Diag(Loc, diag::err_array_star_in_function_definition); 10774 } 10775 10776 /// CheckParmsForFunctionDef - Check that the parameters of the given 10777 /// function are appropriate for the definition of a function. This 10778 /// takes care of any checks that cannot be performed on the 10779 /// declaration itself, e.g., that the types of each of the function 10780 /// parameters are complete. 10781 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10782 bool CheckParameterNames) { 10783 bool HasInvalidParm = false; 10784 for (ParmVarDecl *Param : Parameters) { 10785 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10786 // function declarator that is part of a function definition of 10787 // that function shall not have incomplete type. 10788 // 10789 // This is also C++ [dcl.fct]p6. 10790 if (!Param->isInvalidDecl() && 10791 RequireCompleteType(Param->getLocation(), Param->getType(), 10792 diag::err_typecheck_decl_incomplete_type)) { 10793 Param->setInvalidDecl(); 10794 HasInvalidParm = true; 10795 } 10796 10797 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10798 // declaration of each parameter shall include an identifier. 10799 if (CheckParameterNames && 10800 Param->getIdentifier() == nullptr && 10801 !Param->isImplicit() && 10802 !getLangOpts().CPlusPlus) 10803 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10804 10805 // C99 6.7.5.3p12: 10806 // If the function declarator is not part of a definition of that 10807 // function, parameters may have incomplete type and may use the [*] 10808 // notation in their sequences of declarator specifiers to specify 10809 // variable length array types. 10810 QualType PType = Param->getOriginalType(); 10811 // FIXME: This diagnostic should point the '[*]' if source-location 10812 // information is added for it. 10813 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10814 10815 // MSVC destroys objects passed by value in the callee. Therefore a 10816 // function definition which takes such a parameter must be able to call the 10817 // object's destructor. However, we don't perform any direct access check 10818 // on the dtor. 10819 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10820 .getCXXABI() 10821 .areArgsDestroyedLeftToRightInCallee()) { 10822 if (!Param->isInvalidDecl()) { 10823 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10824 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10825 if (!ClassDecl->isInvalidDecl() && 10826 !ClassDecl->hasIrrelevantDestructor() && 10827 !ClassDecl->isDependentContext()) { 10828 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10829 MarkFunctionReferenced(Param->getLocation(), Destructor); 10830 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10831 } 10832 } 10833 } 10834 } 10835 10836 // Parameters with the pass_object_size attribute only need to be marked 10837 // constant at function definitions. Because we lack information about 10838 // whether we're on a declaration or definition when we're instantiating the 10839 // attribute, we need to check for constness here. 10840 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10841 if (!Param->getType().isConstQualified()) 10842 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10843 << Attr->getSpelling() << 1; 10844 } 10845 10846 return HasInvalidParm; 10847 } 10848 10849 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 10850 /// or MemberExpr. 10851 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 10852 ASTContext &Context) { 10853 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 10854 return Context.getDeclAlign(DRE->getDecl()); 10855 10856 if (const auto *ME = dyn_cast<MemberExpr>(E)) 10857 return Context.getDeclAlign(ME->getMemberDecl()); 10858 10859 return TypeAlign; 10860 } 10861 10862 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10863 /// pointer cast increases the alignment requirements. 10864 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10865 // This is actually a lot of work to potentially be doing on every 10866 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10867 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10868 return; 10869 10870 // Ignore dependent types. 10871 if (T->isDependentType() || Op->getType()->isDependentType()) 10872 return; 10873 10874 // Require that the destination be a pointer type. 10875 const PointerType *DestPtr = T->getAs<PointerType>(); 10876 if (!DestPtr) return; 10877 10878 // If the destination has alignment 1, we're done. 10879 QualType DestPointee = DestPtr->getPointeeType(); 10880 if (DestPointee->isIncompleteType()) return; 10881 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10882 if (DestAlign.isOne()) return; 10883 10884 // Require that the source be a pointer type. 10885 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10886 if (!SrcPtr) return; 10887 QualType SrcPointee = SrcPtr->getPointeeType(); 10888 10889 // Whitelist casts from cv void*. We already implicitly 10890 // whitelisted casts to cv void*, since they have alignment 1. 10891 // Also whitelist casts involving incomplete types, which implicitly 10892 // includes 'void'. 10893 if (SrcPointee->isIncompleteType()) return; 10894 10895 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10896 10897 if (auto *CE = dyn_cast<CastExpr>(Op)) { 10898 if (CE->getCastKind() == CK_ArrayToPointerDecay) 10899 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 10900 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 10901 if (UO->getOpcode() == UO_AddrOf) 10902 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 10903 } 10904 10905 if (SrcAlign >= DestAlign) return; 10906 10907 Diag(TRange.getBegin(), diag::warn_cast_align) 10908 << Op->getType() << T 10909 << static_cast<unsigned>(SrcAlign.getQuantity()) 10910 << static_cast<unsigned>(DestAlign.getQuantity()) 10911 << TRange << Op->getSourceRange(); 10912 } 10913 10914 /// \brief Check whether this array fits the idiom of a size-one tail padded 10915 /// array member of a struct. 10916 /// 10917 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10918 /// commonly used to emulate flexible arrays in C89 code. 10919 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10920 const NamedDecl *ND) { 10921 if (Size != 1 || !ND) return false; 10922 10923 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10924 if (!FD) return false; 10925 10926 // Don't consider sizes resulting from macro expansions or template argument 10927 // substitution to form C89 tail-padded arrays. 10928 10929 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10930 while (TInfo) { 10931 TypeLoc TL = TInfo->getTypeLoc(); 10932 // Look through typedefs. 10933 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10934 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10935 TInfo = TDL->getTypeSourceInfo(); 10936 continue; 10937 } 10938 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10939 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10940 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10941 return false; 10942 } 10943 break; 10944 } 10945 10946 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10947 if (!RD) return false; 10948 if (RD->isUnion()) return false; 10949 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10950 if (!CRD->isStandardLayout()) return false; 10951 } 10952 10953 // See if this is the last field decl in the record. 10954 const Decl *D = FD; 10955 while ((D = D->getNextDeclInContext())) 10956 if (isa<FieldDecl>(D)) 10957 return false; 10958 return true; 10959 } 10960 10961 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10962 const ArraySubscriptExpr *ASE, 10963 bool AllowOnePastEnd, bool IndexNegated) { 10964 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10965 if (IndexExpr->isValueDependent()) 10966 return; 10967 10968 const Type *EffectiveType = 10969 BaseExpr->getType()->getPointeeOrArrayElementType(); 10970 BaseExpr = BaseExpr->IgnoreParenCasts(); 10971 const ConstantArrayType *ArrayTy = 10972 Context.getAsConstantArrayType(BaseExpr->getType()); 10973 if (!ArrayTy) 10974 return; 10975 10976 llvm::APSInt index; 10977 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10978 return; 10979 if (IndexNegated) 10980 index = -index; 10981 10982 const NamedDecl *ND = nullptr; 10983 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10984 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10985 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10986 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10987 10988 if (index.isUnsigned() || !index.isNegative()) { 10989 llvm::APInt size = ArrayTy->getSize(); 10990 if (!size.isStrictlyPositive()) 10991 return; 10992 10993 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10994 if (BaseType != EffectiveType) { 10995 // Make sure we're comparing apples to apples when comparing index to size 10996 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10997 uint64_t array_typesize = Context.getTypeSize(BaseType); 10998 // Handle ptrarith_typesize being zero, such as when casting to void* 10999 if (!ptrarith_typesize) ptrarith_typesize = 1; 11000 if (ptrarith_typesize != array_typesize) { 11001 // There's a cast to a different size type involved 11002 uint64_t ratio = array_typesize / ptrarith_typesize; 11003 // TODO: Be smarter about handling cases where array_typesize is not a 11004 // multiple of ptrarith_typesize 11005 if (ptrarith_typesize * ratio == array_typesize) 11006 size *= llvm::APInt(size.getBitWidth(), ratio); 11007 } 11008 } 11009 11010 if (size.getBitWidth() > index.getBitWidth()) 11011 index = index.zext(size.getBitWidth()); 11012 else if (size.getBitWidth() < index.getBitWidth()) 11013 size = size.zext(index.getBitWidth()); 11014 11015 // For array subscripting the index must be less than size, but for pointer 11016 // arithmetic also allow the index (offset) to be equal to size since 11017 // computing the next address after the end of the array is legal and 11018 // commonly done e.g. in C++ iterators and range-based for loops. 11019 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 11020 return; 11021 11022 // Also don't warn for arrays of size 1 which are members of some 11023 // structure. These are often used to approximate flexible arrays in C89 11024 // code. 11025 if (IsTailPaddedMemberArray(*this, size, ND)) 11026 return; 11027 11028 // Suppress the warning if the subscript expression (as identified by the 11029 // ']' location) and the index expression are both from macro expansions 11030 // within a system header. 11031 if (ASE) { 11032 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 11033 ASE->getRBracketLoc()); 11034 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 11035 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 11036 IndexExpr->getLocStart()); 11037 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 11038 return; 11039 } 11040 } 11041 11042 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 11043 if (ASE) 11044 DiagID = diag::warn_array_index_exceeds_bounds; 11045 11046 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11047 PDiag(DiagID) << index.toString(10, true) 11048 << size.toString(10, true) 11049 << (unsigned)size.getLimitedValue(~0U) 11050 << IndexExpr->getSourceRange()); 11051 } else { 11052 unsigned DiagID = diag::warn_array_index_precedes_bounds; 11053 if (!ASE) { 11054 DiagID = diag::warn_ptr_arith_precedes_bounds; 11055 if (index.isNegative()) index = -index; 11056 } 11057 11058 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11059 PDiag(DiagID) << index.toString(10, true) 11060 << IndexExpr->getSourceRange()); 11061 } 11062 11063 if (!ND) { 11064 // Try harder to find a NamedDecl to point at in the note. 11065 while (const ArraySubscriptExpr *ASE = 11066 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 11067 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 11068 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11069 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 11070 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11071 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 11072 } 11073 11074 if (ND) 11075 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 11076 PDiag(diag::note_array_index_out_of_bounds) 11077 << ND->getDeclName()); 11078 } 11079 11080 void Sema::CheckArrayAccess(const Expr *expr) { 11081 int AllowOnePastEnd = 0; 11082 while (expr) { 11083 expr = expr->IgnoreParenImpCasts(); 11084 switch (expr->getStmtClass()) { 11085 case Stmt::ArraySubscriptExprClass: { 11086 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 11087 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 11088 AllowOnePastEnd > 0); 11089 return; 11090 } 11091 case Stmt::OMPArraySectionExprClass: { 11092 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 11093 if (ASE->getLowerBound()) 11094 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 11095 /*ASE=*/nullptr, AllowOnePastEnd > 0); 11096 return; 11097 } 11098 case Stmt::UnaryOperatorClass: { 11099 // Only unwrap the * and & unary operators 11100 const UnaryOperator *UO = cast<UnaryOperator>(expr); 11101 expr = UO->getSubExpr(); 11102 switch (UO->getOpcode()) { 11103 case UO_AddrOf: 11104 AllowOnePastEnd++; 11105 break; 11106 case UO_Deref: 11107 AllowOnePastEnd--; 11108 break; 11109 default: 11110 return; 11111 } 11112 break; 11113 } 11114 case Stmt::ConditionalOperatorClass: { 11115 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 11116 if (const Expr *lhs = cond->getLHS()) 11117 CheckArrayAccess(lhs); 11118 if (const Expr *rhs = cond->getRHS()) 11119 CheckArrayAccess(rhs); 11120 return; 11121 } 11122 case Stmt::CXXOperatorCallExprClass: { 11123 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 11124 for (const auto *Arg : OCE->arguments()) 11125 CheckArrayAccess(Arg); 11126 return; 11127 } 11128 default: 11129 return; 11130 } 11131 } 11132 } 11133 11134 //===--- CHECK: Objective-C retain cycles ----------------------------------// 11135 11136 namespace { 11137 11138 struct RetainCycleOwner { 11139 VarDecl *Variable = nullptr; 11140 SourceRange Range; 11141 SourceLocation Loc; 11142 bool Indirect = false; 11143 11144 RetainCycleOwner() = default; 11145 11146 void setLocsFrom(Expr *e) { 11147 Loc = e->getExprLoc(); 11148 Range = e->getSourceRange(); 11149 } 11150 }; 11151 11152 } // namespace 11153 11154 /// Consider whether capturing the given variable can possibly lead to 11155 /// a retain cycle. 11156 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11157 // In ARC, it's captured strongly iff the variable has __strong 11158 // lifetime. In MRR, it's captured strongly if the variable is 11159 // __block and has an appropriate type. 11160 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11161 return false; 11162 11163 owner.Variable = var; 11164 if (ref) 11165 owner.setLocsFrom(ref); 11166 return true; 11167 } 11168 11169 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11170 while (true) { 11171 e = e->IgnoreParens(); 11172 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11173 switch (cast->getCastKind()) { 11174 case CK_BitCast: 11175 case CK_LValueBitCast: 11176 case CK_LValueToRValue: 11177 case CK_ARCReclaimReturnedObject: 11178 e = cast->getSubExpr(); 11179 continue; 11180 11181 default: 11182 return false; 11183 } 11184 } 11185 11186 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11187 ObjCIvarDecl *ivar = ref->getDecl(); 11188 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11189 return false; 11190 11191 // Try to find a retain cycle in the base. 11192 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11193 return false; 11194 11195 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11196 owner.Indirect = true; 11197 return true; 11198 } 11199 11200 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11201 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11202 if (!var) return false; 11203 return considerVariable(var, ref, owner); 11204 } 11205 11206 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11207 if (member->isArrow()) return false; 11208 11209 // Don't count this as an indirect ownership. 11210 e = member->getBase(); 11211 continue; 11212 } 11213 11214 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11215 // Only pay attention to pseudo-objects on property references. 11216 ObjCPropertyRefExpr *pre 11217 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11218 ->IgnoreParens()); 11219 if (!pre) return false; 11220 if (pre->isImplicitProperty()) return false; 11221 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11222 if (!property->isRetaining() && 11223 !(property->getPropertyIvarDecl() && 11224 property->getPropertyIvarDecl()->getType() 11225 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11226 return false; 11227 11228 owner.Indirect = true; 11229 if (pre->isSuperReceiver()) { 11230 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11231 if (!owner.Variable) 11232 return false; 11233 owner.Loc = pre->getLocation(); 11234 owner.Range = pre->getSourceRange(); 11235 return true; 11236 } 11237 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11238 ->getSourceExpr()); 11239 continue; 11240 } 11241 11242 // Array ivars? 11243 11244 return false; 11245 } 11246 } 11247 11248 namespace { 11249 11250 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11251 ASTContext &Context; 11252 VarDecl *Variable; 11253 Expr *Capturer = nullptr; 11254 bool VarWillBeReased = false; 11255 11256 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11257 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11258 Context(Context), Variable(variable) {} 11259 11260 void VisitDeclRefExpr(DeclRefExpr *ref) { 11261 if (ref->getDecl() == Variable && !Capturer) 11262 Capturer = ref; 11263 } 11264 11265 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11266 if (Capturer) return; 11267 Visit(ref->getBase()); 11268 if (Capturer && ref->isFreeIvar()) 11269 Capturer = ref; 11270 } 11271 11272 void VisitBlockExpr(BlockExpr *block) { 11273 // Look inside nested blocks 11274 if (block->getBlockDecl()->capturesVariable(Variable)) 11275 Visit(block->getBlockDecl()->getBody()); 11276 } 11277 11278 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11279 if (Capturer) return; 11280 if (OVE->getSourceExpr()) 11281 Visit(OVE->getSourceExpr()); 11282 } 11283 11284 void VisitBinaryOperator(BinaryOperator *BinOp) { 11285 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11286 return; 11287 Expr *LHS = BinOp->getLHS(); 11288 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11289 if (DRE->getDecl() != Variable) 11290 return; 11291 if (Expr *RHS = BinOp->getRHS()) { 11292 RHS = RHS->IgnoreParenCasts(); 11293 llvm::APSInt Value; 11294 VarWillBeReased = 11295 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11296 } 11297 } 11298 } 11299 }; 11300 11301 } // namespace 11302 11303 /// Check whether the given argument is a block which captures a 11304 /// variable. 11305 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11306 assert(owner.Variable && owner.Loc.isValid()); 11307 11308 e = e->IgnoreParenCasts(); 11309 11310 // Look through [^{...} copy] and Block_copy(^{...}). 11311 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11312 Selector Cmd = ME->getSelector(); 11313 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11314 e = ME->getInstanceReceiver(); 11315 if (!e) 11316 return nullptr; 11317 e = e->IgnoreParenCasts(); 11318 } 11319 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11320 if (CE->getNumArgs() == 1) { 11321 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11322 if (Fn) { 11323 const IdentifierInfo *FnI = Fn->getIdentifier(); 11324 if (FnI && FnI->isStr("_Block_copy")) { 11325 e = CE->getArg(0)->IgnoreParenCasts(); 11326 } 11327 } 11328 } 11329 } 11330 11331 BlockExpr *block = dyn_cast<BlockExpr>(e); 11332 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11333 return nullptr; 11334 11335 FindCaptureVisitor visitor(S.Context, owner.Variable); 11336 visitor.Visit(block->getBlockDecl()->getBody()); 11337 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11338 } 11339 11340 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11341 RetainCycleOwner &owner) { 11342 assert(capturer); 11343 assert(owner.Variable && owner.Loc.isValid()); 11344 11345 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11346 << owner.Variable << capturer->getSourceRange(); 11347 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11348 << owner.Indirect << owner.Range; 11349 } 11350 11351 /// Check for a keyword selector that starts with the word 'add' or 11352 /// 'set'. 11353 static bool isSetterLikeSelector(Selector sel) { 11354 if (sel.isUnarySelector()) return false; 11355 11356 StringRef str = sel.getNameForSlot(0); 11357 while (!str.empty() && str.front() == '_') str = str.substr(1); 11358 if (str.startswith("set")) 11359 str = str.substr(3); 11360 else if (str.startswith("add")) { 11361 // Specially whitelist 'addOperationWithBlock:'. 11362 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 11363 return false; 11364 str = str.substr(3); 11365 } 11366 else 11367 return false; 11368 11369 if (str.empty()) return true; 11370 return !isLowercase(str.front()); 11371 } 11372 11373 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 11374 ObjCMessageExpr *Message) { 11375 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 11376 Message->getReceiverInterface(), 11377 NSAPI::ClassId_NSMutableArray); 11378 if (!IsMutableArray) { 11379 return None; 11380 } 11381 11382 Selector Sel = Message->getSelector(); 11383 11384 Optional<NSAPI::NSArrayMethodKind> MKOpt = 11385 S.NSAPIObj->getNSArrayMethodKind(Sel); 11386 if (!MKOpt) { 11387 return None; 11388 } 11389 11390 NSAPI::NSArrayMethodKind MK = *MKOpt; 11391 11392 switch (MK) { 11393 case NSAPI::NSMutableArr_addObject: 11394 case NSAPI::NSMutableArr_insertObjectAtIndex: 11395 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 11396 return 0; 11397 case NSAPI::NSMutableArr_replaceObjectAtIndex: 11398 return 1; 11399 11400 default: 11401 return None; 11402 } 11403 11404 return None; 11405 } 11406 11407 static 11408 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 11409 ObjCMessageExpr *Message) { 11410 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 11411 Message->getReceiverInterface(), 11412 NSAPI::ClassId_NSMutableDictionary); 11413 if (!IsMutableDictionary) { 11414 return None; 11415 } 11416 11417 Selector Sel = Message->getSelector(); 11418 11419 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 11420 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 11421 if (!MKOpt) { 11422 return None; 11423 } 11424 11425 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 11426 11427 switch (MK) { 11428 case NSAPI::NSMutableDict_setObjectForKey: 11429 case NSAPI::NSMutableDict_setValueForKey: 11430 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 11431 return 0; 11432 11433 default: 11434 return None; 11435 } 11436 11437 return None; 11438 } 11439 11440 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 11441 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 11442 Message->getReceiverInterface(), 11443 NSAPI::ClassId_NSMutableSet); 11444 11445 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 11446 Message->getReceiverInterface(), 11447 NSAPI::ClassId_NSMutableOrderedSet); 11448 if (!IsMutableSet && !IsMutableOrderedSet) { 11449 return None; 11450 } 11451 11452 Selector Sel = Message->getSelector(); 11453 11454 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 11455 if (!MKOpt) { 11456 return None; 11457 } 11458 11459 NSAPI::NSSetMethodKind MK = *MKOpt; 11460 11461 switch (MK) { 11462 case NSAPI::NSMutableSet_addObject: 11463 case NSAPI::NSOrderedSet_setObjectAtIndex: 11464 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 11465 case NSAPI::NSOrderedSet_insertObjectAtIndex: 11466 return 0; 11467 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 11468 return 1; 11469 } 11470 11471 return None; 11472 } 11473 11474 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 11475 if (!Message->isInstanceMessage()) { 11476 return; 11477 } 11478 11479 Optional<int> ArgOpt; 11480 11481 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 11482 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 11483 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 11484 return; 11485 } 11486 11487 int ArgIndex = *ArgOpt; 11488 11489 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 11490 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 11491 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 11492 } 11493 11494 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 11495 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11496 if (ArgRE->isObjCSelfExpr()) { 11497 Diag(Message->getSourceRange().getBegin(), 11498 diag::warn_objc_circular_container) 11499 << ArgRE->getDecl()->getName() << StringRef("super"); 11500 } 11501 } 11502 } else { 11503 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 11504 11505 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 11506 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 11507 } 11508 11509 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 11510 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11511 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 11512 ValueDecl *Decl = ReceiverRE->getDecl(); 11513 Diag(Message->getSourceRange().getBegin(), 11514 diag::warn_objc_circular_container) 11515 << Decl->getName() << Decl->getName(); 11516 if (!ArgRE->isObjCSelfExpr()) { 11517 Diag(Decl->getLocation(), 11518 diag::note_objc_circular_container_declared_here) 11519 << Decl->getName(); 11520 } 11521 } 11522 } 11523 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 11524 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 11525 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 11526 ObjCIvarDecl *Decl = IvarRE->getDecl(); 11527 Diag(Message->getSourceRange().getBegin(), 11528 diag::warn_objc_circular_container) 11529 << Decl->getName() << Decl->getName(); 11530 Diag(Decl->getLocation(), 11531 diag::note_objc_circular_container_declared_here) 11532 << Decl->getName(); 11533 } 11534 } 11535 } 11536 } 11537 } 11538 11539 /// Check a message send to see if it's likely to cause a retain cycle. 11540 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11541 // Only check instance methods whose selector looks like a setter. 11542 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 11543 return; 11544 11545 // Try to find a variable that the receiver is strongly owned by. 11546 RetainCycleOwner owner; 11547 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 11548 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 11549 return; 11550 } else { 11551 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 11552 owner.Variable = getCurMethodDecl()->getSelfDecl(); 11553 owner.Loc = msg->getSuperLoc(); 11554 owner.Range = msg->getSuperLoc(); 11555 } 11556 11557 // Check whether the receiver is captured by any of the arguments. 11558 const ObjCMethodDecl *MD = msg->getMethodDecl(); 11559 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 11560 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 11561 // noescape blocks should not be retained by the method. 11562 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 11563 continue; 11564 return diagnoseRetainCycle(*this, capturer, owner); 11565 } 11566 } 11567 } 11568 11569 /// Check a property assign to see if it's likely to cause a retain cycle. 11570 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 11571 RetainCycleOwner owner; 11572 if (!findRetainCycleOwner(*this, receiver, owner)) 11573 return; 11574 11575 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 11576 diagnoseRetainCycle(*this, capturer, owner); 11577 } 11578 11579 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 11580 RetainCycleOwner Owner; 11581 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 11582 return; 11583 11584 // Because we don't have an expression for the variable, we have to set the 11585 // location explicitly here. 11586 Owner.Loc = Var->getLocation(); 11587 Owner.Range = Var->getSourceRange(); 11588 11589 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 11590 diagnoseRetainCycle(*this, Capturer, Owner); 11591 } 11592 11593 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 11594 Expr *RHS, bool isProperty) { 11595 // Check if RHS is an Objective-C object literal, which also can get 11596 // immediately zapped in a weak reference. Note that we explicitly 11597 // allow ObjCStringLiterals, since those are designed to never really die. 11598 RHS = RHS->IgnoreParenImpCasts(); 11599 11600 // This enum needs to match with the 'select' in 11601 // warn_objc_arc_literal_assign (off-by-1). 11602 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 11603 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 11604 return false; 11605 11606 S.Diag(Loc, diag::warn_arc_literal_assign) 11607 << (unsigned) Kind 11608 << (isProperty ? 0 : 1) 11609 << RHS->getSourceRange(); 11610 11611 return true; 11612 } 11613 11614 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 11615 Qualifiers::ObjCLifetime LT, 11616 Expr *RHS, bool isProperty) { 11617 // Strip off any implicit cast added to get to the one ARC-specific. 11618 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11619 if (cast->getCastKind() == CK_ARCConsumeObject) { 11620 S.Diag(Loc, diag::warn_arc_retained_assign) 11621 << (LT == Qualifiers::OCL_ExplicitNone) 11622 << (isProperty ? 0 : 1) 11623 << RHS->getSourceRange(); 11624 return true; 11625 } 11626 RHS = cast->getSubExpr(); 11627 } 11628 11629 if (LT == Qualifiers::OCL_Weak && 11630 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11631 return true; 11632 11633 return false; 11634 } 11635 11636 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11637 QualType LHS, Expr *RHS) { 11638 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11639 11640 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11641 return false; 11642 11643 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11644 return true; 11645 11646 return false; 11647 } 11648 11649 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11650 Expr *LHS, Expr *RHS) { 11651 QualType LHSType; 11652 // PropertyRef on LHS type need be directly obtained from 11653 // its declaration as it has a PseudoType. 11654 ObjCPropertyRefExpr *PRE 11655 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11656 if (PRE && !PRE->isImplicitProperty()) { 11657 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11658 if (PD) 11659 LHSType = PD->getType(); 11660 } 11661 11662 if (LHSType.isNull()) 11663 LHSType = LHS->getType(); 11664 11665 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11666 11667 if (LT == Qualifiers::OCL_Weak) { 11668 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11669 getCurFunction()->markSafeWeakUse(LHS); 11670 } 11671 11672 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11673 return; 11674 11675 // FIXME. Check for other life times. 11676 if (LT != Qualifiers::OCL_None) 11677 return; 11678 11679 if (PRE) { 11680 if (PRE->isImplicitProperty()) 11681 return; 11682 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11683 if (!PD) 11684 return; 11685 11686 unsigned Attributes = PD->getPropertyAttributes(); 11687 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11688 // when 'assign' attribute was not explicitly specified 11689 // by user, ignore it and rely on property type itself 11690 // for lifetime info. 11691 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11692 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11693 LHSType->isObjCRetainableType()) 11694 return; 11695 11696 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11697 if (cast->getCastKind() == CK_ARCConsumeObject) { 11698 Diag(Loc, diag::warn_arc_retained_property_assign) 11699 << RHS->getSourceRange(); 11700 return; 11701 } 11702 RHS = cast->getSubExpr(); 11703 } 11704 } 11705 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11706 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11707 return; 11708 } 11709 } 11710 } 11711 11712 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11713 11714 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11715 SourceLocation StmtLoc, 11716 const NullStmt *Body) { 11717 // Do not warn if the body is a macro that expands to nothing, e.g: 11718 // 11719 // #define CALL(x) 11720 // if (condition) 11721 // CALL(0); 11722 if (Body->hasLeadingEmptyMacro()) 11723 return false; 11724 11725 // Get line numbers of statement and body. 11726 bool StmtLineInvalid; 11727 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11728 &StmtLineInvalid); 11729 if (StmtLineInvalid) 11730 return false; 11731 11732 bool BodyLineInvalid; 11733 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11734 &BodyLineInvalid); 11735 if (BodyLineInvalid) 11736 return false; 11737 11738 // Warn if null statement and body are on the same line. 11739 if (StmtLine != BodyLine) 11740 return false; 11741 11742 return true; 11743 } 11744 11745 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11746 const Stmt *Body, 11747 unsigned DiagID) { 11748 // Since this is a syntactic check, don't emit diagnostic for template 11749 // instantiations, this just adds noise. 11750 if (CurrentInstantiationScope) 11751 return; 11752 11753 // The body should be a null statement. 11754 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11755 if (!NBody) 11756 return; 11757 11758 // Do the usual checks. 11759 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11760 return; 11761 11762 Diag(NBody->getSemiLoc(), DiagID); 11763 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11764 } 11765 11766 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11767 const Stmt *PossibleBody) { 11768 assert(!CurrentInstantiationScope); // Ensured by caller 11769 11770 SourceLocation StmtLoc; 11771 const Stmt *Body; 11772 unsigned DiagID; 11773 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11774 StmtLoc = FS->getRParenLoc(); 11775 Body = FS->getBody(); 11776 DiagID = diag::warn_empty_for_body; 11777 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11778 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11779 Body = WS->getBody(); 11780 DiagID = diag::warn_empty_while_body; 11781 } else 11782 return; // Neither `for' nor `while'. 11783 11784 // The body should be a null statement. 11785 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11786 if (!NBody) 11787 return; 11788 11789 // Skip expensive checks if diagnostic is disabled. 11790 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11791 return; 11792 11793 // Do the usual checks. 11794 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11795 return; 11796 11797 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11798 // noise level low, emit diagnostics only if for/while is followed by a 11799 // CompoundStmt, e.g.: 11800 // for (int i = 0; i < n; i++); 11801 // { 11802 // a(i); 11803 // } 11804 // or if for/while is followed by a statement with more indentation 11805 // than for/while itself: 11806 // for (int i = 0; i < n; i++); 11807 // a(i); 11808 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11809 if (!ProbableTypo) { 11810 bool BodyColInvalid; 11811 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11812 PossibleBody->getLocStart(), 11813 &BodyColInvalid); 11814 if (BodyColInvalid) 11815 return; 11816 11817 bool StmtColInvalid; 11818 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11819 S->getLocStart(), 11820 &StmtColInvalid); 11821 if (StmtColInvalid) 11822 return; 11823 11824 if (BodyCol > StmtCol) 11825 ProbableTypo = true; 11826 } 11827 11828 if (ProbableTypo) { 11829 Diag(NBody->getSemiLoc(), DiagID); 11830 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11831 } 11832 } 11833 11834 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11835 11836 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11837 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11838 SourceLocation OpLoc) { 11839 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11840 return; 11841 11842 if (inTemplateInstantiation()) 11843 return; 11844 11845 // Strip parens and casts away. 11846 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11847 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11848 11849 // Check for a call expression 11850 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11851 if (!CE || CE->getNumArgs() != 1) 11852 return; 11853 11854 // Check for a call to std::move 11855 if (!CE->isCallToStdMove()) 11856 return; 11857 11858 // Get argument from std::move 11859 RHSExpr = CE->getArg(0); 11860 11861 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11862 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11863 11864 // Two DeclRefExpr's, check that the decls are the same. 11865 if (LHSDeclRef && RHSDeclRef) { 11866 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11867 return; 11868 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11869 RHSDeclRef->getDecl()->getCanonicalDecl()) 11870 return; 11871 11872 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11873 << LHSExpr->getSourceRange() 11874 << RHSExpr->getSourceRange(); 11875 return; 11876 } 11877 11878 // Member variables require a different approach to check for self moves. 11879 // MemberExpr's are the same if every nested MemberExpr refers to the same 11880 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11881 // the base Expr's are CXXThisExpr's. 11882 const Expr *LHSBase = LHSExpr; 11883 const Expr *RHSBase = RHSExpr; 11884 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11885 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11886 if (!LHSME || !RHSME) 11887 return; 11888 11889 while (LHSME && RHSME) { 11890 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11891 RHSME->getMemberDecl()->getCanonicalDecl()) 11892 return; 11893 11894 LHSBase = LHSME->getBase(); 11895 RHSBase = RHSME->getBase(); 11896 LHSME = dyn_cast<MemberExpr>(LHSBase); 11897 RHSME = dyn_cast<MemberExpr>(RHSBase); 11898 } 11899 11900 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11901 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11902 if (LHSDeclRef && RHSDeclRef) { 11903 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11904 return; 11905 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11906 RHSDeclRef->getDecl()->getCanonicalDecl()) 11907 return; 11908 11909 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11910 << LHSExpr->getSourceRange() 11911 << RHSExpr->getSourceRange(); 11912 return; 11913 } 11914 11915 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11916 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11917 << LHSExpr->getSourceRange() 11918 << RHSExpr->getSourceRange(); 11919 } 11920 11921 //===--- Layout compatibility ----------------------------------------------// 11922 11923 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11924 11925 /// \brief Check if two enumeration types are layout-compatible. 11926 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11927 // C++11 [dcl.enum] p8: 11928 // Two enumeration types are layout-compatible if they have the same 11929 // underlying type. 11930 return ED1->isComplete() && ED2->isComplete() && 11931 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11932 } 11933 11934 /// \brief Check if two fields are layout-compatible. 11935 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 11936 FieldDecl *Field2) { 11937 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11938 return false; 11939 11940 if (Field1->isBitField() != Field2->isBitField()) 11941 return false; 11942 11943 if (Field1->isBitField()) { 11944 // Make sure that the bit-fields are the same length. 11945 unsigned Bits1 = Field1->getBitWidthValue(C); 11946 unsigned Bits2 = Field2->getBitWidthValue(C); 11947 11948 if (Bits1 != Bits2) 11949 return false; 11950 } 11951 11952 return true; 11953 } 11954 11955 /// \brief Check if two standard-layout structs are layout-compatible. 11956 /// (C++11 [class.mem] p17) 11957 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 11958 RecordDecl *RD2) { 11959 // If both records are C++ classes, check that base classes match. 11960 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11961 // If one of records is a CXXRecordDecl we are in C++ mode, 11962 // thus the other one is a CXXRecordDecl, too. 11963 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11964 // Check number of base classes. 11965 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11966 return false; 11967 11968 // Check the base classes. 11969 for (CXXRecordDecl::base_class_const_iterator 11970 Base1 = D1CXX->bases_begin(), 11971 BaseEnd1 = D1CXX->bases_end(), 11972 Base2 = D2CXX->bases_begin(); 11973 Base1 != BaseEnd1; 11974 ++Base1, ++Base2) { 11975 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11976 return false; 11977 } 11978 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11979 // If only RD2 is a C++ class, it should have zero base classes. 11980 if (D2CXX->getNumBases() > 0) 11981 return false; 11982 } 11983 11984 // Check the fields. 11985 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11986 Field2End = RD2->field_end(), 11987 Field1 = RD1->field_begin(), 11988 Field1End = RD1->field_end(); 11989 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11990 if (!isLayoutCompatible(C, *Field1, *Field2)) 11991 return false; 11992 } 11993 if (Field1 != Field1End || Field2 != Field2End) 11994 return false; 11995 11996 return true; 11997 } 11998 11999 /// \brief Check if two standard-layout unions are layout-compatible. 12000 /// (C++11 [class.mem] p18) 12001 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 12002 RecordDecl *RD2) { 12003 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 12004 for (auto *Field2 : RD2->fields()) 12005 UnmatchedFields.insert(Field2); 12006 12007 for (auto *Field1 : RD1->fields()) { 12008 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 12009 I = UnmatchedFields.begin(), 12010 E = UnmatchedFields.end(); 12011 12012 for ( ; I != E; ++I) { 12013 if (isLayoutCompatible(C, Field1, *I)) { 12014 bool Result = UnmatchedFields.erase(*I); 12015 (void) Result; 12016 assert(Result); 12017 break; 12018 } 12019 } 12020 if (I == E) 12021 return false; 12022 } 12023 12024 return UnmatchedFields.empty(); 12025 } 12026 12027 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 12028 RecordDecl *RD2) { 12029 if (RD1->isUnion() != RD2->isUnion()) 12030 return false; 12031 12032 if (RD1->isUnion()) 12033 return isLayoutCompatibleUnion(C, RD1, RD2); 12034 else 12035 return isLayoutCompatibleStruct(C, RD1, RD2); 12036 } 12037 12038 /// \brief Check if two types are layout-compatible in C++11 sense. 12039 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 12040 if (T1.isNull() || T2.isNull()) 12041 return false; 12042 12043 // C++11 [basic.types] p11: 12044 // If two types T1 and T2 are the same type, then T1 and T2 are 12045 // layout-compatible types. 12046 if (C.hasSameType(T1, T2)) 12047 return true; 12048 12049 T1 = T1.getCanonicalType().getUnqualifiedType(); 12050 T2 = T2.getCanonicalType().getUnqualifiedType(); 12051 12052 const Type::TypeClass TC1 = T1->getTypeClass(); 12053 const Type::TypeClass TC2 = T2->getTypeClass(); 12054 12055 if (TC1 != TC2) 12056 return false; 12057 12058 if (TC1 == Type::Enum) { 12059 return isLayoutCompatible(C, 12060 cast<EnumType>(T1)->getDecl(), 12061 cast<EnumType>(T2)->getDecl()); 12062 } else if (TC1 == Type::Record) { 12063 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 12064 return false; 12065 12066 return isLayoutCompatible(C, 12067 cast<RecordType>(T1)->getDecl(), 12068 cast<RecordType>(T2)->getDecl()); 12069 } 12070 12071 return false; 12072 } 12073 12074 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 12075 12076 /// \brief Given a type tag expression find the type tag itself. 12077 /// 12078 /// \param TypeExpr Type tag expression, as it appears in user's code. 12079 /// 12080 /// \param VD Declaration of an identifier that appears in a type tag. 12081 /// 12082 /// \param MagicValue Type tag magic value. 12083 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 12084 const ValueDecl **VD, uint64_t *MagicValue) { 12085 while(true) { 12086 if (!TypeExpr) 12087 return false; 12088 12089 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 12090 12091 switch (TypeExpr->getStmtClass()) { 12092 case Stmt::UnaryOperatorClass: { 12093 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 12094 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 12095 TypeExpr = UO->getSubExpr(); 12096 continue; 12097 } 12098 return false; 12099 } 12100 12101 case Stmt::DeclRefExprClass: { 12102 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 12103 *VD = DRE->getDecl(); 12104 return true; 12105 } 12106 12107 case Stmt::IntegerLiteralClass: { 12108 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 12109 llvm::APInt MagicValueAPInt = IL->getValue(); 12110 if (MagicValueAPInt.getActiveBits() <= 64) { 12111 *MagicValue = MagicValueAPInt.getZExtValue(); 12112 return true; 12113 } else 12114 return false; 12115 } 12116 12117 case Stmt::BinaryConditionalOperatorClass: 12118 case Stmt::ConditionalOperatorClass: { 12119 const AbstractConditionalOperator *ACO = 12120 cast<AbstractConditionalOperator>(TypeExpr); 12121 bool Result; 12122 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 12123 if (Result) 12124 TypeExpr = ACO->getTrueExpr(); 12125 else 12126 TypeExpr = ACO->getFalseExpr(); 12127 continue; 12128 } 12129 return false; 12130 } 12131 12132 case Stmt::BinaryOperatorClass: { 12133 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 12134 if (BO->getOpcode() == BO_Comma) { 12135 TypeExpr = BO->getRHS(); 12136 continue; 12137 } 12138 return false; 12139 } 12140 12141 default: 12142 return false; 12143 } 12144 } 12145 } 12146 12147 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 12148 /// 12149 /// \param TypeExpr Expression that specifies a type tag. 12150 /// 12151 /// \param MagicValues Registered magic values. 12152 /// 12153 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12154 /// kind. 12155 /// 12156 /// \param TypeInfo Information about the corresponding C type. 12157 /// 12158 /// \returns true if the corresponding C type was found. 12159 static bool GetMatchingCType( 12160 const IdentifierInfo *ArgumentKind, 12161 const Expr *TypeExpr, const ASTContext &Ctx, 12162 const llvm::DenseMap<Sema::TypeTagMagicValue, 12163 Sema::TypeTagData> *MagicValues, 12164 bool &FoundWrongKind, 12165 Sema::TypeTagData &TypeInfo) { 12166 FoundWrongKind = false; 12167 12168 // Variable declaration that has type_tag_for_datatype attribute. 12169 const ValueDecl *VD = nullptr; 12170 12171 uint64_t MagicValue; 12172 12173 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12174 return false; 12175 12176 if (VD) { 12177 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12178 if (I->getArgumentKind() != ArgumentKind) { 12179 FoundWrongKind = true; 12180 return false; 12181 } 12182 TypeInfo.Type = I->getMatchingCType(); 12183 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12184 TypeInfo.MustBeNull = I->getMustBeNull(); 12185 return true; 12186 } 12187 return false; 12188 } 12189 12190 if (!MagicValues) 12191 return false; 12192 12193 llvm::DenseMap<Sema::TypeTagMagicValue, 12194 Sema::TypeTagData>::const_iterator I = 12195 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12196 if (I == MagicValues->end()) 12197 return false; 12198 12199 TypeInfo = I->second; 12200 return true; 12201 } 12202 12203 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12204 uint64_t MagicValue, QualType Type, 12205 bool LayoutCompatible, 12206 bool MustBeNull) { 12207 if (!TypeTagForDatatypeMagicValues) 12208 TypeTagForDatatypeMagicValues.reset( 12209 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12210 12211 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12212 (*TypeTagForDatatypeMagicValues)[Magic] = 12213 TypeTagData(Type, LayoutCompatible, MustBeNull); 12214 } 12215 12216 static bool IsSameCharType(QualType T1, QualType T2) { 12217 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12218 if (!BT1) 12219 return false; 12220 12221 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12222 if (!BT2) 12223 return false; 12224 12225 BuiltinType::Kind T1Kind = BT1->getKind(); 12226 BuiltinType::Kind T2Kind = BT2->getKind(); 12227 12228 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12229 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12230 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12231 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12232 } 12233 12234 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12235 const ArrayRef<const Expr *> ExprArgs, 12236 SourceLocation CallSiteLoc) { 12237 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12238 bool IsPointerAttr = Attr->getIsPointer(); 12239 12240 // Retrieve the argument representing the 'type_tag'. 12241 if (Attr->getTypeTagIdx() >= ExprArgs.size()) { 12242 // Add 1 to display the user's specified value. 12243 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12244 << 0 << Attr->getTypeTagIdx() + 1; 12245 return; 12246 } 12247 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 12248 bool FoundWrongKind; 12249 TypeTagData TypeInfo; 12250 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12251 TypeTagForDatatypeMagicValues.get(), 12252 FoundWrongKind, TypeInfo)) { 12253 if (FoundWrongKind) 12254 Diag(TypeTagExpr->getExprLoc(), 12255 diag::warn_type_tag_for_datatype_wrong_kind) 12256 << TypeTagExpr->getSourceRange(); 12257 return; 12258 } 12259 12260 // Retrieve the argument representing the 'arg_idx'. 12261 if (Attr->getArgumentIdx() >= ExprArgs.size()) { 12262 // Add 1 to display the user's specified value. 12263 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12264 << 1 << Attr->getArgumentIdx() + 1; 12265 return; 12266 } 12267 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 12268 if (IsPointerAttr) { 12269 // Skip implicit cast of pointer to `void *' (as a function argument). 12270 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12271 if (ICE->getType()->isVoidPointerType() && 12272 ICE->getCastKind() == CK_BitCast) 12273 ArgumentExpr = ICE->getSubExpr(); 12274 } 12275 QualType ArgumentType = ArgumentExpr->getType(); 12276 12277 // Passing a `void*' pointer shouldn't trigger a warning. 12278 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12279 return; 12280 12281 if (TypeInfo.MustBeNull) { 12282 // Type tag with matching void type requires a null pointer. 12283 if (!ArgumentExpr->isNullPointerConstant(Context, 12284 Expr::NPC_ValueDependentIsNotNull)) { 12285 Diag(ArgumentExpr->getExprLoc(), 12286 diag::warn_type_safety_null_pointer_required) 12287 << ArgumentKind->getName() 12288 << ArgumentExpr->getSourceRange() 12289 << TypeTagExpr->getSourceRange(); 12290 } 12291 return; 12292 } 12293 12294 QualType RequiredType = TypeInfo.Type; 12295 if (IsPointerAttr) 12296 RequiredType = Context.getPointerType(RequiredType); 12297 12298 bool mismatch = false; 12299 if (!TypeInfo.LayoutCompatible) { 12300 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12301 12302 // C++11 [basic.fundamental] p1: 12303 // Plain char, signed char, and unsigned char are three distinct types. 12304 // 12305 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12306 // char' depending on the current char signedness mode. 12307 if (mismatch) 12308 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12309 RequiredType->getPointeeType())) || 12310 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12311 mismatch = false; 12312 } else 12313 if (IsPointerAttr) 12314 mismatch = !isLayoutCompatible(Context, 12315 ArgumentType->getPointeeType(), 12316 RequiredType->getPointeeType()); 12317 else 12318 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12319 12320 if (mismatch) 12321 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12322 << ArgumentType << ArgumentKind 12323 << TypeInfo.LayoutCompatible << RequiredType 12324 << ArgumentExpr->getSourceRange() 12325 << TypeTagExpr->getSourceRange(); 12326 } 12327 12328 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12329 CharUnits Alignment) { 12330 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12331 } 12332 12333 void Sema::DiagnoseMisalignedMembers() { 12334 for (MisalignedMember &m : MisalignedMembers) { 12335 const NamedDecl *ND = m.RD; 12336 if (ND->getName().empty()) { 12337 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12338 ND = TD; 12339 } 12340 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12341 << m.MD << ND << m.E->getSourceRange(); 12342 } 12343 MisalignedMembers.clear(); 12344 } 12345 12346 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12347 E = E->IgnoreParens(); 12348 if (!T->isPointerType() && !T->isIntegerType()) 12349 return; 12350 if (isa<UnaryOperator>(E) && 12351 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 12352 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 12353 if (isa<MemberExpr>(Op)) { 12354 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 12355 MisalignedMember(Op)); 12356 if (MA != MisalignedMembers.end() && 12357 (T->isIntegerType() || 12358 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 12359 Context.getTypeAlignInChars( 12360 T->getPointeeType()) <= MA->Alignment)))) 12361 MisalignedMembers.erase(MA); 12362 } 12363 } 12364 } 12365 12366 void Sema::RefersToMemberWithReducedAlignment( 12367 Expr *E, 12368 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12369 Action) { 12370 const auto *ME = dyn_cast<MemberExpr>(E); 12371 if (!ME) 12372 return; 12373 12374 // No need to check expressions with an __unaligned-qualified type. 12375 if (E->getType().getQualifiers().hasUnaligned()) 12376 return; 12377 12378 // For a chain of MemberExpr like "a.b.c.d" this list 12379 // will keep FieldDecl's like [d, c, b]. 12380 SmallVector<FieldDecl *, 4> ReverseMemberChain; 12381 const MemberExpr *TopME = nullptr; 12382 bool AnyIsPacked = false; 12383 do { 12384 QualType BaseType = ME->getBase()->getType(); 12385 if (ME->isArrow()) 12386 BaseType = BaseType->getPointeeType(); 12387 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 12388 if (RD->isInvalidDecl()) 12389 return; 12390 12391 ValueDecl *MD = ME->getMemberDecl(); 12392 auto *FD = dyn_cast<FieldDecl>(MD); 12393 // We do not care about non-data members. 12394 if (!FD || FD->isInvalidDecl()) 12395 return; 12396 12397 AnyIsPacked = 12398 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 12399 ReverseMemberChain.push_back(FD); 12400 12401 TopME = ME; 12402 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 12403 } while (ME); 12404 assert(TopME && "We did not compute a topmost MemberExpr!"); 12405 12406 // Not the scope of this diagnostic. 12407 if (!AnyIsPacked) 12408 return; 12409 12410 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 12411 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 12412 // TODO: The innermost base of the member expression may be too complicated. 12413 // For now, just disregard these cases. This is left for future 12414 // improvement. 12415 if (!DRE && !isa<CXXThisExpr>(TopBase)) 12416 return; 12417 12418 // Alignment expected by the whole expression. 12419 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 12420 12421 // No need to do anything else with this case. 12422 if (ExpectedAlignment.isOne()) 12423 return; 12424 12425 // Synthesize offset of the whole access. 12426 CharUnits Offset; 12427 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 12428 I++) { 12429 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 12430 } 12431 12432 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 12433 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 12434 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 12435 12436 // The base expression of the innermost MemberExpr may give 12437 // stronger guarantees than the class containing the member. 12438 if (DRE && !TopME->isArrow()) { 12439 const ValueDecl *VD = DRE->getDecl(); 12440 if (!VD->getType()->isReferenceType()) 12441 CompleteObjectAlignment = 12442 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 12443 } 12444 12445 // Check if the synthesized offset fulfills the alignment. 12446 if (Offset % ExpectedAlignment != 0 || 12447 // It may fulfill the offset it but the effective alignment may still be 12448 // lower than the expected expression alignment. 12449 CompleteObjectAlignment < ExpectedAlignment) { 12450 // If this happens, we want to determine a sensible culprit of this. 12451 // Intuitively, watching the chain of member expressions from right to 12452 // left, we start with the required alignment (as required by the field 12453 // type) but some packed attribute in that chain has reduced the alignment. 12454 // It may happen that another packed structure increases it again. But if 12455 // we are here such increase has not been enough. So pointing the first 12456 // FieldDecl that either is packed or else its RecordDecl is, 12457 // seems reasonable. 12458 FieldDecl *FD = nullptr; 12459 CharUnits Alignment; 12460 for (FieldDecl *FDI : ReverseMemberChain) { 12461 if (FDI->hasAttr<PackedAttr>() || 12462 FDI->getParent()->hasAttr<PackedAttr>()) { 12463 FD = FDI; 12464 Alignment = std::min( 12465 Context.getTypeAlignInChars(FD->getType()), 12466 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 12467 break; 12468 } 12469 } 12470 assert(FD && "We did not find a packed FieldDecl!"); 12471 Action(E, FD->getParent(), FD, Alignment); 12472 } 12473 } 12474 12475 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 12476 using namespace std::placeholders; 12477 12478 RefersToMemberWithReducedAlignment( 12479 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 12480 _2, _3, _4)); 12481 } 12482