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/ASTContext.h" 16 #include "clang/AST/CharUnits.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/EvaluatedExprVisitor.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/ExprObjC.h" 23 #include "clang/AST/ExprOpenMP.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/AST/StmtObjC.h" 26 #include "clang/Analysis/Analyses/FormatString.h" 27 #include "clang/Basic/CharInfo.h" 28 #include "clang/Basic/SyncScope.h" 29 #include "clang/Basic/TargetBuiltins.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 32 #include "clang/Sema/Initialization.h" 33 #include "clang/Sema/Lookup.h" 34 #include "clang/Sema/ScopeInfo.h" 35 #include "clang/Sema/Sema.h" 36 #include "clang/Sema/SemaInternal.h" 37 #include "llvm/ADT/STLExtras.h" 38 #include "llvm/ADT/SmallBitVector.h" 39 #include "llvm/ADT/SmallString.h" 40 #include "llvm/Support/ConvertUTF.h" 41 #include "llvm/Support/Format.h" 42 #include "llvm/Support/Locale.h" 43 #include "llvm/Support/raw_ostream.h" 44 45 using namespace clang; 46 using namespace sema; 47 48 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 49 unsigned ByteNo) const { 50 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 51 Context.getTargetInfo()); 52 } 53 54 /// Checks that a call expression's argument count is the desired number. 55 /// This is useful when doing custom type-checking. Returns true on error. 56 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 57 unsigned argCount = call->getNumArgs(); 58 if (argCount == desiredArgCount) return false; 59 60 if (argCount < desiredArgCount) 61 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 62 << 0 /*function call*/ << desiredArgCount << argCount 63 << call->getSourceRange(); 64 65 // Highlight all the excess arguments. 66 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 67 call->getArg(argCount - 1)->getLocEnd()); 68 69 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 70 << 0 /*function call*/ << desiredArgCount << argCount 71 << call->getArg(1)->getSourceRange(); 72 } 73 74 /// Check that the first argument to __builtin_annotation is an integer 75 /// and the second argument is a non-wide string literal. 76 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 77 if (checkArgCount(S, TheCall, 2)) 78 return true; 79 80 // First argument should be an integer. 81 Expr *ValArg = TheCall->getArg(0); 82 QualType Ty = ValArg->getType(); 83 if (!Ty->isIntegerType()) { 84 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 85 << ValArg->getSourceRange(); 86 return true; 87 } 88 89 // Second argument should be a constant string. 90 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 91 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 92 if (!Literal || !Literal->isAscii()) { 93 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 94 << StrArg->getSourceRange(); 95 return true; 96 } 97 98 TheCall->setType(Ty); 99 return false; 100 } 101 102 /// Check that the argument to __builtin_addressof is a glvalue, and set the 103 /// result type to the corresponding pointer type. 104 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 105 if (checkArgCount(S, TheCall, 1)) 106 return true; 107 108 ExprResult Arg(TheCall->getArg(0)); 109 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 110 if (ResultType.isNull()) 111 return true; 112 113 TheCall->setArg(0, Arg.get()); 114 TheCall->setType(ResultType); 115 return false; 116 } 117 118 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 119 if (checkArgCount(S, TheCall, 3)) 120 return true; 121 122 // First two arguments should be integers. 123 for (unsigned I = 0; I < 2; ++I) { 124 Expr *Arg = TheCall->getArg(I); 125 QualType Ty = Arg->getType(); 126 if (!Ty->isIntegerType()) { 127 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 128 << Ty << Arg->getSourceRange(); 129 return true; 130 } 131 } 132 133 // Third argument should be a pointer to a non-const integer. 134 // IRGen correctly handles volatile, restrict, and address spaces, and 135 // the other qualifiers aren't possible. 136 { 137 Expr *Arg = TheCall->getArg(2); 138 QualType Ty = Arg->getType(); 139 const auto *PtrTy = Ty->getAs<PointerType>(); 140 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 141 !PtrTy->getPointeeType().isConstQualified())) { 142 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 143 << Ty << Arg->getSourceRange(); 144 return true; 145 } 146 } 147 148 return false; 149 } 150 151 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 152 CallExpr *TheCall, unsigned SizeIdx, 153 unsigned DstSizeIdx) { 154 if (TheCall->getNumArgs() <= SizeIdx || 155 TheCall->getNumArgs() <= DstSizeIdx) 156 return; 157 158 const Expr *SizeArg = TheCall->getArg(SizeIdx); 159 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 160 161 llvm::APSInt Size, DstSize; 162 163 // find out if both sizes are known at compile time 164 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 165 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 166 return; 167 168 if (Size.ule(DstSize)) 169 return; 170 171 // confirmed overflow so generate the diagnostic. 172 IdentifierInfo *FnName = FDecl->getIdentifier(); 173 SourceLocation SL = TheCall->getLocStart(); 174 SourceRange SR = TheCall->getSourceRange(); 175 176 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 177 } 178 179 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 180 if (checkArgCount(S, BuiltinCall, 2)) 181 return true; 182 183 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 184 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 185 Expr *Call = BuiltinCall->getArg(0); 186 Expr *Chain = BuiltinCall->getArg(1); 187 188 if (Call->getStmtClass() != Stmt::CallExprClass) { 189 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 190 << Call->getSourceRange(); 191 return true; 192 } 193 194 auto CE = cast<CallExpr>(Call); 195 if (CE->getCallee()->getType()->isBlockPointerType()) { 196 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 197 << Call->getSourceRange(); 198 return true; 199 } 200 201 const Decl *TargetDecl = CE->getCalleeDecl(); 202 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 203 if (FD->getBuiltinID()) { 204 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 205 << Call->getSourceRange(); 206 return true; 207 } 208 209 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 210 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 211 << Call->getSourceRange(); 212 return true; 213 } 214 215 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 216 if (ChainResult.isInvalid()) 217 return true; 218 if (!ChainResult.get()->getType()->isPointerType()) { 219 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 220 << Chain->getSourceRange(); 221 return true; 222 } 223 224 QualType ReturnTy = CE->getCallReturnType(S.Context); 225 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 226 QualType BuiltinTy = S.Context.getFunctionType( 227 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 228 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 229 230 Builtin = 231 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 232 233 BuiltinCall->setType(CE->getType()); 234 BuiltinCall->setValueKind(CE->getValueKind()); 235 BuiltinCall->setObjectKind(CE->getObjectKind()); 236 BuiltinCall->setCallee(Builtin); 237 BuiltinCall->setArg(1, ChainResult.get()); 238 239 return false; 240 } 241 242 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 243 Scope::ScopeFlags NeededScopeFlags, 244 unsigned DiagID) { 245 // Scopes aren't available during instantiation. Fortunately, builtin 246 // functions cannot be template args so they cannot be formed through template 247 // instantiation. Therefore checking once during the parse is sufficient. 248 if (SemaRef.inTemplateInstantiation()) 249 return false; 250 251 Scope *S = SemaRef.getCurScope(); 252 while (S && !S->isSEHExceptScope()) 253 S = S->getParent(); 254 if (!S || !(S->getFlags() & NeededScopeFlags)) { 255 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 256 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 257 << DRE->getDecl()->getIdentifier(); 258 return true; 259 } 260 261 return false; 262 } 263 264 static inline bool isBlockPointer(Expr *Arg) { 265 return Arg->getType()->isBlockPointerType(); 266 } 267 268 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 269 /// void*, which is a requirement of device side enqueue. 270 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 271 const BlockPointerType *BPT = 272 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 273 ArrayRef<QualType> Params = 274 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 275 unsigned ArgCounter = 0; 276 bool IllegalParams = false; 277 // Iterate through the block parameters until either one is found that is not 278 // a local void*, or the block is valid. 279 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 280 I != E; ++I, ++ArgCounter) { 281 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 282 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 283 LangAS::opencl_local) { 284 // Get the location of the error. If a block literal has been passed 285 // (BlockExpr) then we can point straight to the offending argument, 286 // else we just point to the variable reference. 287 SourceLocation ErrorLoc; 288 if (isa<BlockExpr>(BlockArg)) { 289 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 290 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 291 } else if (isa<DeclRefExpr>(BlockArg)) { 292 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 293 } 294 S.Diag(ErrorLoc, 295 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 296 IllegalParams = true; 297 } 298 } 299 300 return IllegalParams; 301 } 302 303 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 304 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 305 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension) 306 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 307 return true; 308 } 309 return false; 310 } 311 312 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 313 if (checkArgCount(S, TheCall, 2)) 314 return true; 315 316 if (checkOpenCLSubgroupExt(S, TheCall)) 317 return true; 318 319 // First argument is an ndrange_t type. 320 Expr *NDRangeArg = TheCall->getArg(0); 321 if (NDRangeArg->getType().getAsString() != "ndrange_t") { 322 S.Diag(NDRangeArg->getLocStart(), 323 diag::err_opencl_builtin_expected_type) 324 << TheCall->getDirectCallee() << "'ndrange_t'"; 325 return true; 326 } 327 328 Expr *BlockArg = TheCall->getArg(1); 329 if (!isBlockPointer(BlockArg)) { 330 S.Diag(BlockArg->getLocStart(), 331 diag::err_opencl_builtin_expected_type) 332 << TheCall->getDirectCallee() << "block"; 333 return true; 334 } 335 return checkOpenCLBlockArgs(S, BlockArg); 336 } 337 338 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 339 /// get_kernel_work_group_size 340 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 341 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 342 if (checkArgCount(S, TheCall, 1)) 343 return true; 344 345 Expr *BlockArg = TheCall->getArg(0); 346 if (!isBlockPointer(BlockArg)) { 347 S.Diag(BlockArg->getLocStart(), 348 diag::err_opencl_builtin_expected_type) 349 << TheCall->getDirectCallee() << "block"; 350 return true; 351 } 352 return checkOpenCLBlockArgs(S, BlockArg); 353 } 354 355 /// Diagnose integer type and any valid implicit conversion to it. 356 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 357 const QualType &IntType); 358 359 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 360 unsigned Start, unsigned End) { 361 bool IllegalParams = false; 362 for (unsigned I = Start; I <= End; ++I) 363 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 364 S.Context.getSizeType()); 365 return IllegalParams; 366 } 367 368 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 369 /// 'local void*' parameter of passed block. 370 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 371 Expr *BlockArg, 372 unsigned NumNonVarArgs) { 373 const BlockPointerType *BPT = 374 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 375 unsigned NumBlockParams = 376 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 377 unsigned TotalNumArgs = TheCall->getNumArgs(); 378 379 // For each argument passed to the block, a corresponding uint needs to 380 // be passed to describe the size of the local memory. 381 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 382 S.Diag(TheCall->getLocStart(), 383 diag::err_opencl_enqueue_kernel_local_size_args); 384 return true; 385 } 386 387 // Check that the sizes of the local memory are specified by integers. 388 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 389 TotalNumArgs - 1); 390 } 391 392 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 393 /// overload formats specified in Table 6.13.17.1. 394 /// int enqueue_kernel(queue_t queue, 395 /// kernel_enqueue_flags_t flags, 396 /// const ndrange_t ndrange, 397 /// void (^block)(void)) 398 /// int enqueue_kernel(queue_t queue, 399 /// kernel_enqueue_flags_t flags, 400 /// const ndrange_t ndrange, 401 /// uint num_events_in_wait_list, 402 /// clk_event_t *event_wait_list, 403 /// clk_event_t *event_ret, 404 /// void (^block)(void)) 405 /// int enqueue_kernel(queue_t queue, 406 /// kernel_enqueue_flags_t flags, 407 /// const ndrange_t ndrange, 408 /// void (^block)(local void*, ...), 409 /// uint size0, ...) 410 /// int enqueue_kernel(queue_t queue, 411 /// kernel_enqueue_flags_t flags, 412 /// const ndrange_t ndrange, 413 /// uint num_events_in_wait_list, 414 /// clk_event_t *event_wait_list, 415 /// clk_event_t *event_ret, 416 /// void (^block)(local void*, ...), 417 /// uint size0, ...) 418 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 419 unsigned NumArgs = TheCall->getNumArgs(); 420 421 if (NumArgs < 4) { 422 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 423 return true; 424 } 425 426 Expr *Arg0 = TheCall->getArg(0); 427 Expr *Arg1 = TheCall->getArg(1); 428 Expr *Arg2 = TheCall->getArg(2); 429 Expr *Arg3 = TheCall->getArg(3); 430 431 // First argument always needs to be a queue_t type. 432 if (!Arg0->getType()->isQueueT()) { 433 S.Diag(TheCall->getArg(0)->getLocStart(), 434 diag::err_opencl_builtin_expected_type) 435 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 436 return true; 437 } 438 439 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 440 if (!Arg1->getType()->isIntegerType()) { 441 S.Diag(TheCall->getArg(1)->getLocStart(), 442 diag::err_opencl_builtin_expected_type) 443 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 444 return true; 445 } 446 447 // Third argument is always an ndrange_t type. 448 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 449 S.Diag(TheCall->getArg(2)->getLocStart(), 450 diag::err_opencl_builtin_expected_type) 451 << TheCall->getDirectCallee() << "'ndrange_t'"; 452 return true; 453 } 454 455 // With four arguments, there is only one form that the function could be 456 // called in: no events and no variable arguments. 457 if (NumArgs == 4) { 458 // check that the last argument is the right block type. 459 if (!isBlockPointer(Arg3)) { 460 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type) 461 << TheCall->getDirectCallee() << "block"; 462 return true; 463 } 464 // we have a block type, check the prototype 465 const BlockPointerType *BPT = 466 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 467 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 468 S.Diag(Arg3->getLocStart(), 469 diag::err_opencl_enqueue_kernel_blocks_no_args); 470 return true; 471 } 472 return false; 473 } 474 // we can have block + varargs. 475 if (isBlockPointer(Arg3)) 476 return (checkOpenCLBlockArgs(S, Arg3) || 477 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 478 // last two cases with either exactly 7 args or 7 args and varargs. 479 if (NumArgs >= 7) { 480 // check common block argument. 481 Expr *Arg6 = TheCall->getArg(6); 482 if (!isBlockPointer(Arg6)) { 483 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type) 484 << TheCall->getDirectCallee() << "block"; 485 return true; 486 } 487 if (checkOpenCLBlockArgs(S, Arg6)) 488 return true; 489 490 // Forth argument has to be any integer type. 491 if (!Arg3->getType()->isIntegerType()) { 492 S.Diag(TheCall->getArg(3)->getLocStart(), 493 diag::err_opencl_builtin_expected_type) 494 << TheCall->getDirectCallee() << "integer"; 495 return true; 496 } 497 // check remaining common arguments. 498 Expr *Arg4 = TheCall->getArg(4); 499 Expr *Arg5 = TheCall->getArg(5); 500 501 // Fifth argument is always passed as a pointer to clk_event_t. 502 if (!Arg4->isNullPointerConstant(S.Context, 503 Expr::NPC_ValueDependentIsNotNull) && 504 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 505 S.Diag(TheCall->getArg(4)->getLocStart(), 506 diag::err_opencl_builtin_expected_type) 507 << TheCall->getDirectCallee() 508 << S.Context.getPointerType(S.Context.OCLClkEventTy); 509 return true; 510 } 511 512 // Sixth argument is always passed as a pointer to clk_event_t. 513 if (!Arg5->isNullPointerConstant(S.Context, 514 Expr::NPC_ValueDependentIsNotNull) && 515 !(Arg5->getType()->isPointerType() && 516 Arg5->getType()->getPointeeType()->isClkEventT())) { 517 S.Diag(TheCall->getArg(5)->getLocStart(), 518 diag::err_opencl_builtin_expected_type) 519 << TheCall->getDirectCallee() 520 << S.Context.getPointerType(S.Context.OCLClkEventTy); 521 return true; 522 } 523 524 if (NumArgs == 7) 525 return false; 526 527 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 528 } 529 530 // None of the specific case has been detected, give generic error 531 S.Diag(TheCall->getLocStart(), 532 diag::err_opencl_enqueue_kernel_incorrect_args); 533 return true; 534 } 535 536 /// Returns OpenCL access qual. 537 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 538 return D->getAttr<OpenCLAccessAttr>(); 539 } 540 541 /// Returns true if pipe element type is different from the pointer. 542 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 543 const Expr *Arg0 = Call->getArg(0); 544 // First argument type should always be pipe. 545 if (!Arg0->getType()->isPipeType()) { 546 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 547 << Call->getDirectCallee() << Arg0->getSourceRange(); 548 return true; 549 } 550 OpenCLAccessAttr *AccessQual = 551 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 552 // Validates the access qualifier is compatible with the call. 553 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 554 // read_only and write_only, and assumed to be read_only if no qualifier is 555 // specified. 556 switch (Call->getDirectCallee()->getBuiltinID()) { 557 case Builtin::BIread_pipe: 558 case Builtin::BIreserve_read_pipe: 559 case Builtin::BIcommit_read_pipe: 560 case Builtin::BIwork_group_reserve_read_pipe: 561 case Builtin::BIsub_group_reserve_read_pipe: 562 case Builtin::BIwork_group_commit_read_pipe: 563 case Builtin::BIsub_group_commit_read_pipe: 564 if (!(!AccessQual || AccessQual->isReadOnly())) { 565 S.Diag(Arg0->getLocStart(), 566 diag::err_opencl_builtin_pipe_invalid_access_modifier) 567 << "read_only" << Arg0->getSourceRange(); 568 return true; 569 } 570 break; 571 case Builtin::BIwrite_pipe: 572 case Builtin::BIreserve_write_pipe: 573 case Builtin::BIcommit_write_pipe: 574 case Builtin::BIwork_group_reserve_write_pipe: 575 case Builtin::BIsub_group_reserve_write_pipe: 576 case Builtin::BIwork_group_commit_write_pipe: 577 case Builtin::BIsub_group_commit_write_pipe: 578 if (!(AccessQual && AccessQual->isWriteOnly())) { 579 S.Diag(Arg0->getLocStart(), 580 diag::err_opencl_builtin_pipe_invalid_access_modifier) 581 << "write_only" << Arg0->getSourceRange(); 582 return true; 583 } 584 break; 585 default: 586 break; 587 } 588 return false; 589 } 590 591 /// Returns true if pipe element type is different from the pointer. 592 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 593 const Expr *Arg0 = Call->getArg(0); 594 const Expr *ArgIdx = Call->getArg(Idx); 595 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 596 const QualType EltTy = PipeTy->getElementType(); 597 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 598 // The Idx argument should be a pointer and the type of the pointer and 599 // the type of pipe element should also be the same. 600 if (!ArgTy || 601 !S.Context.hasSameType( 602 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 603 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 604 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 605 << ArgIdx->getType() << ArgIdx->getSourceRange(); 606 return true; 607 } 608 return false; 609 } 610 611 // \brief Performs semantic analysis for the read/write_pipe call. 612 // \param S Reference to the semantic analyzer. 613 // \param Call A pointer to the builtin call. 614 // \return True if a semantic error has been found, false otherwise. 615 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 616 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 617 // functions have two forms. 618 switch (Call->getNumArgs()) { 619 case 2: { 620 if (checkOpenCLPipeArg(S, Call)) 621 return true; 622 // The call with 2 arguments should be 623 // read/write_pipe(pipe T, T*). 624 // Check packet type T. 625 if (checkOpenCLPipePacketType(S, Call, 1)) 626 return true; 627 } break; 628 629 case 4: { 630 if (checkOpenCLPipeArg(S, Call)) 631 return true; 632 // The call with 4 arguments should be 633 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 634 // Check reserve_id_t. 635 if (!Call->getArg(1)->getType()->isReserveIDT()) { 636 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 637 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 638 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 639 return true; 640 } 641 642 // Check the index. 643 const Expr *Arg2 = Call->getArg(2); 644 if (!Arg2->getType()->isIntegerType() && 645 !Arg2->getType()->isUnsignedIntegerType()) { 646 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 647 << Call->getDirectCallee() << S.Context.UnsignedIntTy 648 << Arg2->getType() << Arg2->getSourceRange(); 649 return true; 650 } 651 652 // Check packet type T. 653 if (checkOpenCLPipePacketType(S, Call, 3)) 654 return true; 655 } break; 656 default: 657 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 658 << Call->getDirectCallee() << Call->getSourceRange(); 659 return true; 660 } 661 662 return false; 663 } 664 665 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 666 // /_}reserve_{read/write}_pipe 667 // \param S Reference to the semantic analyzer. 668 // \param Call The call to the builtin function to be analyzed. 669 // \return True if a semantic error was found, false otherwise. 670 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 671 if (checkArgCount(S, Call, 2)) 672 return true; 673 674 if (checkOpenCLPipeArg(S, Call)) 675 return true; 676 677 // Check the reserve size. 678 if (!Call->getArg(1)->getType()->isIntegerType() && 679 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 680 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 681 << Call->getDirectCallee() << S.Context.UnsignedIntTy 682 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 683 return true; 684 } 685 686 // Since return type of reserve_read/write_pipe built-in function is 687 // reserve_id_t, which is not defined in the builtin def file , we used int 688 // as return type and need to override the return type of these functions. 689 Call->setType(S.Context.OCLReserveIDTy); 690 691 return false; 692 } 693 694 // \brief Performs a semantic analysis on {work_group_/sub_group_ 695 // /_}commit_{read/write}_pipe 696 // \param S Reference to the semantic analyzer. 697 // \param Call The call to the builtin function to be analyzed. 698 // \return True if a semantic error was found, false otherwise. 699 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 700 if (checkArgCount(S, Call, 2)) 701 return true; 702 703 if (checkOpenCLPipeArg(S, Call)) 704 return true; 705 706 // Check reserve_id_t. 707 if (!Call->getArg(1)->getType()->isReserveIDT()) { 708 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 709 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 710 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 711 return true; 712 } 713 714 return false; 715 } 716 717 // \brief Performs a semantic analysis on the call to built-in Pipe 718 // Query Functions. 719 // \param S Reference to the semantic analyzer. 720 // \param Call The call to the builtin function to be analyzed. 721 // \return True if a semantic error was found, false otherwise. 722 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 723 if (checkArgCount(S, Call, 1)) 724 return true; 725 726 if (!Call->getArg(0)->getType()->isPipeType()) { 727 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 728 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 729 return true; 730 } 731 732 return false; 733 } 734 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 735 // \brief Performs semantic analysis for the to_global/local/private call. 736 // \param S Reference to the semantic analyzer. 737 // \param BuiltinID ID of the builtin function. 738 // \param Call A pointer to the builtin call. 739 // \return True if a semantic error has been found, false otherwise. 740 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 741 CallExpr *Call) { 742 if (Call->getNumArgs() != 1) { 743 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 744 << Call->getDirectCallee() << Call->getSourceRange(); 745 return true; 746 } 747 748 auto RT = Call->getArg(0)->getType(); 749 if (!RT->isPointerType() || RT->getPointeeType() 750 .getAddressSpace() == LangAS::opencl_constant) { 751 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 752 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 753 return true; 754 } 755 756 RT = RT->getPointeeType(); 757 auto Qual = RT.getQualifiers(); 758 switch (BuiltinID) { 759 case Builtin::BIto_global: 760 Qual.setAddressSpace(LangAS::opencl_global); 761 break; 762 case Builtin::BIto_local: 763 Qual.setAddressSpace(LangAS::opencl_local); 764 break; 765 default: 766 Qual.removeAddressSpace(); 767 } 768 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 769 RT.getUnqualifiedType(), Qual))); 770 771 return false; 772 } 773 774 ExprResult 775 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 776 CallExpr *TheCall) { 777 ExprResult TheCallResult(TheCall); 778 779 // Find out if any arguments are required to be integer constant expressions. 780 unsigned ICEArguments = 0; 781 ASTContext::GetBuiltinTypeError Error; 782 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 783 if (Error != ASTContext::GE_None) 784 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 785 786 // If any arguments are required to be ICE's, check and diagnose. 787 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 788 // Skip arguments not required to be ICE's. 789 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 790 791 llvm::APSInt Result; 792 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 793 return true; 794 ICEArguments &= ~(1 << ArgNo); 795 } 796 797 switch (BuiltinID) { 798 case Builtin::BI__builtin___CFStringMakeConstantString: 799 assert(TheCall->getNumArgs() == 1 && 800 "Wrong # arguments to builtin CFStringMakeConstantString"); 801 if (CheckObjCString(TheCall->getArg(0))) 802 return ExprError(); 803 break; 804 case Builtin::BI__builtin_ms_va_start: 805 case Builtin::BI__builtin_stdarg_start: 806 case Builtin::BI__builtin_va_start: 807 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 808 return ExprError(); 809 break; 810 case Builtin::BI__va_start: { 811 switch (Context.getTargetInfo().getTriple().getArch()) { 812 case llvm::Triple::arm: 813 case llvm::Triple::thumb: 814 if (SemaBuiltinVAStartARM(TheCall)) 815 return ExprError(); 816 break; 817 default: 818 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 819 return ExprError(); 820 break; 821 } 822 break; 823 } 824 case Builtin::BI__builtin_isgreater: 825 case Builtin::BI__builtin_isgreaterequal: 826 case Builtin::BI__builtin_isless: 827 case Builtin::BI__builtin_islessequal: 828 case Builtin::BI__builtin_islessgreater: 829 case Builtin::BI__builtin_isunordered: 830 if (SemaBuiltinUnorderedCompare(TheCall)) 831 return ExprError(); 832 break; 833 case Builtin::BI__builtin_fpclassify: 834 if (SemaBuiltinFPClassification(TheCall, 6)) 835 return ExprError(); 836 break; 837 case Builtin::BI__builtin_isfinite: 838 case Builtin::BI__builtin_isinf: 839 case Builtin::BI__builtin_isinf_sign: 840 case Builtin::BI__builtin_isnan: 841 case Builtin::BI__builtin_isnormal: 842 if (SemaBuiltinFPClassification(TheCall, 1)) 843 return ExprError(); 844 break; 845 case Builtin::BI__builtin_shufflevector: 846 return SemaBuiltinShuffleVector(TheCall); 847 // TheCall will be freed by the smart pointer here, but that's fine, since 848 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 849 case Builtin::BI__builtin_prefetch: 850 if (SemaBuiltinPrefetch(TheCall)) 851 return ExprError(); 852 break; 853 case Builtin::BI__builtin_alloca_with_align: 854 if (SemaBuiltinAllocaWithAlign(TheCall)) 855 return ExprError(); 856 break; 857 case Builtin::BI__assume: 858 case Builtin::BI__builtin_assume: 859 if (SemaBuiltinAssume(TheCall)) 860 return ExprError(); 861 break; 862 case Builtin::BI__builtin_assume_aligned: 863 if (SemaBuiltinAssumeAligned(TheCall)) 864 return ExprError(); 865 break; 866 case Builtin::BI__builtin_object_size: 867 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 868 return ExprError(); 869 break; 870 case Builtin::BI__builtin_longjmp: 871 if (SemaBuiltinLongjmp(TheCall)) 872 return ExprError(); 873 break; 874 case Builtin::BI__builtin_setjmp: 875 if (SemaBuiltinSetjmp(TheCall)) 876 return ExprError(); 877 break; 878 case Builtin::BI_setjmp: 879 case Builtin::BI_setjmpex: 880 if (checkArgCount(*this, TheCall, 1)) 881 return true; 882 break; 883 884 case Builtin::BI__builtin_classify_type: 885 if (checkArgCount(*this, TheCall, 1)) return true; 886 TheCall->setType(Context.IntTy); 887 break; 888 case Builtin::BI__builtin_constant_p: 889 if (checkArgCount(*this, TheCall, 1)) return true; 890 TheCall->setType(Context.IntTy); 891 break; 892 case Builtin::BI__sync_fetch_and_add: 893 case Builtin::BI__sync_fetch_and_add_1: 894 case Builtin::BI__sync_fetch_and_add_2: 895 case Builtin::BI__sync_fetch_and_add_4: 896 case Builtin::BI__sync_fetch_and_add_8: 897 case Builtin::BI__sync_fetch_and_add_16: 898 case Builtin::BI__sync_fetch_and_sub: 899 case Builtin::BI__sync_fetch_and_sub_1: 900 case Builtin::BI__sync_fetch_and_sub_2: 901 case Builtin::BI__sync_fetch_and_sub_4: 902 case Builtin::BI__sync_fetch_and_sub_8: 903 case Builtin::BI__sync_fetch_and_sub_16: 904 case Builtin::BI__sync_fetch_and_or: 905 case Builtin::BI__sync_fetch_and_or_1: 906 case Builtin::BI__sync_fetch_and_or_2: 907 case Builtin::BI__sync_fetch_and_or_4: 908 case Builtin::BI__sync_fetch_and_or_8: 909 case Builtin::BI__sync_fetch_and_or_16: 910 case Builtin::BI__sync_fetch_and_and: 911 case Builtin::BI__sync_fetch_and_and_1: 912 case Builtin::BI__sync_fetch_and_and_2: 913 case Builtin::BI__sync_fetch_and_and_4: 914 case Builtin::BI__sync_fetch_and_and_8: 915 case Builtin::BI__sync_fetch_and_and_16: 916 case Builtin::BI__sync_fetch_and_xor: 917 case Builtin::BI__sync_fetch_and_xor_1: 918 case Builtin::BI__sync_fetch_and_xor_2: 919 case Builtin::BI__sync_fetch_and_xor_4: 920 case Builtin::BI__sync_fetch_and_xor_8: 921 case Builtin::BI__sync_fetch_and_xor_16: 922 case Builtin::BI__sync_fetch_and_nand: 923 case Builtin::BI__sync_fetch_and_nand_1: 924 case Builtin::BI__sync_fetch_and_nand_2: 925 case Builtin::BI__sync_fetch_and_nand_4: 926 case Builtin::BI__sync_fetch_and_nand_8: 927 case Builtin::BI__sync_fetch_and_nand_16: 928 case Builtin::BI__sync_add_and_fetch: 929 case Builtin::BI__sync_add_and_fetch_1: 930 case Builtin::BI__sync_add_and_fetch_2: 931 case Builtin::BI__sync_add_and_fetch_4: 932 case Builtin::BI__sync_add_and_fetch_8: 933 case Builtin::BI__sync_add_and_fetch_16: 934 case Builtin::BI__sync_sub_and_fetch: 935 case Builtin::BI__sync_sub_and_fetch_1: 936 case Builtin::BI__sync_sub_and_fetch_2: 937 case Builtin::BI__sync_sub_and_fetch_4: 938 case Builtin::BI__sync_sub_and_fetch_8: 939 case Builtin::BI__sync_sub_and_fetch_16: 940 case Builtin::BI__sync_and_and_fetch: 941 case Builtin::BI__sync_and_and_fetch_1: 942 case Builtin::BI__sync_and_and_fetch_2: 943 case Builtin::BI__sync_and_and_fetch_4: 944 case Builtin::BI__sync_and_and_fetch_8: 945 case Builtin::BI__sync_and_and_fetch_16: 946 case Builtin::BI__sync_or_and_fetch: 947 case Builtin::BI__sync_or_and_fetch_1: 948 case Builtin::BI__sync_or_and_fetch_2: 949 case Builtin::BI__sync_or_and_fetch_4: 950 case Builtin::BI__sync_or_and_fetch_8: 951 case Builtin::BI__sync_or_and_fetch_16: 952 case Builtin::BI__sync_xor_and_fetch: 953 case Builtin::BI__sync_xor_and_fetch_1: 954 case Builtin::BI__sync_xor_and_fetch_2: 955 case Builtin::BI__sync_xor_and_fetch_4: 956 case Builtin::BI__sync_xor_and_fetch_8: 957 case Builtin::BI__sync_xor_and_fetch_16: 958 case Builtin::BI__sync_nand_and_fetch: 959 case Builtin::BI__sync_nand_and_fetch_1: 960 case Builtin::BI__sync_nand_and_fetch_2: 961 case Builtin::BI__sync_nand_and_fetch_4: 962 case Builtin::BI__sync_nand_and_fetch_8: 963 case Builtin::BI__sync_nand_and_fetch_16: 964 case Builtin::BI__sync_val_compare_and_swap: 965 case Builtin::BI__sync_val_compare_and_swap_1: 966 case Builtin::BI__sync_val_compare_and_swap_2: 967 case Builtin::BI__sync_val_compare_and_swap_4: 968 case Builtin::BI__sync_val_compare_and_swap_8: 969 case Builtin::BI__sync_val_compare_and_swap_16: 970 case Builtin::BI__sync_bool_compare_and_swap: 971 case Builtin::BI__sync_bool_compare_and_swap_1: 972 case Builtin::BI__sync_bool_compare_and_swap_2: 973 case Builtin::BI__sync_bool_compare_and_swap_4: 974 case Builtin::BI__sync_bool_compare_and_swap_8: 975 case Builtin::BI__sync_bool_compare_and_swap_16: 976 case Builtin::BI__sync_lock_test_and_set: 977 case Builtin::BI__sync_lock_test_and_set_1: 978 case Builtin::BI__sync_lock_test_and_set_2: 979 case Builtin::BI__sync_lock_test_and_set_4: 980 case Builtin::BI__sync_lock_test_and_set_8: 981 case Builtin::BI__sync_lock_test_and_set_16: 982 case Builtin::BI__sync_lock_release: 983 case Builtin::BI__sync_lock_release_1: 984 case Builtin::BI__sync_lock_release_2: 985 case Builtin::BI__sync_lock_release_4: 986 case Builtin::BI__sync_lock_release_8: 987 case Builtin::BI__sync_lock_release_16: 988 case Builtin::BI__sync_swap: 989 case Builtin::BI__sync_swap_1: 990 case Builtin::BI__sync_swap_2: 991 case Builtin::BI__sync_swap_4: 992 case Builtin::BI__sync_swap_8: 993 case Builtin::BI__sync_swap_16: 994 return SemaBuiltinAtomicOverloaded(TheCallResult); 995 case Builtin::BI__builtin_nontemporal_load: 996 case Builtin::BI__builtin_nontemporal_store: 997 return SemaBuiltinNontemporalOverloaded(TheCallResult); 998 #define BUILTIN(ID, TYPE, ATTRS) 999 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1000 case Builtin::BI##ID: \ 1001 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1002 #include "clang/Basic/Builtins.def" 1003 case Builtin::BI__builtin_annotation: 1004 if (SemaBuiltinAnnotation(*this, TheCall)) 1005 return ExprError(); 1006 break; 1007 case Builtin::BI__builtin_addressof: 1008 if (SemaBuiltinAddressof(*this, TheCall)) 1009 return ExprError(); 1010 break; 1011 case Builtin::BI__builtin_add_overflow: 1012 case Builtin::BI__builtin_sub_overflow: 1013 case Builtin::BI__builtin_mul_overflow: 1014 if (SemaBuiltinOverflow(*this, TheCall)) 1015 return ExprError(); 1016 break; 1017 case Builtin::BI__builtin_operator_new: 1018 case Builtin::BI__builtin_operator_delete: 1019 if (!getLangOpts().CPlusPlus) { 1020 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 1021 << (BuiltinID == Builtin::BI__builtin_operator_new 1022 ? "__builtin_operator_new" 1023 : "__builtin_operator_delete") 1024 << "C++"; 1025 return ExprError(); 1026 } 1027 // CodeGen assumes it can find the global new and delete to call, 1028 // so ensure that they are declared. 1029 DeclareGlobalNewDelete(); 1030 break; 1031 1032 // check secure string manipulation functions where overflows 1033 // are detectable at compile time 1034 case Builtin::BI__builtin___memcpy_chk: 1035 case Builtin::BI__builtin___memmove_chk: 1036 case Builtin::BI__builtin___memset_chk: 1037 case Builtin::BI__builtin___strlcat_chk: 1038 case Builtin::BI__builtin___strlcpy_chk: 1039 case Builtin::BI__builtin___strncat_chk: 1040 case Builtin::BI__builtin___strncpy_chk: 1041 case Builtin::BI__builtin___stpncpy_chk: 1042 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1043 break; 1044 case Builtin::BI__builtin___memccpy_chk: 1045 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1046 break; 1047 case Builtin::BI__builtin___snprintf_chk: 1048 case Builtin::BI__builtin___vsnprintf_chk: 1049 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1050 break; 1051 case Builtin::BI__builtin_call_with_static_chain: 1052 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1053 return ExprError(); 1054 break; 1055 case Builtin::BI__exception_code: 1056 case Builtin::BI_exception_code: 1057 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1058 diag::err_seh___except_block)) 1059 return ExprError(); 1060 break; 1061 case Builtin::BI__exception_info: 1062 case Builtin::BI_exception_info: 1063 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1064 diag::err_seh___except_filter)) 1065 return ExprError(); 1066 break; 1067 case Builtin::BI__GetExceptionInfo: 1068 if (checkArgCount(*this, TheCall, 1)) 1069 return ExprError(); 1070 1071 if (CheckCXXThrowOperand( 1072 TheCall->getLocStart(), 1073 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1074 TheCall)) 1075 return ExprError(); 1076 1077 TheCall->setType(Context.VoidPtrTy); 1078 break; 1079 // OpenCL v2.0, s6.13.16 - Pipe functions 1080 case Builtin::BIread_pipe: 1081 case Builtin::BIwrite_pipe: 1082 // Since those two functions are declared with var args, we need a semantic 1083 // check for the argument. 1084 if (SemaBuiltinRWPipe(*this, TheCall)) 1085 return ExprError(); 1086 TheCall->setType(Context.IntTy); 1087 break; 1088 case Builtin::BIreserve_read_pipe: 1089 case Builtin::BIreserve_write_pipe: 1090 case Builtin::BIwork_group_reserve_read_pipe: 1091 case Builtin::BIwork_group_reserve_write_pipe: 1092 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1093 return ExprError(); 1094 break; 1095 case Builtin::BIsub_group_reserve_read_pipe: 1096 case Builtin::BIsub_group_reserve_write_pipe: 1097 if (checkOpenCLSubgroupExt(*this, TheCall) || 1098 SemaBuiltinReserveRWPipe(*this, TheCall)) 1099 return ExprError(); 1100 break; 1101 case Builtin::BIcommit_read_pipe: 1102 case Builtin::BIcommit_write_pipe: 1103 case Builtin::BIwork_group_commit_read_pipe: 1104 case Builtin::BIwork_group_commit_write_pipe: 1105 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1106 return ExprError(); 1107 break; 1108 case Builtin::BIsub_group_commit_read_pipe: 1109 case Builtin::BIsub_group_commit_write_pipe: 1110 if (checkOpenCLSubgroupExt(*this, TheCall) || 1111 SemaBuiltinCommitRWPipe(*this, TheCall)) 1112 return ExprError(); 1113 break; 1114 case Builtin::BIget_pipe_num_packets: 1115 case Builtin::BIget_pipe_max_packets: 1116 if (SemaBuiltinPipePackets(*this, TheCall)) 1117 return ExprError(); 1118 TheCall->setType(Context.UnsignedIntTy); 1119 break; 1120 case Builtin::BIto_global: 1121 case Builtin::BIto_local: 1122 case Builtin::BIto_private: 1123 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1124 return ExprError(); 1125 break; 1126 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1127 case Builtin::BIenqueue_kernel: 1128 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1129 return ExprError(); 1130 break; 1131 case Builtin::BIget_kernel_work_group_size: 1132 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1133 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1134 return ExprError(); 1135 break; 1136 break; 1137 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1138 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1139 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1140 return ExprError(); 1141 break; 1142 case Builtin::BI__builtin_os_log_format: 1143 case Builtin::BI__builtin_os_log_format_buffer_size: 1144 if (SemaBuiltinOSLogFormat(TheCall)) { 1145 return ExprError(); 1146 } 1147 break; 1148 } 1149 1150 // Since the target specific builtins for each arch overlap, only check those 1151 // of the arch we are compiling for. 1152 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1153 switch (Context.getTargetInfo().getTriple().getArch()) { 1154 case llvm::Triple::arm: 1155 case llvm::Triple::armeb: 1156 case llvm::Triple::thumb: 1157 case llvm::Triple::thumbeb: 1158 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1159 return ExprError(); 1160 break; 1161 case llvm::Triple::aarch64: 1162 case llvm::Triple::aarch64_be: 1163 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1164 return ExprError(); 1165 break; 1166 case llvm::Triple::mips: 1167 case llvm::Triple::mipsel: 1168 case llvm::Triple::mips64: 1169 case llvm::Triple::mips64el: 1170 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1171 return ExprError(); 1172 break; 1173 case llvm::Triple::systemz: 1174 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1175 return ExprError(); 1176 break; 1177 case llvm::Triple::x86: 1178 case llvm::Triple::x86_64: 1179 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1180 return ExprError(); 1181 break; 1182 case llvm::Triple::ppc: 1183 case llvm::Triple::ppc64: 1184 case llvm::Triple::ppc64le: 1185 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1186 return ExprError(); 1187 break; 1188 default: 1189 break; 1190 } 1191 } 1192 1193 return TheCallResult; 1194 } 1195 1196 // Get the valid immediate range for the specified NEON type code. 1197 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1198 NeonTypeFlags Type(t); 1199 int IsQuad = ForceQuad ? true : Type.isQuad(); 1200 switch (Type.getEltType()) { 1201 case NeonTypeFlags::Int8: 1202 case NeonTypeFlags::Poly8: 1203 return shift ? 7 : (8 << IsQuad) - 1; 1204 case NeonTypeFlags::Int16: 1205 case NeonTypeFlags::Poly16: 1206 return shift ? 15 : (4 << IsQuad) - 1; 1207 case NeonTypeFlags::Int32: 1208 return shift ? 31 : (2 << IsQuad) - 1; 1209 case NeonTypeFlags::Int64: 1210 case NeonTypeFlags::Poly64: 1211 return shift ? 63 : (1 << IsQuad) - 1; 1212 case NeonTypeFlags::Poly128: 1213 return shift ? 127 : (1 << IsQuad) - 1; 1214 case NeonTypeFlags::Float16: 1215 assert(!shift && "cannot shift float types!"); 1216 return (4 << IsQuad) - 1; 1217 case NeonTypeFlags::Float32: 1218 assert(!shift && "cannot shift float types!"); 1219 return (2 << IsQuad) - 1; 1220 case NeonTypeFlags::Float64: 1221 assert(!shift && "cannot shift float types!"); 1222 return (1 << IsQuad) - 1; 1223 } 1224 llvm_unreachable("Invalid NeonTypeFlag!"); 1225 } 1226 1227 /// getNeonEltType - Return the QualType corresponding to the elements of 1228 /// the vector type specified by the NeonTypeFlags. This is used to check 1229 /// the pointer arguments for Neon load/store intrinsics. 1230 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1231 bool IsPolyUnsigned, bool IsInt64Long) { 1232 switch (Flags.getEltType()) { 1233 case NeonTypeFlags::Int8: 1234 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1235 case NeonTypeFlags::Int16: 1236 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1237 case NeonTypeFlags::Int32: 1238 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1239 case NeonTypeFlags::Int64: 1240 if (IsInt64Long) 1241 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1242 else 1243 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1244 : Context.LongLongTy; 1245 case NeonTypeFlags::Poly8: 1246 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1247 case NeonTypeFlags::Poly16: 1248 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1249 case NeonTypeFlags::Poly64: 1250 if (IsInt64Long) 1251 return Context.UnsignedLongTy; 1252 else 1253 return Context.UnsignedLongLongTy; 1254 case NeonTypeFlags::Poly128: 1255 break; 1256 case NeonTypeFlags::Float16: 1257 return Context.HalfTy; 1258 case NeonTypeFlags::Float32: 1259 return Context.FloatTy; 1260 case NeonTypeFlags::Float64: 1261 return Context.DoubleTy; 1262 } 1263 llvm_unreachable("Invalid NeonTypeFlag!"); 1264 } 1265 1266 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1267 llvm::APSInt Result; 1268 uint64_t mask = 0; 1269 unsigned TV = 0; 1270 int PtrArgNum = -1; 1271 bool HasConstPtr = false; 1272 switch (BuiltinID) { 1273 #define GET_NEON_OVERLOAD_CHECK 1274 #include "clang/Basic/arm_neon.inc" 1275 #undef GET_NEON_OVERLOAD_CHECK 1276 } 1277 1278 // For NEON intrinsics which are overloaded on vector element type, validate 1279 // the immediate which specifies which variant to emit. 1280 unsigned ImmArg = TheCall->getNumArgs()-1; 1281 if (mask) { 1282 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1283 return true; 1284 1285 TV = Result.getLimitedValue(64); 1286 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1287 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1288 << TheCall->getArg(ImmArg)->getSourceRange(); 1289 } 1290 1291 if (PtrArgNum >= 0) { 1292 // Check that pointer arguments have the specified type. 1293 Expr *Arg = TheCall->getArg(PtrArgNum); 1294 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1295 Arg = ICE->getSubExpr(); 1296 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1297 QualType RHSTy = RHS.get()->getType(); 1298 1299 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1300 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1301 Arch == llvm::Triple::aarch64_be; 1302 bool IsInt64Long = 1303 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1304 QualType EltTy = 1305 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1306 if (HasConstPtr) 1307 EltTy = EltTy.withConst(); 1308 QualType LHSTy = Context.getPointerType(EltTy); 1309 AssignConvertType ConvTy; 1310 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1311 if (RHS.isInvalid()) 1312 return true; 1313 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1314 RHS.get(), AA_Assigning)) 1315 return true; 1316 } 1317 1318 // For NEON intrinsics which take an immediate value as part of the 1319 // instruction, range check them here. 1320 unsigned i = 0, l = 0, u = 0; 1321 switch (BuiltinID) { 1322 default: 1323 return false; 1324 #define GET_NEON_IMMEDIATE_CHECK 1325 #include "clang/Basic/arm_neon.inc" 1326 #undef GET_NEON_IMMEDIATE_CHECK 1327 } 1328 1329 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1330 } 1331 1332 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1333 unsigned MaxWidth) { 1334 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1335 BuiltinID == ARM::BI__builtin_arm_ldaex || 1336 BuiltinID == ARM::BI__builtin_arm_strex || 1337 BuiltinID == ARM::BI__builtin_arm_stlex || 1338 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1339 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1340 BuiltinID == AArch64::BI__builtin_arm_strex || 1341 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1342 "unexpected ARM builtin"); 1343 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1344 BuiltinID == ARM::BI__builtin_arm_ldaex || 1345 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1346 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1347 1348 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1349 1350 // Ensure that we have the proper number of arguments. 1351 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1352 return true; 1353 1354 // Inspect the pointer argument of the atomic builtin. This should always be 1355 // a pointer type, whose element is an integral scalar or pointer type. 1356 // Because it is a pointer type, we don't have to worry about any implicit 1357 // casts here. 1358 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1359 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1360 if (PointerArgRes.isInvalid()) 1361 return true; 1362 PointerArg = PointerArgRes.get(); 1363 1364 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1365 if (!pointerType) { 1366 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1367 << PointerArg->getType() << PointerArg->getSourceRange(); 1368 return true; 1369 } 1370 1371 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1372 // task is to insert the appropriate casts into the AST. First work out just 1373 // what the appropriate type is. 1374 QualType ValType = pointerType->getPointeeType(); 1375 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1376 if (IsLdrex) 1377 AddrType.addConst(); 1378 1379 // Issue a warning if the cast is dodgy. 1380 CastKind CastNeeded = CK_NoOp; 1381 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1382 CastNeeded = CK_BitCast; 1383 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1384 << PointerArg->getType() 1385 << Context.getPointerType(AddrType) 1386 << AA_Passing << PointerArg->getSourceRange(); 1387 } 1388 1389 // Finally, do the cast and replace the argument with the corrected version. 1390 AddrType = Context.getPointerType(AddrType); 1391 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1392 if (PointerArgRes.isInvalid()) 1393 return true; 1394 PointerArg = PointerArgRes.get(); 1395 1396 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1397 1398 // In general, we allow ints, floats and pointers to be loaded and stored. 1399 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1400 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1401 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1402 << PointerArg->getType() << PointerArg->getSourceRange(); 1403 return true; 1404 } 1405 1406 // But ARM doesn't have instructions to deal with 128-bit versions. 1407 if (Context.getTypeSize(ValType) > MaxWidth) { 1408 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1409 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1410 << PointerArg->getType() << PointerArg->getSourceRange(); 1411 return true; 1412 } 1413 1414 switch (ValType.getObjCLifetime()) { 1415 case Qualifiers::OCL_None: 1416 case Qualifiers::OCL_ExplicitNone: 1417 // okay 1418 break; 1419 1420 case Qualifiers::OCL_Weak: 1421 case Qualifiers::OCL_Strong: 1422 case Qualifiers::OCL_Autoreleasing: 1423 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1424 << ValType << PointerArg->getSourceRange(); 1425 return true; 1426 } 1427 1428 if (IsLdrex) { 1429 TheCall->setType(ValType); 1430 return false; 1431 } 1432 1433 // Initialize the argument to be stored. 1434 ExprResult ValArg = TheCall->getArg(0); 1435 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1436 Context, ValType, /*consume*/ false); 1437 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1438 if (ValArg.isInvalid()) 1439 return true; 1440 TheCall->setArg(0, ValArg.get()); 1441 1442 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1443 // but the custom checker bypasses all default analysis. 1444 TheCall->setType(Context.IntTy); 1445 return false; 1446 } 1447 1448 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1449 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1450 BuiltinID == ARM::BI__builtin_arm_ldaex || 1451 BuiltinID == ARM::BI__builtin_arm_strex || 1452 BuiltinID == ARM::BI__builtin_arm_stlex) { 1453 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1454 } 1455 1456 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1457 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1458 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1459 } 1460 1461 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1462 BuiltinID == ARM::BI__builtin_arm_wsr64) 1463 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1464 1465 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1466 BuiltinID == ARM::BI__builtin_arm_rsrp || 1467 BuiltinID == ARM::BI__builtin_arm_wsr || 1468 BuiltinID == ARM::BI__builtin_arm_wsrp) 1469 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1470 1471 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1472 return true; 1473 1474 // For intrinsics which take an immediate value as part of the instruction, 1475 // range check them here. 1476 unsigned i = 0, l = 0, u = 0; 1477 switch (BuiltinID) { 1478 default: return false; 1479 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1480 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1481 case ARM::BI__builtin_arm_vcvtr_f: 1482 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1483 case ARM::BI__builtin_arm_dmb: 1484 case ARM::BI__builtin_arm_dsb: 1485 case ARM::BI__builtin_arm_isb: 1486 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1487 } 1488 1489 // FIXME: VFP Intrinsics should error if VFP not present. 1490 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1491 } 1492 1493 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1494 CallExpr *TheCall) { 1495 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1496 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1497 BuiltinID == AArch64::BI__builtin_arm_strex || 1498 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1499 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1500 } 1501 1502 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1503 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1504 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1505 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1506 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1507 } 1508 1509 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1510 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1511 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1512 1513 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1514 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1515 BuiltinID == AArch64::BI__builtin_arm_wsr || 1516 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1517 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1518 1519 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1520 return true; 1521 1522 // For intrinsics which take an immediate value as part of the instruction, 1523 // range check them here. 1524 unsigned i = 0, l = 0, u = 0; 1525 switch (BuiltinID) { 1526 default: return false; 1527 case AArch64::BI__builtin_arm_dmb: 1528 case AArch64::BI__builtin_arm_dsb: 1529 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1530 } 1531 1532 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1533 } 1534 1535 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1536 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1537 // ordering for DSP is unspecified. MSA is ordered by the data format used 1538 // by the underlying instruction i.e., df/m, df/n and then by size. 1539 // 1540 // FIXME: The size tests here should instead be tablegen'd along with the 1541 // definitions from include/clang/Basic/BuiltinsMips.def. 1542 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1543 // be too. 1544 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1545 unsigned i = 0, l = 0, u = 0, m = 0; 1546 switch (BuiltinID) { 1547 default: return false; 1548 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1549 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1550 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1551 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1552 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1553 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1554 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1555 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1556 // df/m field. 1557 // These intrinsics take an unsigned 3 bit immediate. 1558 case Mips::BI__builtin_msa_bclri_b: 1559 case Mips::BI__builtin_msa_bnegi_b: 1560 case Mips::BI__builtin_msa_bseti_b: 1561 case Mips::BI__builtin_msa_sat_s_b: 1562 case Mips::BI__builtin_msa_sat_u_b: 1563 case Mips::BI__builtin_msa_slli_b: 1564 case Mips::BI__builtin_msa_srai_b: 1565 case Mips::BI__builtin_msa_srari_b: 1566 case Mips::BI__builtin_msa_srli_b: 1567 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1568 case Mips::BI__builtin_msa_binsli_b: 1569 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1570 // These intrinsics take an unsigned 4 bit immediate. 1571 case Mips::BI__builtin_msa_bclri_h: 1572 case Mips::BI__builtin_msa_bnegi_h: 1573 case Mips::BI__builtin_msa_bseti_h: 1574 case Mips::BI__builtin_msa_sat_s_h: 1575 case Mips::BI__builtin_msa_sat_u_h: 1576 case Mips::BI__builtin_msa_slli_h: 1577 case Mips::BI__builtin_msa_srai_h: 1578 case Mips::BI__builtin_msa_srari_h: 1579 case Mips::BI__builtin_msa_srli_h: 1580 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1581 case Mips::BI__builtin_msa_binsli_h: 1582 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1583 // These intrinsics take an unsigned 5 bit immedate. 1584 // The first block of intrinsics actually have an unsigned 5 bit field, 1585 // not a df/n field. 1586 case Mips::BI__builtin_msa_clei_u_b: 1587 case Mips::BI__builtin_msa_clei_u_h: 1588 case Mips::BI__builtin_msa_clei_u_w: 1589 case Mips::BI__builtin_msa_clei_u_d: 1590 case Mips::BI__builtin_msa_clti_u_b: 1591 case Mips::BI__builtin_msa_clti_u_h: 1592 case Mips::BI__builtin_msa_clti_u_w: 1593 case Mips::BI__builtin_msa_clti_u_d: 1594 case Mips::BI__builtin_msa_maxi_u_b: 1595 case Mips::BI__builtin_msa_maxi_u_h: 1596 case Mips::BI__builtin_msa_maxi_u_w: 1597 case Mips::BI__builtin_msa_maxi_u_d: 1598 case Mips::BI__builtin_msa_mini_u_b: 1599 case Mips::BI__builtin_msa_mini_u_h: 1600 case Mips::BI__builtin_msa_mini_u_w: 1601 case Mips::BI__builtin_msa_mini_u_d: 1602 case Mips::BI__builtin_msa_addvi_b: 1603 case Mips::BI__builtin_msa_addvi_h: 1604 case Mips::BI__builtin_msa_addvi_w: 1605 case Mips::BI__builtin_msa_addvi_d: 1606 case Mips::BI__builtin_msa_bclri_w: 1607 case Mips::BI__builtin_msa_bnegi_w: 1608 case Mips::BI__builtin_msa_bseti_w: 1609 case Mips::BI__builtin_msa_sat_s_w: 1610 case Mips::BI__builtin_msa_sat_u_w: 1611 case Mips::BI__builtin_msa_slli_w: 1612 case Mips::BI__builtin_msa_srai_w: 1613 case Mips::BI__builtin_msa_srari_w: 1614 case Mips::BI__builtin_msa_srli_w: 1615 case Mips::BI__builtin_msa_srlri_w: 1616 case Mips::BI__builtin_msa_subvi_b: 1617 case Mips::BI__builtin_msa_subvi_h: 1618 case Mips::BI__builtin_msa_subvi_w: 1619 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1620 case Mips::BI__builtin_msa_binsli_w: 1621 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1622 // These intrinsics take an unsigned 6 bit immediate. 1623 case Mips::BI__builtin_msa_bclri_d: 1624 case Mips::BI__builtin_msa_bnegi_d: 1625 case Mips::BI__builtin_msa_bseti_d: 1626 case Mips::BI__builtin_msa_sat_s_d: 1627 case Mips::BI__builtin_msa_sat_u_d: 1628 case Mips::BI__builtin_msa_slli_d: 1629 case Mips::BI__builtin_msa_srai_d: 1630 case Mips::BI__builtin_msa_srari_d: 1631 case Mips::BI__builtin_msa_srli_d: 1632 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1633 case Mips::BI__builtin_msa_binsli_d: 1634 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1635 // These intrinsics take a signed 5 bit immediate. 1636 case Mips::BI__builtin_msa_ceqi_b: 1637 case Mips::BI__builtin_msa_ceqi_h: 1638 case Mips::BI__builtin_msa_ceqi_w: 1639 case Mips::BI__builtin_msa_ceqi_d: 1640 case Mips::BI__builtin_msa_clti_s_b: 1641 case Mips::BI__builtin_msa_clti_s_h: 1642 case Mips::BI__builtin_msa_clti_s_w: 1643 case Mips::BI__builtin_msa_clti_s_d: 1644 case Mips::BI__builtin_msa_clei_s_b: 1645 case Mips::BI__builtin_msa_clei_s_h: 1646 case Mips::BI__builtin_msa_clei_s_w: 1647 case Mips::BI__builtin_msa_clei_s_d: 1648 case Mips::BI__builtin_msa_maxi_s_b: 1649 case Mips::BI__builtin_msa_maxi_s_h: 1650 case Mips::BI__builtin_msa_maxi_s_w: 1651 case Mips::BI__builtin_msa_maxi_s_d: 1652 case Mips::BI__builtin_msa_mini_s_b: 1653 case Mips::BI__builtin_msa_mini_s_h: 1654 case Mips::BI__builtin_msa_mini_s_w: 1655 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1656 // These intrinsics take an unsigned 8 bit immediate. 1657 case Mips::BI__builtin_msa_andi_b: 1658 case Mips::BI__builtin_msa_nori_b: 1659 case Mips::BI__builtin_msa_ori_b: 1660 case Mips::BI__builtin_msa_shf_b: 1661 case Mips::BI__builtin_msa_shf_h: 1662 case Mips::BI__builtin_msa_shf_w: 1663 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1664 case Mips::BI__builtin_msa_bseli_b: 1665 case Mips::BI__builtin_msa_bmnzi_b: 1666 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1667 // df/n format 1668 // These intrinsics take an unsigned 4 bit immediate. 1669 case Mips::BI__builtin_msa_copy_s_b: 1670 case Mips::BI__builtin_msa_copy_u_b: 1671 case Mips::BI__builtin_msa_insve_b: 1672 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1673 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1674 // These intrinsics take an unsigned 3 bit immediate. 1675 case Mips::BI__builtin_msa_copy_s_h: 1676 case Mips::BI__builtin_msa_copy_u_h: 1677 case Mips::BI__builtin_msa_insve_h: 1678 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1679 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1680 // These intrinsics take an unsigned 2 bit immediate. 1681 case Mips::BI__builtin_msa_copy_s_w: 1682 case Mips::BI__builtin_msa_copy_u_w: 1683 case Mips::BI__builtin_msa_insve_w: 1684 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1685 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1686 // These intrinsics take an unsigned 1 bit immediate. 1687 case Mips::BI__builtin_msa_copy_s_d: 1688 case Mips::BI__builtin_msa_copy_u_d: 1689 case Mips::BI__builtin_msa_insve_d: 1690 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1691 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1692 // Memory offsets and immediate loads. 1693 // These intrinsics take a signed 10 bit immediate. 1694 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 1695 case Mips::BI__builtin_msa_ldi_h: 1696 case Mips::BI__builtin_msa_ldi_w: 1697 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1698 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1699 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1700 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1701 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1702 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1703 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1704 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1705 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1706 } 1707 1708 if (!m) 1709 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1710 1711 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1712 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1713 } 1714 1715 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1716 unsigned i = 0, l = 0, u = 0; 1717 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1718 BuiltinID == PPC::BI__builtin_divdeu || 1719 BuiltinID == PPC::BI__builtin_bpermd; 1720 bool IsTarget64Bit = Context.getTargetInfo() 1721 .getTypeWidth(Context 1722 .getTargetInfo() 1723 .getIntPtrType()) == 64; 1724 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1725 BuiltinID == PPC::BI__builtin_divweu || 1726 BuiltinID == PPC::BI__builtin_divde || 1727 BuiltinID == PPC::BI__builtin_divdeu; 1728 1729 if (Is64BitBltin && !IsTarget64Bit) 1730 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1731 << TheCall->getSourceRange(); 1732 1733 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1734 (BuiltinID == PPC::BI__builtin_bpermd && 1735 !Context.getTargetInfo().hasFeature("bpermd"))) 1736 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1737 << TheCall->getSourceRange(); 1738 1739 switch (BuiltinID) { 1740 default: return false; 1741 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1742 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1743 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1744 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1745 case PPC::BI__builtin_tbegin: 1746 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1747 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1748 case PPC::BI__builtin_tabortwc: 1749 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1750 case PPC::BI__builtin_tabortwci: 1751 case PPC::BI__builtin_tabortdci: 1752 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1753 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1754 case PPC::BI__builtin_vsx_xxpermdi: 1755 case PPC::BI__builtin_vsx_xxsldwi: 1756 return SemaBuiltinVSX(TheCall); 1757 } 1758 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1759 } 1760 1761 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1762 CallExpr *TheCall) { 1763 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1764 Expr *Arg = TheCall->getArg(0); 1765 llvm::APSInt AbortCode(32); 1766 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1767 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1768 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1769 << Arg->getSourceRange(); 1770 } 1771 1772 // For intrinsics which take an immediate value as part of the instruction, 1773 // range check them here. 1774 unsigned i = 0, l = 0, u = 0; 1775 switch (BuiltinID) { 1776 default: return false; 1777 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1778 case SystemZ::BI__builtin_s390_verimb: 1779 case SystemZ::BI__builtin_s390_verimh: 1780 case SystemZ::BI__builtin_s390_verimf: 1781 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1782 case SystemZ::BI__builtin_s390_vfaeb: 1783 case SystemZ::BI__builtin_s390_vfaeh: 1784 case SystemZ::BI__builtin_s390_vfaef: 1785 case SystemZ::BI__builtin_s390_vfaebs: 1786 case SystemZ::BI__builtin_s390_vfaehs: 1787 case SystemZ::BI__builtin_s390_vfaefs: 1788 case SystemZ::BI__builtin_s390_vfaezb: 1789 case SystemZ::BI__builtin_s390_vfaezh: 1790 case SystemZ::BI__builtin_s390_vfaezf: 1791 case SystemZ::BI__builtin_s390_vfaezbs: 1792 case SystemZ::BI__builtin_s390_vfaezhs: 1793 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1794 case SystemZ::BI__builtin_s390_vfisb: 1795 case SystemZ::BI__builtin_s390_vfidb: 1796 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1797 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1798 case SystemZ::BI__builtin_s390_vftcisb: 1799 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1800 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1801 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1802 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1803 case SystemZ::BI__builtin_s390_vstrcb: 1804 case SystemZ::BI__builtin_s390_vstrch: 1805 case SystemZ::BI__builtin_s390_vstrcf: 1806 case SystemZ::BI__builtin_s390_vstrczb: 1807 case SystemZ::BI__builtin_s390_vstrczh: 1808 case SystemZ::BI__builtin_s390_vstrczf: 1809 case SystemZ::BI__builtin_s390_vstrcbs: 1810 case SystemZ::BI__builtin_s390_vstrchs: 1811 case SystemZ::BI__builtin_s390_vstrcfs: 1812 case SystemZ::BI__builtin_s390_vstrczbs: 1813 case SystemZ::BI__builtin_s390_vstrczhs: 1814 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1815 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 1816 case SystemZ::BI__builtin_s390_vfminsb: 1817 case SystemZ::BI__builtin_s390_vfmaxsb: 1818 case SystemZ::BI__builtin_s390_vfmindb: 1819 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 1820 } 1821 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1822 } 1823 1824 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1825 /// This checks that the target supports __builtin_cpu_supports and 1826 /// that the string argument is constant and valid. 1827 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1828 Expr *Arg = TheCall->getArg(0); 1829 1830 // Check if the argument is a string literal. 1831 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1832 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1833 << Arg->getSourceRange(); 1834 1835 // Check the contents of the string. 1836 StringRef Feature = 1837 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1838 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1839 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1840 << Arg->getSourceRange(); 1841 return false; 1842 } 1843 1844 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 1845 /// This checks that the target supports __builtin_cpu_is and 1846 /// that the string argument is constant and valid. 1847 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 1848 Expr *Arg = TheCall->getArg(0); 1849 1850 // Check if the argument is a string literal. 1851 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1852 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1853 << Arg->getSourceRange(); 1854 1855 // Check the contents of the string. 1856 StringRef Feature = 1857 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1858 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 1859 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is) 1860 << Arg->getSourceRange(); 1861 return false; 1862 } 1863 1864 // Check if the rounding mode is legal. 1865 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1866 // Indicates if this instruction has rounding control or just SAE. 1867 bool HasRC = false; 1868 1869 unsigned ArgNum = 0; 1870 switch (BuiltinID) { 1871 default: 1872 return false; 1873 case X86::BI__builtin_ia32_vcvttsd2si32: 1874 case X86::BI__builtin_ia32_vcvttsd2si64: 1875 case X86::BI__builtin_ia32_vcvttsd2usi32: 1876 case X86::BI__builtin_ia32_vcvttsd2usi64: 1877 case X86::BI__builtin_ia32_vcvttss2si32: 1878 case X86::BI__builtin_ia32_vcvttss2si64: 1879 case X86::BI__builtin_ia32_vcvttss2usi32: 1880 case X86::BI__builtin_ia32_vcvttss2usi64: 1881 ArgNum = 1; 1882 break; 1883 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1884 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1885 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1886 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1887 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1888 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1889 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1890 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1891 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1892 case X86::BI__builtin_ia32_exp2pd_mask: 1893 case X86::BI__builtin_ia32_exp2ps_mask: 1894 case X86::BI__builtin_ia32_getexppd512_mask: 1895 case X86::BI__builtin_ia32_getexpps512_mask: 1896 case X86::BI__builtin_ia32_rcp28pd_mask: 1897 case X86::BI__builtin_ia32_rcp28ps_mask: 1898 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1899 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1900 case X86::BI__builtin_ia32_vcomisd: 1901 case X86::BI__builtin_ia32_vcomiss: 1902 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1903 ArgNum = 3; 1904 break; 1905 case X86::BI__builtin_ia32_cmppd512_mask: 1906 case X86::BI__builtin_ia32_cmpps512_mask: 1907 case X86::BI__builtin_ia32_cmpsd_mask: 1908 case X86::BI__builtin_ia32_cmpss_mask: 1909 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1910 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1911 case X86::BI__builtin_ia32_getexpss128_round_mask: 1912 case X86::BI__builtin_ia32_maxpd512_mask: 1913 case X86::BI__builtin_ia32_maxps512_mask: 1914 case X86::BI__builtin_ia32_maxsd_round_mask: 1915 case X86::BI__builtin_ia32_maxss_round_mask: 1916 case X86::BI__builtin_ia32_minpd512_mask: 1917 case X86::BI__builtin_ia32_minps512_mask: 1918 case X86::BI__builtin_ia32_minsd_round_mask: 1919 case X86::BI__builtin_ia32_minss_round_mask: 1920 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1921 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1922 case X86::BI__builtin_ia32_reducepd512_mask: 1923 case X86::BI__builtin_ia32_reduceps512_mask: 1924 case X86::BI__builtin_ia32_rndscalepd_mask: 1925 case X86::BI__builtin_ia32_rndscaleps_mask: 1926 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1927 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1928 ArgNum = 4; 1929 break; 1930 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1931 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1932 case X86::BI__builtin_ia32_fixupimmps512_mask: 1933 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1934 case X86::BI__builtin_ia32_fixupimmsd_mask: 1935 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1936 case X86::BI__builtin_ia32_fixupimmss_mask: 1937 case X86::BI__builtin_ia32_fixupimmss_maskz: 1938 case X86::BI__builtin_ia32_rangepd512_mask: 1939 case X86::BI__builtin_ia32_rangeps512_mask: 1940 case X86::BI__builtin_ia32_rangesd128_round_mask: 1941 case X86::BI__builtin_ia32_rangess128_round_mask: 1942 case X86::BI__builtin_ia32_reducesd_mask: 1943 case X86::BI__builtin_ia32_reducess_mask: 1944 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1945 case X86::BI__builtin_ia32_rndscaless_round_mask: 1946 ArgNum = 5; 1947 break; 1948 case X86::BI__builtin_ia32_vcvtsd2si64: 1949 case X86::BI__builtin_ia32_vcvtsd2si32: 1950 case X86::BI__builtin_ia32_vcvtsd2usi32: 1951 case X86::BI__builtin_ia32_vcvtsd2usi64: 1952 case X86::BI__builtin_ia32_vcvtss2si32: 1953 case X86::BI__builtin_ia32_vcvtss2si64: 1954 case X86::BI__builtin_ia32_vcvtss2usi32: 1955 case X86::BI__builtin_ia32_vcvtss2usi64: 1956 ArgNum = 1; 1957 HasRC = true; 1958 break; 1959 case X86::BI__builtin_ia32_cvtsi2sd64: 1960 case X86::BI__builtin_ia32_cvtsi2ss32: 1961 case X86::BI__builtin_ia32_cvtsi2ss64: 1962 case X86::BI__builtin_ia32_cvtusi2sd64: 1963 case X86::BI__builtin_ia32_cvtusi2ss32: 1964 case X86::BI__builtin_ia32_cvtusi2ss64: 1965 ArgNum = 2; 1966 HasRC = true; 1967 break; 1968 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1969 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1970 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1971 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1972 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1973 case X86::BI__builtin_ia32_cvtps2qq512_mask: 1974 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 1975 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 1976 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 1977 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 1978 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 1979 case X86::BI__builtin_ia32_sqrtpd512_mask: 1980 case X86::BI__builtin_ia32_sqrtps512_mask: 1981 ArgNum = 3; 1982 HasRC = true; 1983 break; 1984 case X86::BI__builtin_ia32_addpd512_mask: 1985 case X86::BI__builtin_ia32_addps512_mask: 1986 case X86::BI__builtin_ia32_divpd512_mask: 1987 case X86::BI__builtin_ia32_divps512_mask: 1988 case X86::BI__builtin_ia32_mulpd512_mask: 1989 case X86::BI__builtin_ia32_mulps512_mask: 1990 case X86::BI__builtin_ia32_subpd512_mask: 1991 case X86::BI__builtin_ia32_subps512_mask: 1992 case X86::BI__builtin_ia32_addss_round_mask: 1993 case X86::BI__builtin_ia32_addsd_round_mask: 1994 case X86::BI__builtin_ia32_divss_round_mask: 1995 case X86::BI__builtin_ia32_divsd_round_mask: 1996 case X86::BI__builtin_ia32_mulss_round_mask: 1997 case X86::BI__builtin_ia32_mulsd_round_mask: 1998 case X86::BI__builtin_ia32_subss_round_mask: 1999 case X86::BI__builtin_ia32_subsd_round_mask: 2000 case X86::BI__builtin_ia32_scalefpd512_mask: 2001 case X86::BI__builtin_ia32_scalefps512_mask: 2002 case X86::BI__builtin_ia32_scalefsd_round_mask: 2003 case X86::BI__builtin_ia32_scalefss_round_mask: 2004 case X86::BI__builtin_ia32_getmantpd512_mask: 2005 case X86::BI__builtin_ia32_getmantps512_mask: 2006 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 2007 case X86::BI__builtin_ia32_sqrtsd_round_mask: 2008 case X86::BI__builtin_ia32_sqrtss_round_mask: 2009 case X86::BI__builtin_ia32_vfmaddpd512_mask: 2010 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 2011 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 2012 case X86::BI__builtin_ia32_vfmaddps512_mask: 2013 case X86::BI__builtin_ia32_vfmaddps512_mask3: 2014 case X86::BI__builtin_ia32_vfmaddps512_maskz: 2015 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 2016 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 2017 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 2018 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 2019 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2020 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2021 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2022 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2023 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2024 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2025 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 2026 case X86::BI__builtin_ia32_vfnmaddps512_mask: 2027 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 2028 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 2029 case X86::BI__builtin_ia32_vfnmsubps512_mask: 2030 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 2031 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2032 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2033 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2034 case X86::BI__builtin_ia32_vfmaddss3_mask: 2035 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2036 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2037 ArgNum = 4; 2038 HasRC = true; 2039 break; 2040 case X86::BI__builtin_ia32_getmantsd_round_mask: 2041 case X86::BI__builtin_ia32_getmantss_round_mask: 2042 ArgNum = 5; 2043 HasRC = true; 2044 break; 2045 } 2046 2047 llvm::APSInt Result; 2048 2049 // We can't check the value of a dependent argument. 2050 Expr *Arg = TheCall->getArg(ArgNum); 2051 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2052 return false; 2053 2054 // Check constant-ness first. 2055 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2056 return true; 2057 2058 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2059 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2060 // combined with ROUND_NO_EXC. 2061 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2062 Result == 8/*ROUND_NO_EXC*/ || 2063 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2064 return false; 2065 2066 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2067 << Arg->getSourceRange(); 2068 } 2069 2070 // Check if the gather/scatter scale is legal. 2071 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2072 CallExpr *TheCall) { 2073 unsigned ArgNum = 0; 2074 switch (BuiltinID) { 2075 default: 2076 return false; 2077 case X86::BI__builtin_ia32_gatherpfdpd: 2078 case X86::BI__builtin_ia32_gatherpfdps: 2079 case X86::BI__builtin_ia32_gatherpfqpd: 2080 case X86::BI__builtin_ia32_gatherpfqps: 2081 case X86::BI__builtin_ia32_scatterpfdpd: 2082 case X86::BI__builtin_ia32_scatterpfdps: 2083 case X86::BI__builtin_ia32_scatterpfqpd: 2084 case X86::BI__builtin_ia32_scatterpfqps: 2085 ArgNum = 3; 2086 break; 2087 case X86::BI__builtin_ia32_gatherd_pd: 2088 case X86::BI__builtin_ia32_gatherd_pd256: 2089 case X86::BI__builtin_ia32_gatherq_pd: 2090 case X86::BI__builtin_ia32_gatherq_pd256: 2091 case X86::BI__builtin_ia32_gatherd_ps: 2092 case X86::BI__builtin_ia32_gatherd_ps256: 2093 case X86::BI__builtin_ia32_gatherq_ps: 2094 case X86::BI__builtin_ia32_gatherq_ps256: 2095 case X86::BI__builtin_ia32_gatherd_q: 2096 case X86::BI__builtin_ia32_gatherd_q256: 2097 case X86::BI__builtin_ia32_gatherq_q: 2098 case X86::BI__builtin_ia32_gatherq_q256: 2099 case X86::BI__builtin_ia32_gatherd_d: 2100 case X86::BI__builtin_ia32_gatherd_d256: 2101 case X86::BI__builtin_ia32_gatherq_d: 2102 case X86::BI__builtin_ia32_gatherq_d256: 2103 case X86::BI__builtin_ia32_gather3div2df: 2104 case X86::BI__builtin_ia32_gather3div2di: 2105 case X86::BI__builtin_ia32_gather3div4df: 2106 case X86::BI__builtin_ia32_gather3div4di: 2107 case X86::BI__builtin_ia32_gather3div4sf: 2108 case X86::BI__builtin_ia32_gather3div4si: 2109 case X86::BI__builtin_ia32_gather3div8sf: 2110 case X86::BI__builtin_ia32_gather3div8si: 2111 case X86::BI__builtin_ia32_gather3siv2df: 2112 case X86::BI__builtin_ia32_gather3siv2di: 2113 case X86::BI__builtin_ia32_gather3siv4df: 2114 case X86::BI__builtin_ia32_gather3siv4di: 2115 case X86::BI__builtin_ia32_gather3siv4sf: 2116 case X86::BI__builtin_ia32_gather3siv4si: 2117 case X86::BI__builtin_ia32_gather3siv8sf: 2118 case X86::BI__builtin_ia32_gather3siv8si: 2119 case X86::BI__builtin_ia32_gathersiv8df: 2120 case X86::BI__builtin_ia32_gathersiv16sf: 2121 case X86::BI__builtin_ia32_gatherdiv8df: 2122 case X86::BI__builtin_ia32_gatherdiv16sf: 2123 case X86::BI__builtin_ia32_gathersiv8di: 2124 case X86::BI__builtin_ia32_gathersiv16si: 2125 case X86::BI__builtin_ia32_gatherdiv8di: 2126 case X86::BI__builtin_ia32_gatherdiv16si: 2127 case X86::BI__builtin_ia32_scatterdiv2df: 2128 case X86::BI__builtin_ia32_scatterdiv2di: 2129 case X86::BI__builtin_ia32_scatterdiv4df: 2130 case X86::BI__builtin_ia32_scatterdiv4di: 2131 case X86::BI__builtin_ia32_scatterdiv4sf: 2132 case X86::BI__builtin_ia32_scatterdiv4si: 2133 case X86::BI__builtin_ia32_scatterdiv8sf: 2134 case X86::BI__builtin_ia32_scatterdiv8si: 2135 case X86::BI__builtin_ia32_scattersiv2df: 2136 case X86::BI__builtin_ia32_scattersiv2di: 2137 case X86::BI__builtin_ia32_scattersiv4df: 2138 case X86::BI__builtin_ia32_scattersiv4di: 2139 case X86::BI__builtin_ia32_scattersiv4sf: 2140 case X86::BI__builtin_ia32_scattersiv4si: 2141 case X86::BI__builtin_ia32_scattersiv8sf: 2142 case X86::BI__builtin_ia32_scattersiv8si: 2143 case X86::BI__builtin_ia32_scattersiv8df: 2144 case X86::BI__builtin_ia32_scattersiv16sf: 2145 case X86::BI__builtin_ia32_scatterdiv8df: 2146 case X86::BI__builtin_ia32_scatterdiv16sf: 2147 case X86::BI__builtin_ia32_scattersiv8di: 2148 case X86::BI__builtin_ia32_scattersiv16si: 2149 case X86::BI__builtin_ia32_scatterdiv8di: 2150 case X86::BI__builtin_ia32_scatterdiv16si: 2151 ArgNum = 4; 2152 break; 2153 } 2154 2155 llvm::APSInt Result; 2156 2157 // We can't check the value of a dependent argument. 2158 Expr *Arg = TheCall->getArg(ArgNum); 2159 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2160 return false; 2161 2162 // Check constant-ness first. 2163 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2164 return true; 2165 2166 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2167 return false; 2168 2169 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2170 << Arg->getSourceRange(); 2171 } 2172 2173 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2174 if (BuiltinID == X86::BI__builtin_cpu_supports) 2175 return SemaBuiltinCpuSupports(*this, TheCall); 2176 2177 if (BuiltinID == X86::BI__builtin_cpu_is) 2178 return SemaBuiltinCpuIs(*this, TheCall); 2179 2180 // If the intrinsic has rounding or SAE make sure its valid. 2181 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2182 return true; 2183 2184 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2185 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2186 return true; 2187 2188 // For intrinsics which take an immediate value as part of the instruction, 2189 // range check them here. 2190 int i = 0, l = 0, u = 0; 2191 switch (BuiltinID) { 2192 default: 2193 return false; 2194 case X86::BI_mm_prefetch: 2195 i = 1; l = 0; u = 3; 2196 break; 2197 case X86::BI__builtin_ia32_sha1rnds4: 2198 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2199 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2200 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2201 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2202 i = 2; l = 0; u = 3; 2203 break; 2204 case X86::BI__builtin_ia32_vpermil2pd: 2205 case X86::BI__builtin_ia32_vpermil2pd256: 2206 case X86::BI__builtin_ia32_vpermil2ps: 2207 case X86::BI__builtin_ia32_vpermil2ps256: 2208 i = 3; l = 0; u = 3; 2209 break; 2210 case X86::BI__builtin_ia32_cmpb128_mask: 2211 case X86::BI__builtin_ia32_cmpw128_mask: 2212 case X86::BI__builtin_ia32_cmpd128_mask: 2213 case X86::BI__builtin_ia32_cmpq128_mask: 2214 case X86::BI__builtin_ia32_cmpb256_mask: 2215 case X86::BI__builtin_ia32_cmpw256_mask: 2216 case X86::BI__builtin_ia32_cmpd256_mask: 2217 case X86::BI__builtin_ia32_cmpq256_mask: 2218 case X86::BI__builtin_ia32_cmpb512_mask: 2219 case X86::BI__builtin_ia32_cmpw512_mask: 2220 case X86::BI__builtin_ia32_cmpd512_mask: 2221 case X86::BI__builtin_ia32_cmpq512_mask: 2222 case X86::BI__builtin_ia32_ucmpb128_mask: 2223 case X86::BI__builtin_ia32_ucmpw128_mask: 2224 case X86::BI__builtin_ia32_ucmpd128_mask: 2225 case X86::BI__builtin_ia32_ucmpq128_mask: 2226 case X86::BI__builtin_ia32_ucmpb256_mask: 2227 case X86::BI__builtin_ia32_ucmpw256_mask: 2228 case X86::BI__builtin_ia32_ucmpd256_mask: 2229 case X86::BI__builtin_ia32_ucmpq256_mask: 2230 case X86::BI__builtin_ia32_ucmpb512_mask: 2231 case X86::BI__builtin_ia32_ucmpw512_mask: 2232 case X86::BI__builtin_ia32_ucmpd512_mask: 2233 case X86::BI__builtin_ia32_ucmpq512_mask: 2234 case X86::BI__builtin_ia32_vpcomub: 2235 case X86::BI__builtin_ia32_vpcomuw: 2236 case X86::BI__builtin_ia32_vpcomud: 2237 case X86::BI__builtin_ia32_vpcomuq: 2238 case X86::BI__builtin_ia32_vpcomb: 2239 case X86::BI__builtin_ia32_vpcomw: 2240 case X86::BI__builtin_ia32_vpcomd: 2241 case X86::BI__builtin_ia32_vpcomq: 2242 i = 2; l = 0; u = 7; 2243 break; 2244 case X86::BI__builtin_ia32_roundps: 2245 case X86::BI__builtin_ia32_roundpd: 2246 case X86::BI__builtin_ia32_roundps256: 2247 case X86::BI__builtin_ia32_roundpd256: 2248 i = 1; l = 0; u = 15; 2249 break; 2250 case X86::BI__builtin_ia32_roundss: 2251 case X86::BI__builtin_ia32_roundsd: 2252 case X86::BI__builtin_ia32_rangepd128_mask: 2253 case X86::BI__builtin_ia32_rangepd256_mask: 2254 case X86::BI__builtin_ia32_rangepd512_mask: 2255 case X86::BI__builtin_ia32_rangeps128_mask: 2256 case X86::BI__builtin_ia32_rangeps256_mask: 2257 case X86::BI__builtin_ia32_rangeps512_mask: 2258 case X86::BI__builtin_ia32_getmantsd_round_mask: 2259 case X86::BI__builtin_ia32_getmantss_round_mask: 2260 i = 2; l = 0; u = 15; 2261 break; 2262 case X86::BI__builtin_ia32_cmpps: 2263 case X86::BI__builtin_ia32_cmpss: 2264 case X86::BI__builtin_ia32_cmppd: 2265 case X86::BI__builtin_ia32_cmpsd: 2266 case X86::BI__builtin_ia32_cmpps256: 2267 case X86::BI__builtin_ia32_cmppd256: 2268 case X86::BI__builtin_ia32_cmpps128_mask: 2269 case X86::BI__builtin_ia32_cmppd128_mask: 2270 case X86::BI__builtin_ia32_cmpps256_mask: 2271 case X86::BI__builtin_ia32_cmppd256_mask: 2272 case X86::BI__builtin_ia32_cmpps512_mask: 2273 case X86::BI__builtin_ia32_cmppd512_mask: 2274 case X86::BI__builtin_ia32_cmpsd_mask: 2275 case X86::BI__builtin_ia32_cmpss_mask: 2276 i = 2; l = 0; u = 31; 2277 break; 2278 case X86::BI__builtin_ia32_xabort: 2279 i = 0; l = -128; u = 255; 2280 break; 2281 case X86::BI__builtin_ia32_pshufw: 2282 case X86::BI__builtin_ia32_aeskeygenassist128: 2283 i = 1; l = -128; u = 255; 2284 break; 2285 case X86::BI__builtin_ia32_vcvtps2ph: 2286 case X86::BI__builtin_ia32_vcvtps2ph256: 2287 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2288 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2289 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2290 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2291 case X86::BI__builtin_ia32_rndscaleps_mask: 2292 case X86::BI__builtin_ia32_rndscalepd_mask: 2293 case X86::BI__builtin_ia32_reducepd128_mask: 2294 case X86::BI__builtin_ia32_reducepd256_mask: 2295 case X86::BI__builtin_ia32_reducepd512_mask: 2296 case X86::BI__builtin_ia32_reduceps128_mask: 2297 case X86::BI__builtin_ia32_reduceps256_mask: 2298 case X86::BI__builtin_ia32_reduceps512_mask: 2299 case X86::BI__builtin_ia32_prold512_mask: 2300 case X86::BI__builtin_ia32_prolq512_mask: 2301 case X86::BI__builtin_ia32_prold128_mask: 2302 case X86::BI__builtin_ia32_prold256_mask: 2303 case X86::BI__builtin_ia32_prolq128_mask: 2304 case X86::BI__builtin_ia32_prolq256_mask: 2305 case X86::BI__builtin_ia32_prord128_mask: 2306 case X86::BI__builtin_ia32_prord256_mask: 2307 case X86::BI__builtin_ia32_prorq128_mask: 2308 case X86::BI__builtin_ia32_prorq256_mask: 2309 case X86::BI__builtin_ia32_fpclasspd128_mask: 2310 case X86::BI__builtin_ia32_fpclasspd256_mask: 2311 case X86::BI__builtin_ia32_fpclassps128_mask: 2312 case X86::BI__builtin_ia32_fpclassps256_mask: 2313 case X86::BI__builtin_ia32_fpclassps512_mask: 2314 case X86::BI__builtin_ia32_fpclasspd512_mask: 2315 case X86::BI__builtin_ia32_fpclasssd_mask: 2316 case X86::BI__builtin_ia32_fpclassss_mask: 2317 i = 1; l = 0; u = 255; 2318 break; 2319 case X86::BI__builtin_ia32_palignr: 2320 case X86::BI__builtin_ia32_insertps128: 2321 case X86::BI__builtin_ia32_dpps: 2322 case X86::BI__builtin_ia32_dppd: 2323 case X86::BI__builtin_ia32_dpps256: 2324 case X86::BI__builtin_ia32_mpsadbw128: 2325 case X86::BI__builtin_ia32_mpsadbw256: 2326 case X86::BI__builtin_ia32_pcmpistrm128: 2327 case X86::BI__builtin_ia32_pcmpistri128: 2328 case X86::BI__builtin_ia32_pcmpistria128: 2329 case X86::BI__builtin_ia32_pcmpistric128: 2330 case X86::BI__builtin_ia32_pcmpistrio128: 2331 case X86::BI__builtin_ia32_pcmpistris128: 2332 case X86::BI__builtin_ia32_pcmpistriz128: 2333 case X86::BI__builtin_ia32_pclmulqdq128: 2334 case X86::BI__builtin_ia32_vperm2f128_pd256: 2335 case X86::BI__builtin_ia32_vperm2f128_ps256: 2336 case X86::BI__builtin_ia32_vperm2f128_si256: 2337 case X86::BI__builtin_ia32_permti256: 2338 i = 2; l = -128; u = 255; 2339 break; 2340 case X86::BI__builtin_ia32_palignr128: 2341 case X86::BI__builtin_ia32_palignr256: 2342 case X86::BI__builtin_ia32_palignr512_mask: 2343 case X86::BI__builtin_ia32_vcomisd: 2344 case X86::BI__builtin_ia32_vcomiss: 2345 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2346 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2347 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2348 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2349 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2350 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2351 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2352 i = 2; l = 0; u = 255; 2353 break; 2354 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2355 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2356 case X86::BI__builtin_ia32_fixupimmps512_mask: 2357 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2358 case X86::BI__builtin_ia32_fixupimmsd_mask: 2359 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2360 case X86::BI__builtin_ia32_fixupimmss_mask: 2361 case X86::BI__builtin_ia32_fixupimmss_maskz: 2362 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2363 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2364 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2365 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2366 case X86::BI__builtin_ia32_fixupimmps128_mask: 2367 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2368 case X86::BI__builtin_ia32_fixupimmps256_mask: 2369 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2370 case X86::BI__builtin_ia32_pternlogd512_mask: 2371 case X86::BI__builtin_ia32_pternlogd512_maskz: 2372 case X86::BI__builtin_ia32_pternlogq512_mask: 2373 case X86::BI__builtin_ia32_pternlogq512_maskz: 2374 case X86::BI__builtin_ia32_pternlogd128_mask: 2375 case X86::BI__builtin_ia32_pternlogd128_maskz: 2376 case X86::BI__builtin_ia32_pternlogd256_mask: 2377 case X86::BI__builtin_ia32_pternlogd256_maskz: 2378 case X86::BI__builtin_ia32_pternlogq128_mask: 2379 case X86::BI__builtin_ia32_pternlogq128_maskz: 2380 case X86::BI__builtin_ia32_pternlogq256_mask: 2381 case X86::BI__builtin_ia32_pternlogq256_maskz: 2382 i = 3; l = 0; u = 255; 2383 break; 2384 case X86::BI__builtin_ia32_gatherpfdpd: 2385 case X86::BI__builtin_ia32_gatherpfdps: 2386 case X86::BI__builtin_ia32_gatherpfqpd: 2387 case X86::BI__builtin_ia32_gatherpfqps: 2388 case X86::BI__builtin_ia32_scatterpfdpd: 2389 case X86::BI__builtin_ia32_scatterpfdps: 2390 case X86::BI__builtin_ia32_scatterpfqpd: 2391 case X86::BI__builtin_ia32_scatterpfqps: 2392 i = 4; l = 2; u = 3; 2393 break; 2394 case X86::BI__builtin_ia32_pcmpestrm128: 2395 case X86::BI__builtin_ia32_pcmpestri128: 2396 case X86::BI__builtin_ia32_pcmpestria128: 2397 case X86::BI__builtin_ia32_pcmpestric128: 2398 case X86::BI__builtin_ia32_pcmpestrio128: 2399 case X86::BI__builtin_ia32_pcmpestris128: 2400 case X86::BI__builtin_ia32_pcmpestriz128: 2401 i = 4; l = -128; u = 255; 2402 break; 2403 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2404 case X86::BI__builtin_ia32_rndscaless_round_mask: 2405 i = 4; l = 0; u = 255; 2406 break; 2407 } 2408 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2409 } 2410 2411 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2412 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2413 /// Returns true when the format fits the function and the FormatStringInfo has 2414 /// been populated. 2415 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2416 FormatStringInfo *FSI) { 2417 FSI->HasVAListArg = Format->getFirstArg() == 0; 2418 FSI->FormatIdx = Format->getFormatIdx() - 1; 2419 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2420 2421 // The way the format attribute works in GCC, the implicit this argument 2422 // of member functions is counted. However, it doesn't appear in our own 2423 // lists, so decrement format_idx in that case. 2424 if (IsCXXMember) { 2425 if(FSI->FormatIdx == 0) 2426 return false; 2427 --FSI->FormatIdx; 2428 if (FSI->FirstDataArg != 0) 2429 --FSI->FirstDataArg; 2430 } 2431 return true; 2432 } 2433 2434 /// Checks if a the given expression evaluates to null. 2435 /// 2436 /// \brief Returns true if the value evaluates to null. 2437 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2438 // If the expression has non-null type, it doesn't evaluate to null. 2439 if (auto nullability 2440 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2441 if (*nullability == NullabilityKind::NonNull) 2442 return false; 2443 } 2444 2445 // As a special case, transparent unions initialized with zero are 2446 // considered null for the purposes of the nonnull attribute. 2447 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2448 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2449 if (const CompoundLiteralExpr *CLE = 2450 dyn_cast<CompoundLiteralExpr>(Expr)) 2451 if (const InitListExpr *ILE = 2452 dyn_cast<InitListExpr>(CLE->getInitializer())) 2453 Expr = ILE->getInit(0); 2454 } 2455 2456 bool Result; 2457 return (!Expr->isValueDependent() && 2458 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2459 !Result); 2460 } 2461 2462 static void CheckNonNullArgument(Sema &S, 2463 const Expr *ArgExpr, 2464 SourceLocation CallSiteLoc) { 2465 if (CheckNonNullExpr(S, ArgExpr)) 2466 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2467 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2468 } 2469 2470 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2471 FormatStringInfo FSI; 2472 if ((GetFormatStringType(Format) == FST_NSString) && 2473 getFormatStringInfo(Format, false, &FSI)) { 2474 Idx = FSI.FormatIdx; 2475 return true; 2476 } 2477 return false; 2478 } 2479 /// \brief Diagnose use of %s directive in an NSString which is being passed 2480 /// as formatting string to formatting method. 2481 static void 2482 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2483 const NamedDecl *FDecl, 2484 Expr **Args, 2485 unsigned NumArgs) { 2486 unsigned Idx = 0; 2487 bool Format = false; 2488 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2489 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2490 Idx = 2; 2491 Format = true; 2492 } 2493 else 2494 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2495 if (S.GetFormatNSStringIdx(I, Idx)) { 2496 Format = true; 2497 break; 2498 } 2499 } 2500 if (!Format || NumArgs <= Idx) 2501 return; 2502 const Expr *FormatExpr = Args[Idx]; 2503 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2504 FormatExpr = CSCE->getSubExpr(); 2505 const StringLiteral *FormatString; 2506 if (const ObjCStringLiteral *OSL = 2507 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2508 FormatString = OSL->getString(); 2509 else 2510 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2511 if (!FormatString) 2512 return; 2513 if (S.FormatStringHasSArg(FormatString)) { 2514 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2515 << "%s" << 1 << 1; 2516 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2517 << FDecl->getDeclName(); 2518 } 2519 } 2520 2521 /// Determine whether the given type has a non-null nullability annotation. 2522 static bool isNonNullType(ASTContext &ctx, QualType type) { 2523 if (auto nullability = type->getNullability(ctx)) 2524 return *nullability == NullabilityKind::NonNull; 2525 2526 return false; 2527 } 2528 2529 static void CheckNonNullArguments(Sema &S, 2530 const NamedDecl *FDecl, 2531 const FunctionProtoType *Proto, 2532 ArrayRef<const Expr *> Args, 2533 SourceLocation CallSiteLoc) { 2534 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2535 2536 // Check the attributes attached to the method/function itself. 2537 llvm::SmallBitVector NonNullArgs; 2538 if (FDecl) { 2539 // Handle the nonnull attribute on the function/method declaration itself. 2540 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2541 if (!NonNull->args_size()) { 2542 // Easy case: all pointer arguments are nonnull. 2543 for (const auto *Arg : Args) 2544 if (S.isValidPointerAttrType(Arg->getType())) 2545 CheckNonNullArgument(S, Arg, CallSiteLoc); 2546 return; 2547 } 2548 2549 for (unsigned Val : NonNull->args()) { 2550 if (Val >= Args.size()) 2551 continue; 2552 if (NonNullArgs.empty()) 2553 NonNullArgs.resize(Args.size()); 2554 NonNullArgs.set(Val); 2555 } 2556 } 2557 } 2558 2559 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2560 // Handle the nonnull attribute on the parameters of the 2561 // function/method. 2562 ArrayRef<ParmVarDecl*> parms; 2563 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2564 parms = FD->parameters(); 2565 else 2566 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2567 2568 unsigned ParamIndex = 0; 2569 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2570 I != E; ++I, ++ParamIndex) { 2571 const ParmVarDecl *PVD = *I; 2572 if (PVD->hasAttr<NonNullAttr>() || 2573 isNonNullType(S.Context, PVD->getType())) { 2574 if (NonNullArgs.empty()) 2575 NonNullArgs.resize(Args.size()); 2576 2577 NonNullArgs.set(ParamIndex); 2578 } 2579 } 2580 } else { 2581 // If we have a non-function, non-method declaration but no 2582 // function prototype, try to dig out the function prototype. 2583 if (!Proto) { 2584 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2585 QualType type = VD->getType().getNonReferenceType(); 2586 if (auto pointerType = type->getAs<PointerType>()) 2587 type = pointerType->getPointeeType(); 2588 else if (auto blockType = type->getAs<BlockPointerType>()) 2589 type = blockType->getPointeeType(); 2590 // FIXME: data member pointers? 2591 2592 // Dig out the function prototype, if there is one. 2593 Proto = type->getAs<FunctionProtoType>(); 2594 } 2595 } 2596 2597 // Fill in non-null argument information from the nullability 2598 // information on the parameter types (if we have them). 2599 if (Proto) { 2600 unsigned Index = 0; 2601 for (auto paramType : Proto->getParamTypes()) { 2602 if (isNonNullType(S.Context, paramType)) { 2603 if (NonNullArgs.empty()) 2604 NonNullArgs.resize(Args.size()); 2605 2606 NonNullArgs.set(Index); 2607 } 2608 2609 ++Index; 2610 } 2611 } 2612 } 2613 2614 // Check for non-null arguments. 2615 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2616 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2617 if (NonNullArgs[ArgIndex]) 2618 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2619 } 2620 } 2621 2622 /// Handles the checks for format strings, non-POD arguments to vararg 2623 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2624 /// attributes. 2625 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2626 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2627 bool IsMemberFunction, SourceLocation Loc, 2628 SourceRange Range, VariadicCallType CallType) { 2629 // FIXME: We should check as much as we can in the template definition. 2630 if (CurContext->isDependentContext()) 2631 return; 2632 2633 // Printf and scanf checking. 2634 llvm::SmallBitVector CheckedVarArgs; 2635 if (FDecl) { 2636 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2637 // Only create vector if there are format attributes. 2638 CheckedVarArgs.resize(Args.size()); 2639 2640 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2641 CheckedVarArgs); 2642 } 2643 } 2644 2645 // Refuse POD arguments that weren't caught by the format string 2646 // checks above. 2647 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2648 if (CallType != VariadicDoesNotApply && 2649 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2650 unsigned NumParams = Proto ? Proto->getNumParams() 2651 : FDecl && isa<FunctionDecl>(FDecl) 2652 ? cast<FunctionDecl>(FDecl)->getNumParams() 2653 : FDecl && isa<ObjCMethodDecl>(FDecl) 2654 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2655 : 0; 2656 2657 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2658 // Args[ArgIdx] can be null in malformed code. 2659 if (const Expr *Arg = Args[ArgIdx]) { 2660 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2661 checkVariadicArgument(Arg, CallType); 2662 } 2663 } 2664 } 2665 2666 if (FDecl || Proto) { 2667 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2668 2669 // Type safety checking. 2670 if (FDecl) { 2671 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2672 CheckArgumentWithTypeTag(I, Args.data()); 2673 } 2674 } 2675 2676 if (FD) 2677 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 2678 } 2679 2680 /// CheckConstructorCall - Check a constructor call for correctness and safety 2681 /// properties not enforced by the C type system. 2682 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2683 ArrayRef<const Expr *> Args, 2684 const FunctionProtoType *Proto, 2685 SourceLocation Loc) { 2686 VariadicCallType CallType = 2687 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2688 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 2689 Loc, SourceRange(), CallType); 2690 } 2691 2692 /// CheckFunctionCall - Check a direct function call for various correctness 2693 /// and safety properties not strictly enforced by the C type system. 2694 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2695 const FunctionProtoType *Proto) { 2696 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2697 isa<CXXMethodDecl>(FDecl); 2698 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2699 IsMemberOperatorCall; 2700 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2701 TheCall->getCallee()); 2702 Expr** Args = TheCall->getArgs(); 2703 unsigned NumArgs = TheCall->getNumArgs(); 2704 2705 Expr *ImplicitThis = nullptr; 2706 if (IsMemberOperatorCall) { 2707 // If this is a call to a member operator, hide the first argument 2708 // from checkCall. 2709 // FIXME: Our choice of AST representation here is less than ideal. 2710 ImplicitThis = Args[0]; 2711 ++Args; 2712 --NumArgs; 2713 } else if (IsMemberFunction) 2714 ImplicitThis = 2715 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 2716 2717 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 2718 IsMemberFunction, TheCall->getRParenLoc(), 2719 TheCall->getCallee()->getSourceRange(), CallType); 2720 2721 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2722 // None of the checks below are needed for functions that don't have 2723 // simple names (e.g., C++ conversion functions). 2724 if (!FnInfo) 2725 return false; 2726 2727 CheckAbsoluteValueFunction(TheCall, FDecl); 2728 CheckMaxUnsignedZero(TheCall, FDecl); 2729 2730 if (getLangOpts().ObjC1) 2731 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2732 2733 unsigned CMId = FDecl->getMemoryFunctionKind(); 2734 if (CMId == 0) 2735 return false; 2736 2737 // Handle memory setting and copying functions. 2738 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2739 CheckStrlcpycatArguments(TheCall, FnInfo); 2740 else if (CMId == Builtin::BIstrncat) 2741 CheckStrncatArguments(TheCall, FnInfo); 2742 else 2743 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2744 2745 return false; 2746 } 2747 2748 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2749 ArrayRef<const Expr *> Args) { 2750 VariadicCallType CallType = 2751 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2752 2753 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 2754 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2755 CallType); 2756 2757 return false; 2758 } 2759 2760 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2761 const FunctionProtoType *Proto) { 2762 QualType Ty; 2763 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2764 Ty = V->getType().getNonReferenceType(); 2765 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2766 Ty = F->getType().getNonReferenceType(); 2767 else 2768 return false; 2769 2770 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2771 !Ty->isFunctionProtoType()) 2772 return false; 2773 2774 VariadicCallType CallType; 2775 if (!Proto || !Proto->isVariadic()) { 2776 CallType = VariadicDoesNotApply; 2777 } else if (Ty->isBlockPointerType()) { 2778 CallType = VariadicBlock; 2779 } else { // Ty->isFunctionPointerType() 2780 CallType = VariadicFunction; 2781 } 2782 2783 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 2784 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2785 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2786 TheCall->getCallee()->getSourceRange(), CallType); 2787 2788 return false; 2789 } 2790 2791 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2792 /// such as function pointers returned from functions. 2793 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2794 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2795 TheCall->getCallee()); 2796 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 2797 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2798 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2799 TheCall->getCallee()->getSourceRange(), CallType); 2800 2801 return false; 2802 } 2803 2804 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2805 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2806 return false; 2807 2808 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2809 switch (Op) { 2810 case AtomicExpr::AO__c11_atomic_init: 2811 case AtomicExpr::AO__opencl_atomic_init: 2812 llvm_unreachable("There is no ordering argument for an init"); 2813 2814 case AtomicExpr::AO__c11_atomic_load: 2815 case AtomicExpr::AO__opencl_atomic_load: 2816 case AtomicExpr::AO__atomic_load_n: 2817 case AtomicExpr::AO__atomic_load: 2818 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2819 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2820 2821 case AtomicExpr::AO__c11_atomic_store: 2822 case AtomicExpr::AO__opencl_atomic_store: 2823 case AtomicExpr::AO__atomic_store: 2824 case AtomicExpr::AO__atomic_store_n: 2825 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2826 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2827 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2828 2829 default: 2830 return true; 2831 } 2832 } 2833 2834 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2835 AtomicExpr::AtomicOp Op) { 2836 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2837 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2838 2839 // All the non-OpenCL operations take one of the following forms. 2840 // The OpenCL operations take the __c11 forms with one extra argument for 2841 // synchronization scope. 2842 enum { 2843 // C __c11_atomic_init(A *, C) 2844 Init, 2845 // C __c11_atomic_load(A *, int) 2846 Load, 2847 // void __atomic_load(A *, CP, int) 2848 LoadCopy, 2849 // void __atomic_store(A *, CP, int) 2850 Copy, 2851 // C __c11_atomic_add(A *, M, int) 2852 Arithmetic, 2853 // C __atomic_exchange_n(A *, CP, int) 2854 Xchg, 2855 // void __atomic_exchange(A *, C *, CP, int) 2856 GNUXchg, 2857 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2858 C11CmpXchg, 2859 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2860 GNUCmpXchg 2861 } Form = Init; 2862 const unsigned NumForm = GNUCmpXchg + 1; 2863 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2864 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2865 // where: 2866 // C is an appropriate type, 2867 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2868 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2869 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2870 // the int parameters are for orderings. 2871 2872 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 2873 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 2874 "need to update code for modified forms"); 2875 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2876 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2877 AtomicExpr::AO__atomic_load, 2878 "need to update code for modified C11 atomics"); 2879 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 2880 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 2881 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 2882 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 2883 IsOpenCL; 2884 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2885 Op == AtomicExpr::AO__atomic_store_n || 2886 Op == AtomicExpr::AO__atomic_exchange_n || 2887 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2888 bool IsAddSub = false; 2889 2890 switch (Op) { 2891 case AtomicExpr::AO__c11_atomic_init: 2892 case AtomicExpr::AO__opencl_atomic_init: 2893 Form = Init; 2894 break; 2895 2896 case AtomicExpr::AO__c11_atomic_load: 2897 case AtomicExpr::AO__opencl_atomic_load: 2898 case AtomicExpr::AO__atomic_load_n: 2899 Form = Load; 2900 break; 2901 2902 case AtomicExpr::AO__atomic_load: 2903 Form = LoadCopy; 2904 break; 2905 2906 case AtomicExpr::AO__c11_atomic_store: 2907 case AtomicExpr::AO__opencl_atomic_store: 2908 case AtomicExpr::AO__atomic_store: 2909 case AtomicExpr::AO__atomic_store_n: 2910 Form = Copy; 2911 break; 2912 2913 case AtomicExpr::AO__c11_atomic_fetch_add: 2914 case AtomicExpr::AO__c11_atomic_fetch_sub: 2915 case AtomicExpr::AO__opencl_atomic_fetch_add: 2916 case AtomicExpr::AO__opencl_atomic_fetch_sub: 2917 case AtomicExpr::AO__opencl_atomic_fetch_min: 2918 case AtomicExpr::AO__opencl_atomic_fetch_max: 2919 case AtomicExpr::AO__atomic_fetch_add: 2920 case AtomicExpr::AO__atomic_fetch_sub: 2921 case AtomicExpr::AO__atomic_add_fetch: 2922 case AtomicExpr::AO__atomic_sub_fetch: 2923 IsAddSub = true; 2924 // Fall through. 2925 case AtomicExpr::AO__c11_atomic_fetch_and: 2926 case AtomicExpr::AO__c11_atomic_fetch_or: 2927 case AtomicExpr::AO__c11_atomic_fetch_xor: 2928 case AtomicExpr::AO__opencl_atomic_fetch_and: 2929 case AtomicExpr::AO__opencl_atomic_fetch_or: 2930 case AtomicExpr::AO__opencl_atomic_fetch_xor: 2931 case AtomicExpr::AO__atomic_fetch_and: 2932 case AtomicExpr::AO__atomic_fetch_or: 2933 case AtomicExpr::AO__atomic_fetch_xor: 2934 case AtomicExpr::AO__atomic_fetch_nand: 2935 case AtomicExpr::AO__atomic_and_fetch: 2936 case AtomicExpr::AO__atomic_or_fetch: 2937 case AtomicExpr::AO__atomic_xor_fetch: 2938 case AtomicExpr::AO__atomic_nand_fetch: 2939 Form = Arithmetic; 2940 break; 2941 2942 case AtomicExpr::AO__c11_atomic_exchange: 2943 case AtomicExpr::AO__opencl_atomic_exchange: 2944 case AtomicExpr::AO__atomic_exchange_n: 2945 Form = Xchg; 2946 break; 2947 2948 case AtomicExpr::AO__atomic_exchange: 2949 Form = GNUXchg; 2950 break; 2951 2952 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2953 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2954 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 2955 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 2956 Form = C11CmpXchg; 2957 break; 2958 2959 case AtomicExpr::AO__atomic_compare_exchange: 2960 case AtomicExpr::AO__atomic_compare_exchange_n: 2961 Form = GNUCmpXchg; 2962 break; 2963 } 2964 2965 unsigned AdjustedNumArgs = NumArgs[Form]; 2966 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 2967 ++AdjustedNumArgs; 2968 // Check we have the right number of arguments. 2969 if (TheCall->getNumArgs() < AdjustedNumArgs) { 2970 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2971 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 2972 << TheCall->getCallee()->getSourceRange(); 2973 return ExprError(); 2974 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 2975 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 2976 diag::err_typecheck_call_too_many_args) 2977 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 2978 << TheCall->getCallee()->getSourceRange(); 2979 return ExprError(); 2980 } 2981 2982 // Inspect the first argument of the atomic operation. 2983 Expr *Ptr = TheCall->getArg(0); 2984 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2985 if (ConvertedPtr.isInvalid()) 2986 return ExprError(); 2987 2988 Ptr = ConvertedPtr.get(); 2989 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2990 if (!pointerType) { 2991 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2992 << Ptr->getType() << Ptr->getSourceRange(); 2993 return ExprError(); 2994 } 2995 2996 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2997 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2998 QualType ValType = AtomTy; // 'C' 2999 if (IsC11) { 3000 if (!AtomTy->isAtomicType()) { 3001 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 3002 << Ptr->getType() << Ptr->getSourceRange(); 3003 return ExprError(); 3004 } 3005 if (AtomTy.isConstQualified() || 3006 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3007 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 3008 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3009 << Ptr->getSourceRange(); 3010 return ExprError(); 3011 } 3012 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 3013 } else if (Form != Load && Form != LoadCopy) { 3014 if (ValType.isConstQualified()) { 3015 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 3016 << Ptr->getType() << Ptr->getSourceRange(); 3017 return ExprError(); 3018 } 3019 } 3020 3021 // For an arithmetic operation, the implied arithmetic must be well-formed. 3022 if (Form == Arithmetic) { 3023 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3024 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 3025 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3026 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3027 return ExprError(); 3028 } 3029 if (!IsAddSub && !ValType->isIntegerType()) { 3030 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3031 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3032 return ExprError(); 3033 } 3034 if (IsC11 && ValType->isPointerType() && 3035 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3036 diag::err_incomplete_type)) { 3037 return ExprError(); 3038 } 3039 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3040 // For __atomic_*_n operations, the value type must be a scalar integral or 3041 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3042 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3043 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3044 return ExprError(); 3045 } 3046 3047 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3048 !AtomTy->isScalarType()) { 3049 // For GNU atomics, require a trivially-copyable type. This is not part of 3050 // the GNU atomics specification, but we enforce it for sanity. 3051 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3052 << Ptr->getType() << Ptr->getSourceRange(); 3053 return ExprError(); 3054 } 3055 3056 switch (ValType.getObjCLifetime()) { 3057 case Qualifiers::OCL_None: 3058 case Qualifiers::OCL_ExplicitNone: 3059 // okay 3060 break; 3061 3062 case Qualifiers::OCL_Weak: 3063 case Qualifiers::OCL_Strong: 3064 case Qualifiers::OCL_Autoreleasing: 3065 // FIXME: Can this happen? By this point, ValType should be known 3066 // to be trivially copyable. 3067 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3068 << ValType << Ptr->getSourceRange(); 3069 return ExprError(); 3070 } 3071 3072 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 3073 // volatile-ness of the pointee-type inject itself into the result or the 3074 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 3075 ValType.removeLocalVolatile(); 3076 ValType.removeLocalConst(); 3077 QualType ResultType = ValType; 3078 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3079 Form == Init) 3080 ResultType = Context.VoidTy; 3081 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3082 ResultType = Context.BoolTy; 3083 3084 // The type of a parameter passed 'by value'. In the GNU atomics, such 3085 // arguments are actually passed as pointers. 3086 QualType ByValType = ValType; // 'CP' 3087 if (!IsC11 && !IsN) 3088 ByValType = Ptr->getType(); 3089 3090 // The first argument --- the pointer --- has a fixed type; we 3091 // deduce the types of the rest of the arguments accordingly. Walk 3092 // the remaining arguments, converting them to the deduced value type. 3093 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) { 3094 QualType Ty; 3095 if (i < NumVals[Form] + 1) { 3096 switch (i) { 3097 case 1: 3098 // The second argument is the non-atomic operand. For arithmetic, this 3099 // is always passed by value, and for a compare_exchange it is always 3100 // passed by address. For the rest, GNU uses by-address and C11 uses 3101 // by-value. 3102 assert(Form != Load); 3103 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3104 Ty = ValType; 3105 else if (Form == Copy || Form == Xchg) 3106 Ty = ByValType; 3107 else if (Form == Arithmetic) 3108 Ty = Context.getPointerDiffType(); 3109 else { 3110 Expr *ValArg = TheCall->getArg(i); 3111 // Treat this argument as _Nonnull as we want to show a warning if 3112 // NULL is passed into it. 3113 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3114 unsigned AS = 0; 3115 // Keep address space of non-atomic pointer type. 3116 if (const PointerType *PtrTy = 3117 ValArg->getType()->getAs<PointerType>()) { 3118 AS = PtrTy->getPointeeType().getAddressSpace(); 3119 } 3120 Ty = Context.getPointerType( 3121 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3122 } 3123 break; 3124 case 2: 3125 // The third argument to compare_exchange / GNU exchange is a 3126 // (pointer to a) desired value. 3127 Ty = ByValType; 3128 break; 3129 case 3: 3130 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3131 Ty = Context.BoolTy; 3132 break; 3133 } 3134 } else { 3135 // The order(s) and scope are always converted to int. 3136 Ty = Context.IntTy; 3137 } 3138 3139 InitializedEntity Entity = 3140 InitializedEntity::InitializeParameter(Context, Ty, false); 3141 ExprResult Arg = TheCall->getArg(i); 3142 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3143 if (Arg.isInvalid()) 3144 return true; 3145 TheCall->setArg(i, Arg.get()); 3146 } 3147 3148 // Permute the arguments into a 'consistent' order. 3149 SmallVector<Expr*, 5> SubExprs; 3150 SubExprs.push_back(Ptr); 3151 switch (Form) { 3152 case Init: 3153 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3154 SubExprs.push_back(TheCall->getArg(1)); // Val1 3155 break; 3156 case Load: 3157 SubExprs.push_back(TheCall->getArg(1)); // Order 3158 break; 3159 case LoadCopy: 3160 case Copy: 3161 case Arithmetic: 3162 case Xchg: 3163 SubExprs.push_back(TheCall->getArg(2)); // Order 3164 SubExprs.push_back(TheCall->getArg(1)); // Val1 3165 break; 3166 case GNUXchg: 3167 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3168 SubExprs.push_back(TheCall->getArg(3)); // Order 3169 SubExprs.push_back(TheCall->getArg(1)); // Val1 3170 SubExprs.push_back(TheCall->getArg(2)); // Val2 3171 break; 3172 case C11CmpXchg: 3173 SubExprs.push_back(TheCall->getArg(3)); // Order 3174 SubExprs.push_back(TheCall->getArg(1)); // Val1 3175 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3176 SubExprs.push_back(TheCall->getArg(2)); // Val2 3177 break; 3178 case GNUCmpXchg: 3179 SubExprs.push_back(TheCall->getArg(4)); // Order 3180 SubExprs.push_back(TheCall->getArg(1)); // Val1 3181 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3182 SubExprs.push_back(TheCall->getArg(2)); // Val2 3183 SubExprs.push_back(TheCall->getArg(3)); // Weak 3184 break; 3185 } 3186 3187 if (SubExprs.size() >= 2 && Form != Init) { 3188 llvm::APSInt Result(32); 3189 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3190 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3191 Diag(SubExprs[1]->getLocStart(), 3192 diag::warn_atomic_op_has_invalid_memory_order) 3193 << SubExprs[1]->getSourceRange(); 3194 } 3195 3196 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 3197 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3198 llvm::APSInt Result(32); 3199 if (Scope->isIntegerConstantExpr(Result, Context) && 3200 !ScopeModel->isValid(Result.getZExtValue())) { 3201 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3202 << Scope->getSourceRange(); 3203 } 3204 SubExprs.push_back(Scope); 3205 } 3206 3207 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3208 SubExprs, ResultType, Op, 3209 TheCall->getRParenLoc()); 3210 3211 if ((Op == AtomicExpr::AO__c11_atomic_load || 3212 Op == AtomicExpr::AO__c11_atomic_store || 3213 Op == AtomicExpr::AO__opencl_atomic_load || 3214 Op == AtomicExpr::AO__opencl_atomic_store ) && 3215 Context.AtomicUsesUnsupportedLibcall(AE)) 3216 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3217 << ((Op == AtomicExpr::AO__c11_atomic_load || 3218 Op == AtomicExpr::AO__opencl_atomic_load) 3219 ? 0 : 1); 3220 3221 return AE; 3222 } 3223 3224 /// checkBuiltinArgument - Given a call to a builtin function, perform 3225 /// normal type-checking on the given argument, updating the call in 3226 /// place. This is useful when a builtin function requires custom 3227 /// type-checking for some of its arguments but not necessarily all of 3228 /// them. 3229 /// 3230 /// Returns true on error. 3231 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3232 FunctionDecl *Fn = E->getDirectCallee(); 3233 assert(Fn && "builtin call without direct callee!"); 3234 3235 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3236 InitializedEntity Entity = 3237 InitializedEntity::InitializeParameter(S.Context, Param); 3238 3239 ExprResult Arg = E->getArg(0); 3240 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3241 if (Arg.isInvalid()) 3242 return true; 3243 3244 E->setArg(ArgIndex, Arg.get()); 3245 return false; 3246 } 3247 3248 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3249 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3250 /// type of its first argument. The main ActOnCallExpr routines have already 3251 /// promoted the types of arguments because all of these calls are prototyped as 3252 /// void(...). 3253 /// 3254 /// This function goes through and does final semantic checking for these 3255 /// builtins, 3256 ExprResult 3257 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3258 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3259 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3260 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3261 3262 // Ensure that we have at least one argument to do type inference from. 3263 if (TheCall->getNumArgs() < 1) { 3264 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3265 << 0 << 1 << TheCall->getNumArgs() 3266 << TheCall->getCallee()->getSourceRange(); 3267 return ExprError(); 3268 } 3269 3270 // Inspect the first argument of the atomic builtin. This should always be 3271 // a pointer type, whose element is an integral scalar or pointer type. 3272 // Because it is a pointer type, we don't have to worry about any implicit 3273 // casts here. 3274 // FIXME: We don't allow floating point scalars as input. 3275 Expr *FirstArg = TheCall->getArg(0); 3276 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3277 if (FirstArgResult.isInvalid()) 3278 return ExprError(); 3279 FirstArg = FirstArgResult.get(); 3280 TheCall->setArg(0, FirstArg); 3281 3282 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3283 if (!pointerType) { 3284 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3285 << FirstArg->getType() << FirstArg->getSourceRange(); 3286 return ExprError(); 3287 } 3288 3289 QualType ValType = pointerType->getPointeeType(); 3290 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3291 !ValType->isBlockPointerType()) { 3292 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3293 << FirstArg->getType() << FirstArg->getSourceRange(); 3294 return ExprError(); 3295 } 3296 3297 switch (ValType.getObjCLifetime()) { 3298 case Qualifiers::OCL_None: 3299 case Qualifiers::OCL_ExplicitNone: 3300 // okay 3301 break; 3302 3303 case Qualifiers::OCL_Weak: 3304 case Qualifiers::OCL_Strong: 3305 case Qualifiers::OCL_Autoreleasing: 3306 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3307 << ValType << FirstArg->getSourceRange(); 3308 return ExprError(); 3309 } 3310 3311 // Strip any qualifiers off ValType. 3312 ValType = ValType.getUnqualifiedType(); 3313 3314 // The majority of builtins return a value, but a few have special return 3315 // types, so allow them to override appropriately below. 3316 QualType ResultType = ValType; 3317 3318 // We need to figure out which concrete builtin this maps onto. For example, 3319 // __sync_fetch_and_add with a 2 byte object turns into 3320 // __sync_fetch_and_add_2. 3321 #define BUILTIN_ROW(x) \ 3322 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3323 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3324 3325 static const unsigned BuiltinIndices[][5] = { 3326 BUILTIN_ROW(__sync_fetch_and_add), 3327 BUILTIN_ROW(__sync_fetch_and_sub), 3328 BUILTIN_ROW(__sync_fetch_and_or), 3329 BUILTIN_ROW(__sync_fetch_and_and), 3330 BUILTIN_ROW(__sync_fetch_and_xor), 3331 BUILTIN_ROW(__sync_fetch_and_nand), 3332 3333 BUILTIN_ROW(__sync_add_and_fetch), 3334 BUILTIN_ROW(__sync_sub_and_fetch), 3335 BUILTIN_ROW(__sync_and_and_fetch), 3336 BUILTIN_ROW(__sync_or_and_fetch), 3337 BUILTIN_ROW(__sync_xor_and_fetch), 3338 BUILTIN_ROW(__sync_nand_and_fetch), 3339 3340 BUILTIN_ROW(__sync_val_compare_and_swap), 3341 BUILTIN_ROW(__sync_bool_compare_and_swap), 3342 BUILTIN_ROW(__sync_lock_test_and_set), 3343 BUILTIN_ROW(__sync_lock_release), 3344 BUILTIN_ROW(__sync_swap) 3345 }; 3346 #undef BUILTIN_ROW 3347 3348 // Determine the index of the size. 3349 unsigned SizeIndex; 3350 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3351 case 1: SizeIndex = 0; break; 3352 case 2: SizeIndex = 1; break; 3353 case 4: SizeIndex = 2; break; 3354 case 8: SizeIndex = 3; break; 3355 case 16: SizeIndex = 4; break; 3356 default: 3357 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3358 << FirstArg->getType() << FirstArg->getSourceRange(); 3359 return ExprError(); 3360 } 3361 3362 // Each of these builtins has one pointer argument, followed by some number of 3363 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3364 // that we ignore. Find out which row of BuiltinIndices to read from as well 3365 // as the number of fixed args. 3366 unsigned BuiltinID = FDecl->getBuiltinID(); 3367 unsigned BuiltinIndex, NumFixed = 1; 3368 bool WarnAboutSemanticsChange = false; 3369 switch (BuiltinID) { 3370 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3371 case Builtin::BI__sync_fetch_and_add: 3372 case Builtin::BI__sync_fetch_and_add_1: 3373 case Builtin::BI__sync_fetch_and_add_2: 3374 case Builtin::BI__sync_fetch_and_add_4: 3375 case Builtin::BI__sync_fetch_and_add_8: 3376 case Builtin::BI__sync_fetch_and_add_16: 3377 BuiltinIndex = 0; 3378 break; 3379 3380 case Builtin::BI__sync_fetch_and_sub: 3381 case Builtin::BI__sync_fetch_and_sub_1: 3382 case Builtin::BI__sync_fetch_and_sub_2: 3383 case Builtin::BI__sync_fetch_and_sub_4: 3384 case Builtin::BI__sync_fetch_and_sub_8: 3385 case Builtin::BI__sync_fetch_and_sub_16: 3386 BuiltinIndex = 1; 3387 break; 3388 3389 case Builtin::BI__sync_fetch_and_or: 3390 case Builtin::BI__sync_fetch_and_or_1: 3391 case Builtin::BI__sync_fetch_and_or_2: 3392 case Builtin::BI__sync_fetch_and_or_4: 3393 case Builtin::BI__sync_fetch_and_or_8: 3394 case Builtin::BI__sync_fetch_and_or_16: 3395 BuiltinIndex = 2; 3396 break; 3397 3398 case Builtin::BI__sync_fetch_and_and: 3399 case Builtin::BI__sync_fetch_and_and_1: 3400 case Builtin::BI__sync_fetch_and_and_2: 3401 case Builtin::BI__sync_fetch_and_and_4: 3402 case Builtin::BI__sync_fetch_and_and_8: 3403 case Builtin::BI__sync_fetch_and_and_16: 3404 BuiltinIndex = 3; 3405 break; 3406 3407 case Builtin::BI__sync_fetch_and_xor: 3408 case Builtin::BI__sync_fetch_and_xor_1: 3409 case Builtin::BI__sync_fetch_and_xor_2: 3410 case Builtin::BI__sync_fetch_and_xor_4: 3411 case Builtin::BI__sync_fetch_and_xor_8: 3412 case Builtin::BI__sync_fetch_and_xor_16: 3413 BuiltinIndex = 4; 3414 break; 3415 3416 case Builtin::BI__sync_fetch_and_nand: 3417 case Builtin::BI__sync_fetch_and_nand_1: 3418 case Builtin::BI__sync_fetch_and_nand_2: 3419 case Builtin::BI__sync_fetch_and_nand_4: 3420 case Builtin::BI__sync_fetch_and_nand_8: 3421 case Builtin::BI__sync_fetch_and_nand_16: 3422 BuiltinIndex = 5; 3423 WarnAboutSemanticsChange = true; 3424 break; 3425 3426 case Builtin::BI__sync_add_and_fetch: 3427 case Builtin::BI__sync_add_and_fetch_1: 3428 case Builtin::BI__sync_add_and_fetch_2: 3429 case Builtin::BI__sync_add_and_fetch_4: 3430 case Builtin::BI__sync_add_and_fetch_8: 3431 case Builtin::BI__sync_add_and_fetch_16: 3432 BuiltinIndex = 6; 3433 break; 3434 3435 case Builtin::BI__sync_sub_and_fetch: 3436 case Builtin::BI__sync_sub_and_fetch_1: 3437 case Builtin::BI__sync_sub_and_fetch_2: 3438 case Builtin::BI__sync_sub_and_fetch_4: 3439 case Builtin::BI__sync_sub_and_fetch_8: 3440 case Builtin::BI__sync_sub_and_fetch_16: 3441 BuiltinIndex = 7; 3442 break; 3443 3444 case Builtin::BI__sync_and_and_fetch: 3445 case Builtin::BI__sync_and_and_fetch_1: 3446 case Builtin::BI__sync_and_and_fetch_2: 3447 case Builtin::BI__sync_and_and_fetch_4: 3448 case Builtin::BI__sync_and_and_fetch_8: 3449 case Builtin::BI__sync_and_and_fetch_16: 3450 BuiltinIndex = 8; 3451 break; 3452 3453 case Builtin::BI__sync_or_and_fetch: 3454 case Builtin::BI__sync_or_and_fetch_1: 3455 case Builtin::BI__sync_or_and_fetch_2: 3456 case Builtin::BI__sync_or_and_fetch_4: 3457 case Builtin::BI__sync_or_and_fetch_8: 3458 case Builtin::BI__sync_or_and_fetch_16: 3459 BuiltinIndex = 9; 3460 break; 3461 3462 case Builtin::BI__sync_xor_and_fetch: 3463 case Builtin::BI__sync_xor_and_fetch_1: 3464 case Builtin::BI__sync_xor_and_fetch_2: 3465 case Builtin::BI__sync_xor_and_fetch_4: 3466 case Builtin::BI__sync_xor_and_fetch_8: 3467 case Builtin::BI__sync_xor_and_fetch_16: 3468 BuiltinIndex = 10; 3469 break; 3470 3471 case Builtin::BI__sync_nand_and_fetch: 3472 case Builtin::BI__sync_nand_and_fetch_1: 3473 case Builtin::BI__sync_nand_and_fetch_2: 3474 case Builtin::BI__sync_nand_and_fetch_4: 3475 case Builtin::BI__sync_nand_and_fetch_8: 3476 case Builtin::BI__sync_nand_and_fetch_16: 3477 BuiltinIndex = 11; 3478 WarnAboutSemanticsChange = true; 3479 break; 3480 3481 case Builtin::BI__sync_val_compare_and_swap: 3482 case Builtin::BI__sync_val_compare_and_swap_1: 3483 case Builtin::BI__sync_val_compare_and_swap_2: 3484 case Builtin::BI__sync_val_compare_and_swap_4: 3485 case Builtin::BI__sync_val_compare_and_swap_8: 3486 case Builtin::BI__sync_val_compare_and_swap_16: 3487 BuiltinIndex = 12; 3488 NumFixed = 2; 3489 break; 3490 3491 case Builtin::BI__sync_bool_compare_and_swap: 3492 case Builtin::BI__sync_bool_compare_and_swap_1: 3493 case Builtin::BI__sync_bool_compare_and_swap_2: 3494 case Builtin::BI__sync_bool_compare_and_swap_4: 3495 case Builtin::BI__sync_bool_compare_and_swap_8: 3496 case Builtin::BI__sync_bool_compare_and_swap_16: 3497 BuiltinIndex = 13; 3498 NumFixed = 2; 3499 ResultType = Context.BoolTy; 3500 break; 3501 3502 case Builtin::BI__sync_lock_test_and_set: 3503 case Builtin::BI__sync_lock_test_and_set_1: 3504 case Builtin::BI__sync_lock_test_and_set_2: 3505 case Builtin::BI__sync_lock_test_and_set_4: 3506 case Builtin::BI__sync_lock_test_and_set_8: 3507 case Builtin::BI__sync_lock_test_and_set_16: 3508 BuiltinIndex = 14; 3509 break; 3510 3511 case Builtin::BI__sync_lock_release: 3512 case Builtin::BI__sync_lock_release_1: 3513 case Builtin::BI__sync_lock_release_2: 3514 case Builtin::BI__sync_lock_release_4: 3515 case Builtin::BI__sync_lock_release_8: 3516 case Builtin::BI__sync_lock_release_16: 3517 BuiltinIndex = 15; 3518 NumFixed = 0; 3519 ResultType = Context.VoidTy; 3520 break; 3521 3522 case Builtin::BI__sync_swap: 3523 case Builtin::BI__sync_swap_1: 3524 case Builtin::BI__sync_swap_2: 3525 case Builtin::BI__sync_swap_4: 3526 case Builtin::BI__sync_swap_8: 3527 case Builtin::BI__sync_swap_16: 3528 BuiltinIndex = 16; 3529 break; 3530 } 3531 3532 // Now that we know how many fixed arguments we expect, first check that we 3533 // have at least that many. 3534 if (TheCall->getNumArgs() < 1+NumFixed) { 3535 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3536 << 0 << 1+NumFixed << TheCall->getNumArgs() 3537 << TheCall->getCallee()->getSourceRange(); 3538 return ExprError(); 3539 } 3540 3541 if (WarnAboutSemanticsChange) { 3542 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3543 << TheCall->getCallee()->getSourceRange(); 3544 } 3545 3546 // Get the decl for the concrete builtin from this, we can tell what the 3547 // concrete integer type we should convert to is. 3548 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3549 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3550 FunctionDecl *NewBuiltinDecl; 3551 if (NewBuiltinID == BuiltinID) 3552 NewBuiltinDecl = FDecl; 3553 else { 3554 // Perform builtin lookup to avoid redeclaring it. 3555 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3556 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3557 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3558 assert(Res.getFoundDecl()); 3559 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3560 if (!NewBuiltinDecl) 3561 return ExprError(); 3562 } 3563 3564 // The first argument --- the pointer --- has a fixed type; we 3565 // deduce the types of the rest of the arguments accordingly. Walk 3566 // the remaining arguments, converting them to the deduced value type. 3567 for (unsigned i = 0; i != NumFixed; ++i) { 3568 ExprResult Arg = TheCall->getArg(i+1); 3569 3570 // GCC does an implicit conversion to the pointer or integer ValType. This 3571 // can fail in some cases (1i -> int**), check for this error case now. 3572 // Initialize the argument. 3573 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3574 ValType, /*consume*/ false); 3575 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3576 if (Arg.isInvalid()) 3577 return ExprError(); 3578 3579 // Okay, we have something that *can* be converted to the right type. Check 3580 // to see if there is a potentially weird extension going on here. This can 3581 // happen when you do an atomic operation on something like an char* and 3582 // pass in 42. The 42 gets converted to char. This is even more strange 3583 // for things like 45.123 -> char, etc. 3584 // FIXME: Do this check. 3585 TheCall->setArg(i+1, Arg.get()); 3586 } 3587 3588 ASTContext& Context = this->getASTContext(); 3589 3590 // Create a new DeclRefExpr to refer to the new decl. 3591 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3592 Context, 3593 DRE->getQualifierLoc(), 3594 SourceLocation(), 3595 NewBuiltinDecl, 3596 /*enclosing*/ false, 3597 DRE->getLocation(), 3598 Context.BuiltinFnTy, 3599 DRE->getValueKind()); 3600 3601 // Set the callee in the CallExpr. 3602 // FIXME: This loses syntactic information. 3603 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3604 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3605 CK_BuiltinFnToFnPtr); 3606 TheCall->setCallee(PromotedCall.get()); 3607 3608 // Change the result type of the call to match the original value type. This 3609 // is arbitrary, but the codegen for these builtins ins design to handle it 3610 // gracefully. 3611 TheCall->setType(ResultType); 3612 3613 return TheCallResult; 3614 } 3615 3616 /// SemaBuiltinNontemporalOverloaded - We have a call to 3617 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3618 /// overloaded function based on the pointer type of its last argument. 3619 /// 3620 /// This function goes through and does final semantic checking for these 3621 /// builtins. 3622 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3623 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3624 DeclRefExpr *DRE = 3625 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3626 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3627 unsigned BuiltinID = FDecl->getBuiltinID(); 3628 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3629 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3630 "Unexpected nontemporal load/store builtin!"); 3631 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3632 unsigned numArgs = isStore ? 2 : 1; 3633 3634 // Ensure that we have the proper number of arguments. 3635 if (checkArgCount(*this, TheCall, numArgs)) 3636 return ExprError(); 3637 3638 // Inspect the last argument of the nontemporal builtin. This should always 3639 // be a pointer type, from which we imply the type of the memory access. 3640 // Because it is a pointer type, we don't have to worry about any implicit 3641 // casts here. 3642 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3643 ExprResult PointerArgResult = 3644 DefaultFunctionArrayLvalueConversion(PointerArg); 3645 3646 if (PointerArgResult.isInvalid()) 3647 return ExprError(); 3648 PointerArg = PointerArgResult.get(); 3649 TheCall->setArg(numArgs - 1, PointerArg); 3650 3651 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3652 if (!pointerType) { 3653 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3654 << PointerArg->getType() << PointerArg->getSourceRange(); 3655 return ExprError(); 3656 } 3657 3658 QualType ValType = pointerType->getPointeeType(); 3659 3660 // Strip any qualifiers off ValType. 3661 ValType = ValType.getUnqualifiedType(); 3662 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3663 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3664 !ValType->isVectorType()) { 3665 Diag(DRE->getLocStart(), 3666 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3667 << PointerArg->getType() << PointerArg->getSourceRange(); 3668 return ExprError(); 3669 } 3670 3671 if (!isStore) { 3672 TheCall->setType(ValType); 3673 return TheCallResult; 3674 } 3675 3676 ExprResult ValArg = TheCall->getArg(0); 3677 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3678 Context, ValType, /*consume*/ false); 3679 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3680 if (ValArg.isInvalid()) 3681 return ExprError(); 3682 3683 TheCall->setArg(0, ValArg.get()); 3684 TheCall->setType(Context.VoidTy); 3685 return TheCallResult; 3686 } 3687 3688 /// CheckObjCString - Checks that the argument to the builtin 3689 /// CFString constructor is correct 3690 /// Note: It might also make sense to do the UTF-16 conversion here (would 3691 /// simplify the backend). 3692 bool Sema::CheckObjCString(Expr *Arg) { 3693 Arg = Arg->IgnoreParenCasts(); 3694 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3695 3696 if (!Literal || !Literal->isAscii()) { 3697 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3698 << Arg->getSourceRange(); 3699 return true; 3700 } 3701 3702 if (Literal->containsNonAsciiOrNull()) { 3703 StringRef String = Literal->getString(); 3704 unsigned NumBytes = String.size(); 3705 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3706 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3707 llvm::UTF16 *ToPtr = &ToBuf[0]; 3708 3709 llvm::ConversionResult Result = 3710 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3711 ToPtr + NumBytes, llvm::strictConversion); 3712 // Check for conversion failure. 3713 if (Result != llvm::conversionOK) 3714 Diag(Arg->getLocStart(), 3715 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3716 } 3717 return false; 3718 } 3719 3720 /// CheckObjCString - Checks that the format string argument to the os_log() 3721 /// and os_trace() functions is correct, and converts it to const char *. 3722 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3723 Arg = Arg->IgnoreParenCasts(); 3724 auto *Literal = dyn_cast<StringLiteral>(Arg); 3725 if (!Literal) { 3726 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3727 Literal = ObjcLiteral->getString(); 3728 } 3729 } 3730 3731 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3732 return ExprError( 3733 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3734 << Arg->getSourceRange()); 3735 } 3736 3737 ExprResult Result(Literal); 3738 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3739 InitializedEntity Entity = 3740 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3741 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3742 return Result; 3743 } 3744 3745 /// Check that the user is calling the appropriate va_start builtin for the 3746 /// target and calling convention. 3747 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 3748 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 3749 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 3750 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 3751 bool IsWindows = TT.isOSWindows(); 3752 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 3753 if (IsX64 || IsAArch64) { 3754 clang::CallingConv CC = CC_C; 3755 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 3756 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3757 if (IsMSVAStart) { 3758 // Don't allow this in System V ABI functions. 3759 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 3760 return S.Diag(Fn->getLocStart(), 3761 diag::err_ms_va_start_used_in_sysv_function); 3762 } else { 3763 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 3764 // On x64 Windows, don't allow this in System V ABI functions. 3765 // (Yes, that means there's no corresponding way to support variadic 3766 // System V ABI functions on Windows.) 3767 if ((IsWindows && CC == CC_X86_64SysV) || 3768 (!IsWindows && CC == CC_Win64)) 3769 return S.Diag(Fn->getLocStart(), 3770 diag::err_va_start_used_in_wrong_abi_function) 3771 << !IsWindows; 3772 } 3773 return false; 3774 } 3775 3776 if (IsMSVAStart) 3777 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 3778 return false; 3779 } 3780 3781 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 3782 ParmVarDecl **LastParam = nullptr) { 3783 // Determine whether the current function, block, or obj-c method is variadic 3784 // and get its parameter list. 3785 bool IsVariadic = false; 3786 ArrayRef<ParmVarDecl *> Params; 3787 DeclContext *Caller = S.CurContext; 3788 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 3789 IsVariadic = Block->isVariadic(); 3790 Params = Block->parameters(); 3791 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 3792 IsVariadic = FD->isVariadic(); 3793 Params = FD->parameters(); 3794 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 3795 IsVariadic = MD->isVariadic(); 3796 // FIXME: This isn't correct for methods (results in bogus warning). 3797 Params = MD->parameters(); 3798 } else if (isa<CapturedDecl>(Caller)) { 3799 // We don't support va_start in a CapturedDecl. 3800 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 3801 return true; 3802 } else { 3803 // This must be some other declcontext that parses exprs. 3804 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 3805 return true; 3806 } 3807 3808 if (!IsVariadic) { 3809 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 3810 return true; 3811 } 3812 3813 if (LastParam) 3814 *LastParam = Params.empty() ? nullptr : Params.back(); 3815 3816 return false; 3817 } 3818 3819 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3820 /// for validity. Emit an error and return true on failure; return false 3821 /// on success. 3822 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 3823 Expr *Fn = TheCall->getCallee(); 3824 3825 if (checkVAStartABI(*this, BuiltinID, Fn)) 3826 return true; 3827 3828 if (TheCall->getNumArgs() > 2) { 3829 Diag(TheCall->getArg(2)->getLocStart(), 3830 diag::err_typecheck_call_too_many_args) 3831 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3832 << Fn->getSourceRange() 3833 << SourceRange(TheCall->getArg(2)->getLocStart(), 3834 (*(TheCall->arg_end()-1))->getLocEnd()); 3835 return true; 3836 } 3837 3838 if (TheCall->getNumArgs() < 2) { 3839 return Diag(TheCall->getLocEnd(), 3840 diag::err_typecheck_call_too_few_args_at_least) 3841 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3842 } 3843 3844 // Type-check the first argument normally. 3845 if (checkBuiltinArgument(*this, TheCall, 0)) 3846 return true; 3847 3848 // Check that the current function is variadic, and get its last parameter. 3849 ParmVarDecl *LastParam; 3850 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 3851 return true; 3852 3853 // Verify that the second argument to the builtin is the last argument of the 3854 // current function or method. 3855 bool SecondArgIsLastNamedArgument = false; 3856 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3857 3858 // These are valid if SecondArgIsLastNamedArgument is false after the next 3859 // block. 3860 QualType Type; 3861 SourceLocation ParamLoc; 3862 bool IsCRegister = false; 3863 3864 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3865 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3866 SecondArgIsLastNamedArgument = PV == LastParam; 3867 3868 Type = PV->getType(); 3869 ParamLoc = PV->getLocation(); 3870 IsCRegister = 3871 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3872 } 3873 } 3874 3875 if (!SecondArgIsLastNamedArgument) 3876 Diag(TheCall->getArg(1)->getLocStart(), 3877 diag::warn_second_arg_of_va_start_not_last_named_param); 3878 else if (IsCRegister || Type->isReferenceType() || 3879 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3880 // Promotable integers are UB, but enumerations need a bit of 3881 // extra checking to see what their promotable type actually is. 3882 if (!Type->isPromotableIntegerType()) 3883 return false; 3884 if (!Type->isEnumeralType()) 3885 return true; 3886 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3887 return !(ED && 3888 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3889 }()) { 3890 unsigned Reason = 0; 3891 if (Type->isReferenceType()) Reason = 1; 3892 else if (IsCRegister) Reason = 2; 3893 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3894 Diag(ParamLoc, diag::note_parameter_type) << Type; 3895 } 3896 3897 TheCall->setType(Context.VoidTy); 3898 return false; 3899 } 3900 3901 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3902 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3903 // const char *named_addr); 3904 3905 Expr *Func = Call->getCallee(); 3906 3907 if (Call->getNumArgs() < 3) 3908 return Diag(Call->getLocEnd(), 3909 diag::err_typecheck_call_too_few_args_at_least) 3910 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3911 3912 // Type-check the first argument normally. 3913 if (checkBuiltinArgument(*this, Call, 0)) 3914 return true; 3915 3916 // Check that the current function is variadic. 3917 if (checkVAStartIsInVariadicFunction(*this, Func)) 3918 return true; 3919 3920 const struct { 3921 unsigned ArgNo; 3922 QualType Type; 3923 } ArgumentTypes[] = { 3924 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3925 { 2, Context.getSizeType() }, 3926 }; 3927 3928 for (const auto &AT : ArgumentTypes) { 3929 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3930 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3931 continue; 3932 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3933 << Arg->getType() << AT.Type << 1 /* different class */ 3934 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3935 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3936 } 3937 3938 return false; 3939 } 3940 3941 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3942 /// friends. This is declared to take (...), so we have to check everything. 3943 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3944 if (TheCall->getNumArgs() < 2) 3945 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3946 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3947 if (TheCall->getNumArgs() > 2) 3948 return Diag(TheCall->getArg(2)->getLocStart(), 3949 diag::err_typecheck_call_too_many_args) 3950 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3951 << SourceRange(TheCall->getArg(2)->getLocStart(), 3952 (*(TheCall->arg_end()-1))->getLocEnd()); 3953 3954 ExprResult OrigArg0 = TheCall->getArg(0); 3955 ExprResult OrigArg1 = TheCall->getArg(1); 3956 3957 // Do standard promotions between the two arguments, returning their common 3958 // type. 3959 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3960 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3961 return true; 3962 3963 // Make sure any conversions are pushed back into the call; this is 3964 // type safe since unordered compare builtins are declared as "_Bool 3965 // foo(...)". 3966 TheCall->setArg(0, OrigArg0.get()); 3967 TheCall->setArg(1, OrigArg1.get()); 3968 3969 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3970 return false; 3971 3972 // If the common type isn't a real floating type, then the arguments were 3973 // invalid for this operation. 3974 if (Res.isNull() || !Res->isRealFloatingType()) 3975 return Diag(OrigArg0.get()->getLocStart(), 3976 diag::err_typecheck_call_invalid_ordered_compare) 3977 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3978 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3979 3980 return false; 3981 } 3982 3983 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3984 /// __builtin_isnan and friends. This is declared to take (...), so we have 3985 /// to check everything. We expect the last argument to be a floating point 3986 /// value. 3987 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3988 if (TheCall->getNumArgs() < NumArgs) 3989 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3990 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3991 if (TheCall->getNumArgs() > NumArgs) 3992 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3993 diag::err_typecheck_call_too_many_args) 3994 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3995 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3996 (*(TheCall->arg_end()-1))->getLocEnd()); 3997 3998 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3999 4000 if (OrigArg->isTypeDependent()) 4001 return false; 4002 4003 // This operation requires a non-_Complex floating-point number. 4004 if (!OrigArg->getType()->isRealFloatingType()) 4005 return Diag(OrigArg->getLocStart(), 4006 diag::err_typecheck_call_invalid_unary_fp) 4007 << OrigArg->getType() << OrigArg->getSourceRange(); 4008 4009 // If this is an implicit conversion from float -> float or double, remove it. 4010 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4011 // Only remove standard FloatCasts, leaving other casts inplace 4012 if (Cast->getCastKind() == CK_FloatingCast) { 4013 Expr *CastArg = Cast->getSubExpr(); 4014 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4015 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4016 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 4017 "promotion from float to either float or double is the only expected cast here"); 4018 Cast->setSubExpr(nullptr); 4019 TheCall->setArg(NumArgs-1, CastArg); 4020 } 4021 } 4022 } 4023 4024 return false; 4025 } 4026 4027 // Customized Sema Checking for VSX builtins that have the following signature: 4028 // vector [...] builtinName(vector [...], vector [...], const int); 4029 // Which takes the same type of vectors (any legal vector type) for the first 4030 // two arguments and takes compile time constant for the third argument. 4031 // Example builtins are : 4032 // vector double vec_xxpermdi(vector double, vector double, int); 4033 // vector short vec_xxsldwi(vector short, vector short, int); 4034 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4035 unsigned ExpectedNumArgs = 3; 4036 if (TheCall->getNumArgs() < ExpectedNumArgs) 4037 return Diag(TheCall->getLocEnd(), 4038 diag::err_typecheck_call_too_few_args_at_least) 4039 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4040 << TheCall->getSourceRange(); 4041 4042 if (TheCall->getNumArgs() > ExpectedNumArgs) 4043 return Diag(TheCall->getLocEnd(), 4044 diag::err_typecheck_call_too_many_args_at_most) 4045 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4046 << TheCall->getSourceRange(); 4047 4048 // Check the third argument is a compile time constant 4049 llvm::APSInt Value; 4050 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4051 return Diag(TheCall->getLocStart(), 4052 diag::err_vsx_builtin_nonconstant_argument) 4053 << 3 /* argument index */ << TheCall->getDirectCallee() 4054 << SourceRange(TheCall->getArg(2)->getLocStart(), 4055 TheCall->getArg(2)->getLocEnd()); 4056 4057 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4058 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4059 4060 // Check the type of argument 1 and argument 2 are vectors. 4061 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4062 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4063 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4064 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4065 << TheCall->getDirectCallee() 4066 << SourceRange(TheCall->getArg(0)->getLocStart(), 4067 TheCall->getArg(1)->getLocEnd()); 4068 } 4069 4070 // Check the first two arguments are the same type. 4071 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4072 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4073 << TheCall->getDirectCallee() 4074 << SourceRange(TheCall->getArg(0)->getLocStart(), 4075 TheCall->getArg(1)->getLocEnd()); 4076 } 4077 4078 // When default clang type checking is turned off and the customized type 4079 // checking is used, the returning type of the function must be explicitly 4080 // set. Otherwise it is _Bool by default. 4081 TheCall->setType(Arg1Ty); 4082 4083 return false; 4084 } 4085 4086 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4087 // This is declared to take (...), so we have to check everything. 4088 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4089 if (TheCall->getNumArgs() < 2) 4090 return ExprError(Diag(TheCall->getLocEnd(), 4091 diag::err_typecheck_call_too_few_args_at_least) 4092 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4093 << TheCall->getSourceRange()); 4094 4095 // Determine which of the following types of shufflevector we're checking: 4096 // 1) unary, vector mask: (lhs, mask) 4097 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4098 QualType resType = TheCall->getArg(0)->getType(); 4099 unsigned numElements = 0; 4100 4101 if (!TheCall->getArg(0)->isTypeDependent() && 4102 !TheCall->getArg(1)->isTypeDependent()) { 4103 QualType LHSType = TheCall->getArg(0)->getType(); 4104 QualType RHSType = TheCall->getArg(1)->getType(); 4105 4106 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4107 return ExprError(Diag(TheCall->getLocStart(), 4108 diag::err_vec_builtin_non_vector) 4109 << TheCall->getDirectCallee() 4110 << SourceRange(TheCall->getArg(0)->getLocStart(), 4111 TheCall->getArg(1)->getLocEnd())); 4112 4113 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4114 unsigned numResElements = TheCall->getNumArgs() - 2; 4115 4116 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4117 // with mask. If so, verify that RHS is an integer vector type with the 4118 // same number of elts as lhs. 4119 if (TheCall->getNumArgs() == 2) { 4120 if (!RHSType->hasIntegerRepresentation() || 4121 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4122 return ExprError(Diag(TheCall->getLocStart(), 4123 diag::err_vec_builtin_incompatible_vector) 4124 << TheCall->getDirectCallee() 4125 << SourceRange(TheCall->getArg(1)->getLocStart(), 4126 TheCall->getArg(1)->getLocEnd())); 4127 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4128 return ExprError(Diag(TheCall->getLocStart(), 4129 diag::err_vec_builtin_incompatible_vector) 4130 << TheCall->getDirectCallee() 4131 << SourceRange(TheCall->getArg(0)->getLocStart(), 4132 TheCall->getArg(1)->getLocEnd())); 4133 } else if (numElements != numResElements) { 4134 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4135 resType = Context.getVectorType(eltType, numResElements, 4136 VectorType::GenericVector); 4137 } 4138 } 4139 4140 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4141 if (TheCall->getArg(i)->isTypeDependent() || 4142 TheCall->getArg(i)->isValueDependent()) 4143 continue; 4144 4145 llvm::APSInt Result(32); 4146 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4147 return ExprError(Diag(TheCall->getLocStart(), 4148 diag::err_shufflevector_nonconstant_argument) 4149 << TheCall->getArg(i)->getSourceRange()); 4150 4151 // Allow -1 which will be translated to undef in the IR. 4152 if (Result.isSigned() && Result.isAllOnesValue()) 4153 continue; 4154 4155 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4156 return ExprError(Diag(TheCall->getLocStart(), 4157 diag::err_shufflevector_argument_too_large) 4158 << TheCall->getArg(i)->getSourceRange()); 4159 } 4160 4161 SmallVector<Expr*, 32> exprs; 4162 4163 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4164 exprs.push_back(TheCall->getArg(i)); 4165 TheCall->setArg(i, nullptr); 4166 } 4167 4168 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4169 TheCall->getCallee()->getLocStart(), 4170 TheCall->getRParenLoc()); 4171 } 4172 4173 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4174 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4175 SourceLocation BuiltinLoc, 4176 SourceLocation RParenLoc) { 4177 ExprValueKind VK = VK_RValue; 4178 ExprObjectKind OK = OK_Ordinary; 4179 QualType DstTy = TInfo->getType(); 4180 QualType SrcTy = E->getType(); 4181 4182 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4183 return ExprError(Diag(BuiltinLoc, 4184 diag::err_convertvector_non_vector) 4185 << E->getSourceRange()); 4186 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4187 return ExprError(Diag(BuiltinLoc, 4188 diag::err_convertvector_non_vector_type)); 4189 4190 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4191 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4192 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4193 if (SrcElts != DstElts) 4194 return ExprError(Diag(BuiltinLoc, 4195 diag::err_convertvector_incompatible_vector) 4196 << E->getSourceRange()); 4197 } 4198 4199 return new (Context) 4200 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4201 } 4202 4203 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4204 // This is declared to take (const void*, ...) and can take two 4205 // optional constant int args. 4206 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4207 unsigned NumArgs = TheCall->getNumArgs(); 4208 4209 if (NumArgs > 3) 4210 return Diag(TheCall->getLocEnd(), 4211 diag::err_typecheck_call_too_many_args_at_most) 4212 << 0 /*function call*/ << 3 << NumArgs 4213 << TheCall->getSourceRange(); 4214 4215 // Argument 0 is checked for us and the remaining arguments must be 4216 // constant integers. 4217 for (unsigned i = 1; i != NumArgs; ++i) 4218 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4219 return true; 4220 4221 return false; 4222 } 4223 4224 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4225 // __assume does not evaluate its arguments, and should warn if its argument 4226 // has side effects. 4227 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4228 Expr *Arg = TheCall->getArg(0); 4229 if (Arg->isInstantiationDependent()) return false; 4230 4231 if (Arg->HasSideEffects(Context)) 4232 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4233 << Arg->getSourceRange() 4234 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4235 4236 return false; 4237 } 4238 4239 /// Handle __builtin_alloca_with_align. This is declared 4240 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4241 /// than 8. 4242 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4243 // The alignment must be a constant integer. 4244 Expr *Arg = TheCall->getArg(1); 4245 4246 // We can't check the value of a dependent argument. 4247 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4248 if (const auto *UE = 4249 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4250 if (UE->getKind() == UETT_AlignOf) 4251 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4252 << Arg->getSourceRange(); 4253 4254 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4255 4256 if (!Result.isPowerOf2()) 4257 return Diag(TheCall->getLocStart(), 4258 diag::err_alignment_not_power_of_two) 4259 << Arg->getSourceRange(); 4260 4261 if (Result < Context.getCharWidth()) 4262 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4263 << (unsigned)Context.getCharWidth() 4264 << Arg->getSourceRange(); 4265 4266 if (Result > INT32_MAX) 4267 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4268 << INT32_MAX 4269 << Arg->getSourceRange(); 4270 } 4271 4272 return false; 4273 } 4274 4275 /// Handle __builtin_assume_aligned. This is declared 4276 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4277 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4278 unsigned NumArgs = TheCall->getNumArgs(); 4279 4280 if (NumArgs > 3) 4281 return Diag(TheCall->getLocEnd(), 4282 diag::err_typecheck_call_too_many_args_at_most) 4283 << 0 /*function call*/ << 3 << NumArgs 4284 << TheCall->getSourceRange(); 4285 4286 // The alignment must be a constant integer. 4287 Expr *Arg = TheCall->getArg(1); 4288 4289 // We can't check the value of a dependent argument. 4290 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4291 llvm::APSInt Result; 4292 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4293 return true; 4294 4295 if (!Result.isPowerOf2()) 4296 return Diag(TheCall->getLocStart(), 4297 diag::err_alignment_not_power_of_two) 4298 << Arg->getSourceRange(); 4299 } 4300 4301 if (NumArgs > 2) { 4302 ExprResult Arg(TheCall->getArg(2)); 4303 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4304 Context.getSizeType(), false); 4305 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4306 if (Arg.isInvalid()) return true; 4307 TheCall->setArg(2, Arg.get()); 4308 } 4309 4310 return false; 4311 } 4312 4313 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4314 unsigned BuiltinID = 4315 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4316 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4317 4318 unsigned NumArgs = TheCall->getNumArgs(); 4319 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4320 if (NumArgs < NumRequiredArgs) { 4321 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4322 << 0 /* function call */ << NumRequiredArgs << NumArgs 4323 << TheCall->getSourceRange(); 4324 } 4325 if (NumArgs >= NumRequiredArgs + 0x100) { 4326 return Diag(TheCall->getLocEnd(), 4327 diag::err_typecheck_call_too_many_args_at_most) 4328 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4329 << TheCall->getSourceRange(); 4330 } 4331 unsigned i = 0; 4332 4333 // For formatting call, check buffer arg. 4334 if (!IsSizeCall) { 4335 ExprResult Arg(TheCall->getArg(i)); 4336 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4337 Context, Context.VoidPtrTy, false); 4338 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4339 if (Arg.isInvalid()) 4340 return true; 4341 TheCall->setArg(i, Arg.get()); 4342 i++; 4343 } 4344 4345 // Check string literal arg. 4346 unsigned FormatIdx = i; 4347 { 4348 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4349 if (Arg.isInvalid()) 4350 return true; 4351 TheCall->setArg(i, Arg.get()); 4352 i++; 4353 } 4354 4355 // Make sure variadic args are scalar. 4356 unsigned FirstDataArg = i; 4357 while (i < NumArgs) { 4358 ExprResult Arg = DefaultVariadicArgumentPromotion( 4359 TheCall->getArg(i), VariadicFunction, nullptr); 4360 if (Arg.isInvalid()) 4361 return true; 4362 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4363 if (ArgSize.getQuantity() >= 0x100) { 4364 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4365 << i << (int)ArgSize.getQuantity() << 0xff 4366 << TheCall->getSourceRange(); 4367 } 4368 TheCall->setArg(i, Arg.get()); 4369 i++; 4370 } 4371 4372 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4373 // call to avoid duplicate diagnostics. 4374 if (!IsSizeCall) { 4375 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4376 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4377 bool Success = CheckFormatArguments( 4378 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4379 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4380 CheckedVarArgs); 4381 if (!Success) 4382 return true; 4383 } 4384 4385 if (IsSizeCall) { 4386 TheCall->setType(Context.getSizeType()); 4387 } else { 4388 TheCall->setType(Context.VoidPtrTy); 4389 } 4390 return false; 4391 } 4392 4393 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4394 /// TheCall is a constant expression. 4395 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4396 llvm::APSInt &Result) { 4397 Expr *Arg = TheCall->getArg(ArgNum); 4398 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4399 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4400 4401 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4402 4403 if (!Arg->isIntegerConstantExpr(Result, Context)) 4404 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4405 << FDecl->getDeclName() << Arg->getSourceRange(); 4406 4407 return false; 4408 } 4409 4410 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4411 /// TheCall is a constant expression in the range [Low, High]. 4412 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4413 int Low, int High) { 4414 llvm::APSInt Result; 4415 4416 // We can't check the value of a dependent argument. 4417 Expr *Arg = TheCall->getArg(ArgNum); 4418 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4419 return false; 4420 4421 // Check constant-ness first. 4422 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4423 return true; 4424 4425 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4426 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4427 << Low << High << Arg->getSourceRange(); 4428 4429 return false; 4430 } 4431 4432 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4433 /// TheCall is a constant expression is a multiple of Num.. 4434 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4435 unsigned Num) { 4436 llvm::APSInt Result; 4437 4438 // We can't check the value of a dependent argument. 4439 Expr *Arg = TheCall->getArg(ArgNum); 4440 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4441 return false; 4442 4443 // Check constant-ness first. 4444 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4445 return true; 4446 4447 if (Result.getSExtValue() % Num != 0) 4448 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4449 << Num << Arg->getSourceRange(); 4450 4451 return false; 4452 } 4453 4454 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4455 /// TheCall is an ARM/AArch64 special register string literal. 4456 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4457 int ArgNum, unsigned ExpectedFieldNum, 4458 bool AllowName) { 4459 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4460 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4461 BuiltinID == ARM::BI__builtin_arm_rsr || 4462 BuiltinID == ARM::BI__builtin_arm_rsrp || 4463 BuiltinID == ARM::BI__builtin_arm_wsr || 4464 BuiltinID == ARM::BI__builtin_arm_wsrp; 4465 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4466 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4467 BuiltinID == AArch64::BI__builtin_arm_rsr || 4468 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4469 BuiltinID == AArch64::BI__builtin_arm_wsr || 4470 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4471 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4472 4473 // We can't check the value of a dependent argument. 4474 Expr *Arg = TheCall->getArg(ArgNum); 4475 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4476 return false; 4477 4478 // Check if the argument is a string literal. 4479 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4480 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4481 << Arg->getSourceRange(); 4482 4483 // Check the type of special register given. 4484 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4485 SmallVector<StringRef, 6> Fields; 4486 Reg.split(Fields, ":"); 4487 4488 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4489 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4490 << Arg->getSourceRange(); 4491 4492 // If the string is the name of a register then we cannot check that it is 4493 // valid here but if the string is of one the forms described in ACLE then we 4494 // can check that the supplied fields are integers and within the valid 4495 // ranges. 4496 if (Fields.size() > 1) { 4497 bool FiveFields = Fields.size() == 5; 4498 4499 bool ValidString = true; 4500 if (IsARMBuiltin) { 4501 ValidString &= Fields[0].startswith_lower("cp") || 4502 Fields[0].startswith_lower("p"); 4503 if (ValidString) 4504 Fields[0] = 4505 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4506 4507 ValidString &= Fields[2].startswith_lower("c"); 4508 if (ValidString) 4509 Fields[2] = Fields[2].drop_front(1); 4510 4511 if (FiveFields) { 4512 ValidString &= Fields[3].startswith_lower("c"); 4513 if (ValidString) 4514 Fields[3] = Fields[3].drop_front(1); 4515 } 4516 } 4517 4518 SmallVector<int, 5> Ranges; 4519 if (FiveFields) 4520 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4521 else 4522 Ranges.append({15, 7, 15}); 4523 4524 for (unsigned i=0; i<Fields.size(); ++i) { 4525 int IntField; 4526 ValidString &= !Fields[i].getAsInteger(10, IntField); 4527 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4528 } 4529 4530 if (!ValidString) 4531 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4532 << Arg->getSourceRange(); 4533 4534 } else if (IsAArch64Builtin && Fields.size() == 1) { 4535 // If the register name is one of those that appear in the condition below 4536 // and the special register builtin being used is one of the write builtins, 4537 // then we require that the argument provided for writing to the register 4538 // is an integer constant expression. This is because it will be lowered to 4539 // an MSR (immediate) instruction, so we need to know the immediate at 4540 // compile time. 4541 if (TheCall->getNumArgs() != 2) 4542 return false; 4543 4544 std::string RegLower = Reg.lower(); 4545 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4546 RegLower != "pan" && RegLower != "uao") 4547 return false; 4548 4549 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4550 } 4551 4552 return false; 4553 } 4554 4555 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4556 /// This checks that the target supports __builtin_longjmp and 4557 /// that val is a constant 1. 4558 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4559 if (!Context.getTargetInfo().hasSjLjLowering()) 4560 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4561 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4562 4563 Expr *Arg = TheCall->getArg(1); 4564 llvm::APSInt Result; 4565 4566 // TODO: This is less than ideal. Overload this to take a value. 4567 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4568 return true; 4569 4570 if (Result != 1) 4571 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4572 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4573 4574 return false; 4575 } 4576 4577 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4578 /// This checks that the target supports __builtin_setjmp. 4579 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4580 if (!Context.getTargetInfo().hasSjLjLowering()) 4581 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4582 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4583 return false; 4584 } 4585 4586 namespace { 4587 class UncoveredArgHandler { 4588 enum { Unknown = -1, AllCovered = -2 }; 4589 signed FirstUncoveredArg; 4590 SmallVector<const Expr *, 4> DiagnosticExprs; 4591 4592 public: 4593 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4594 4595 bool hasUncoveredArg() const { 4596 return (FirstUncoveredArg >= 0); 4597 } 4598 4599 unsigned getUncoveredArg() const { 4600 assert(hasUncoveredArg() && "no uncovered argument"); 4601 return FirstUncoveredArg; 4602 } 4603 4604 void setAllCovered() { 4605 // A string has been found with all arguments covered, so clear out 4606 // the diagnostics. 4607 DiagnosticExprs.clear(); 4608 FirstUncoveredArg = AllCovered; 4609 } 4610 4611 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4612 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4613 4614 // Don't update if a previous string covers all arguments. 4615 if (FirstUncoveredArg == AllCovered) 4616 return; 4617 4618 // UncoveredArgHandler tracks the highest uncovered argument index 4619 // and with it all the strings that match this index. 4620 if (NewFirstUncoveredArg == FirstUncoveredArg) 4621 DiagnosticExprs.push_back(StrExpr); 4622 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4623 DiagnosticExprs.clear(); 4624 DiagnosticExprs.push_back(StrExpr); 4625 FirstUncoveredArg = NewFirstUncoveredArg; 4626 } 4627 } 4628 4629 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4630 }; 4631 4632 enum StringLiteralCheckType { 4633 SLCT_NotALiteral, 4634 SLCT_UncheckedLiteral, 4635 SLCT_CheckedLiteral 4636 }; 4637 } // end anonymous namespace 4638 4639 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4640 BinaryOperatorKind BinOpKind, 4641 bool AddendIsRight) { 4642 unsigned BitWidth = Offset.getBitWidth(); 4643 unsigned AddendBitWidth = Addend.getBitWidth(); 4644 // There might be negative interim results. 4645 if (Addend.isUnsigned()) { 4646 Addend = Addend.zext(++AddendBitWidth); 4647 Addend.setIsSigned(true); 4648 } 4649 // Adjust the bit width of the APSInts. 4650 if (AddendBitWidth > BitWidth) { 4651 Offset = Offset.sext(AddendBitWidth); 4652 BitWidth = AddendBitWidth; 4653 } else if (BitWidth > AddendBitWidth) { 4654 Addend = Addend.sext(BitWidth); 4655 } 4656 4657 bool Ov = false; 4658 llvm::APSInt ResOffset = Offset; 4659 if (BinOpKind == BO_Add) 4660 ResOffset = Offset.sadd_ov(Addend, Ov); 4661 else { 4662 assert(AddendIsRight && BinOpKind == BO_Sub && 4663 "operator must be add or sub with addend on the right"); 4664 ResOffset = Offset.ssub_ov(Addend, Ov); 4665 } 4666 4667 // We add an offset to a pointer here so we should support an offset as big as 4668 // possible. 4669 if (Ov) { 4670 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4671 Offset = Offset.sext(2 * BitWidth); 4672 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4673 return; 4674 } 4675 4676 Offset = ResOffset; 4677 } 4678 4679 namespace { 4680 // This is a wrapper class around StringLiteral to support offsetted string 4681 // literals as format strings. It takes the offset into account when returning 4682 // the string and its length or the source locations to display notes correctly. 4683 class FormatStringLiteral { 4684 const StringLiteral *FExpr; 4685 int64_t Offset; 4686 4687 public: 4688 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4689 : FExpr(fexpr), Offset(Offset) {} 4690 4691 StringRef getString() const { 4692 return FExpr->getString().drop_front(Offset); 4693 } 4694 4695 unsigned getByteLength() const { 4696 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4697 } 4698 unsigned getLength() const { return FExpr->getLength() - Offset; } 4699 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4700 4701 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4702 4703 QualType getType() const { return FExpr->getType(); } 4704 4705 bool isAscii() const { return FExpr->isAscii(); } 4706 bool isWide() const { return FExpr->isWide(); } 4707 bool isUTF8() const { return FExpr->isUTF8(); } 4708 bool isUTF16() const { return FExpr->isUTF16(); } 4709 bool isUTF32() const { return FExpr->isUTF32(); } 4710 bool isPascal() const { return FExpr->isPascal(); } 4711 4712 SourceLocation getLocationOfByte( 4713 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4714 const TargetInfo &Target, unsigned *StartToken = nullptr, 4715 unsigned *StartTokenByteOffset = nullptr) const { 4716 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4717 StartToken, StartTokenByteOffset); 4718 } 4719 4720 SourceLocation getLocStart() const LLVM_READONLY { 4721 return FExpr->getLocStart().getLocWithOffset(Offset); 4722 } 4723 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4724 }; 4725 } // end anonymous namespace 4726 4727 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4728 const Expr *OrigFormatExpr, 4729 ArrayRef<const Expr *> Args, 4730 bool HasVAListArg, unsigned format_idx, 4731 unsigned firstDataArg, 4732 Sema::FormatStringType Type, 4733 bool inFunctionCall, 4734 Sema::VariadicCallType CallType, 4735 llvm::SmallBitVector &CheckedVarArgs, 4736 UncoveredArgHandler &UncoveredArg); 4737 4738 // Determine if an expression is a string literal or constant string. 4739 // If this function returns false on the arguments to a function expecting a 4740 // format string, we will usually need to emit a warning. 4741 // True string literals are then checked by CheckFormatString. 4742 static StringLiteralCheckType 4743 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4744 bool HasVAListArg, unsigned format_idx, 4745 unsigned firstDataArg, Sema::FormatStringType Type, 4746 Sema::VariadicCallType CallType, bool InFunctionCall, 4747 llvm::SmallBitVector &CheckedVarArgs, 4748 UncoveredArgHandler &UncoveredArg, 4749 llvm::APSInt Offset) { 4750 tryAgain: 4751 assert(Offset.isSigned() && "invalid offset"); 4752 4753 if (E->isTypeDependent() || E->isValueDependent()) 4754 return SLCT_NotALiteral; 4755 4756 E = E->IgnoreParenCasts(); 4757 4758 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4759 // Technically -Wformat-nonliteral does not warn about this case. 4760 // The behavior of printf and friends in this case is implementation 4761 // dependent. Ideally if the format string cannot be null then 4762 // it should have a 'nonnull' attribute in the function prototype. 4763 return SLCT_UncheckedLiteral; 4764 4765 switch (E->getStmtClass()) { 4766 case Stmt::BinaryConditionalOperatorClass: 4767 case Stmt::ConditionalOperatorClass: { 4768 // The expression is a literal if both sub-expressions were, and it was 4769 // completely checked only if both sub-expressions were checked. 4770 const AbstractConditionalOperator *C = 4771 cast<AbstractConditionalOperator>(E); 4772 4773 // Determine whether it is necessary to check both sub-expressions, for 4774 // example, because the condition expression is a constant that can be 4775 // evaluated at compile time. 4776 bool CheckLeft = true, CheckRight = true; 4777 4778 bool Cond; 4779 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4780 if (Cond) 4781 CheckRight = false; 4782 else 4783 CheckLeft = false; 4784 } 4785 4786 // We need to maintain the offsets for the right and the left hand side 4787 // separately to check if every possible indexed expression is a valid 4788 // string literal. They might have different offsets for different string 4789 // literals in the end. 4790 StringLiteralCheckType Left; 4791 if (!CheckLeft) 4792 Left = SLCT_UncheckedLiteral; 4793 else { 4794 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4795 HasVAListArg, format_idx, firstDataArg, 4796 Type, CallType, InFunctionCall, 4797 CheckedVarArgs, UncoveredArg, Offset); 4798 if (Left == SLCT_NotALiteral || !CheckRight) { 4799 return Left; 4800 } 4801 } 4802 4803 StringLiteralCheckType Right = 4804 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4805 HasVAListArg, format_idx, firstDataArg, 4806 Type, CallType, InFunctionCall, CheckedVarArgs, 4807 UncoveredArg, Offset); 4808 4809 return (CheckLeft && Left < Right) ? Left : Right; 4810 } 4811 4812 case Stmt::ImplicitCastExprClass: { 4813 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4814 goto tryAgain; 4815 } 4816 4817 case Stmt::OpaqueValueExprClass: 4818 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4819 E = src; 4820 goto tryAgain; 4821 } 4822 return SLCT_NotALiteral; 4823 4824 case Stmt::PredefinedExprClass: 4825 // While __func__, etc., are technically not string literals, they 4826 // cannot contain format specifiers and thus are not a security 4827 // liability. 4828 return SLCT_UncheckedLiteral; 4829 4830 case Stmt::DeclRefExprClass: { 4831 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4832 4833 // As an exception, do not flag errors for variables binding to 4834 // const string literals. 4835 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4836 bool isConstant = false; 4837 QualType T = DR->getType(); 4838 4839 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4840 isConstant = AT->getElementType().isConstant(S.Context); 4841 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4842 isConstant = T.isConstant(S.Context) && 4843 PT->getPointeeType().isConstant(S.Context); 4844 } else if (T->isObjCObjectPointerType()) { 4845 // In ObjC, there is usually no "const ObjectPointer" type, 4846 // so don't check if the pointee type is constant. 4847 isConstant = T.isConstant(S.Context); 4848 } 4849 4850 if (isConstant) { 4851 if (const Expr *Init = VD->getAnyInitializer()) { 4852 // Look through initializers like const char c[] = { "foo" } 4853 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4854 if (InitList->isStringLiteralInit()) 4855 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4856 } 4857 return checkFormatStringExpr(S, Init, Args, 4858 HasVAListArg, format_idx, 4859 firstDataArg, Type, CallType, 4860 /*InFunctionCall*/ false, CheckedVarArgs, 4861 UncoveredArg, Offset); 4862 } 4863 } 4864 4865 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4866 // special check to see if the format string is a function parameter 4867 // of the function calling the printf function. If the function 4868 // has an attribute indicating it is a printf-like function, then we 4869 // should suppress warnings concerning non-literals being used in a call 4870 // to a vprintf function. For example: 4871 // 4872 // void 4873 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4874 // va_list ap; 4875 // va_start(ap, fmt); 4876 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4877 // ... 4878 // } 4879 if (HasVAListArg) { 4880 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4881 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4882 int PVIndex = PV->getFunctionScopeIndex() + 1; 4883 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4884 // adjust for implicit parameter 4885 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4886 if (MD->isInstance()) 4887 ++PVIndex; 4888 // We also check if the formats are compatible. 4889 // We can't pass a 'scanf' string to a 'printf' function. 4890 if (PVIndex == PVFormat->getFormatIdx() && 4891 Type == S.GetFormatStringType(PVFormat)) 4892 return SLCT_UncheckedLiteral; 4893 } 4894 } 4895 } 4896 } 4897 } 4898 4899 return SLCT_NotALiteral; 4900 } 4901 4902 case Stmt::CallExprClass: 4903 case Stmt::CXXMemberCallExprClass: { 4904 const CallExpr *CE = cast<CallExpr>(E); 4905 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4906 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4907 unsigned ArgIndex = FA->getFormatIdx(); 4908 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4909 if (MD->isInstance()) 4910 --ArgIndex; 4911 const Expr *Arg = CE->getArg(ArgIndex - 1); 4912 4913 return checkFormatStringExpr(S, Arg, Args, 4914 HasVAListArg, format_idx, firstDataArg, 4915 Type, CallType, InFunctionCall, 4916 CheckedVarArgs, UncoveredArg, Offset); 4917 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4918 unsigned BuiltinID = FD->getBuiltinID(); 4919 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4920 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4921 const Expr *Arg = CE->getArg(0); 4922 return checkFormatStringExpr(S, Arg, Args, 4923 HasVAListArg, format_idx, 4924 firstDataArg, Type, CallType, 4925 InFunctionCall, CheckedVarArgs, 4926 UncoveredArg, Offset); 4927 } 4928 } 4929 } 4930 4931 return SLCT_NotALiteral; 4932 } 4933 case Stmt::ObjCMessageExprClass: { 4934 const auto *ME = cast<ObjCMessageExpr>(E); 4935 if (const auto *ND = ME->getMethodDecl()) { 4936 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4937 unsigned ArgIndex = FA->getFormatIdx(); 4938 const Expr *Arg = ME->getArg(ArgIndex - 1); 4939 return checkFormatStringExpr( 4940 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4941 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4942 } 4943 } 4944 4945 return SLCT_NotALiteral; 4946 } 4947 case Stmt::ObjCStringLiteralClass: 4948 case Stmt::StringLiteralClass: { 4949 const StringLiteral *StrE = nullptr; 4950 4951 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4952 StrE = ObjCFExpr->getString(); 4953 else 4954 StrE = cast<StringLiteral>(E); 4955 4956 if (StrE) { 4957 if (Offset.isNegative() || Offset > StrE->getLength()) { 4958 // TODO: It would be better to have an explicit warning for out of 4959 // bounds literals. 4960 return SLCT_NotALiteral; 4961 } 4962 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4963 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4964 firstDataArg, Type, InFunctionCall, CallType, 4965 CheckedVarArgs, UncoveredArg); 4966 return SLCT_CheckedLiteral; 4967 } 4968 4969 return SLCT_NotALiteral; 4970 } 4971 case Stmt::BinaryOperatorClass: { 4972 llvm::APSInt LResult; 4973 llvm::APSInt RResult; 4974 4975 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 4976 4977 // A string literal + an int offset is still a string literal. 4978 if (BinOp->isAdditiveOp()) { 4979 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 4980 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 4981 4982 if (LIsInt != RIsInt) { 4983 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 4984 4985 if (LIsInt) { 4986 if (BinOpKind == BO_Add) { 4987 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 4988 E = BinOp->getRHS(); 4989 goto tryAgain; 4990 } 4991 } else { 4992 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 4993 E = BinOp->getLHS(); 4994 goto tryAgain; 4995 } 4996 } 4997 } 4998 4999 return SLCT_NotALiteral; 5000 } 5001 case Stmt::UnaryOperatorClass: { 5002 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 5003 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 5004 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 5005 llvm::APSInt IndexResult; 5006 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5007 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5008 E = ASE->getBase(); 5009 goto tryAgain; 5010 } 5011 } 5012 5013 return SLCT_NotALiteral; 5014 } 5015 5016 default: 5017 return SLCT_NotALiteral; 5018 } 5019 } 5020 5021 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5022 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5023 .Case("scanf", FST_Scanf) 5024 .Cases("printf", "printf0", FST_Printf) 5025 .Cases("NSString", "CFString", FST_NSString) 5026 .Case("strftime", FST_Strftime) 5027 .Case("strfmon", FST_Strfmon) 5028 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5029 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5030 .Case("os_trace", FST_OSLog) 5031 .Case("os_log", FST_OSLog) 5032 .Default(FST_Unknown); 5033 } 5034 5035 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5036 /// functions) for correct use of format strings. 5037 /// Returns true if a format string has been fully checked. 5038 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5039 ArrayRef<const Expr *> Args, 5040 bool IsCXXMember, 5041 VariadicCallType CallType, 5042 SourceLocation Loc, SourceRange Range, 5043 llvm::SmallBitVector &CheckedVarArgs) { 5044 FormatStringInfo FSI; 5045 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5046 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5047 FSI.FirstDataArg, GetFormatStringType(Format), 5048 CallType, Loc, Range, CheckedVarArgs); 5049 return false; 5050 } 5051 5052 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5053 bool HasVAListArg, unsigned format_idx, 5054 unsigned firstDataArg, FormatStringType Type, 5055 VariadicCallType CallType, 5056 SourceLocation Loc, SourceRange Range, 5057 llvm::SmallBitVector &CheckedVarArgs) { 5058 // CHECK: printf/scanf-like function is called with no format string. 5059 if (format_idx >= Args.size()) { 5060 Diag(Loc, diag::warn_missing_format_string) << Range; 5061 return false; 5062 } 5063 5064 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5065 5066 // CHECK: format string is not a string literal. 5067 // 5068 // Dynamically generated format strings are difficult to 5069 // automatically vet at compile time. Requiring that format strings 5070 // are string literals: (1) permits the checking of format strings by 5071 // the compiler and thereby (2) can practically remove the source of 5072 // many format string exploits. 5073 5074 // Format string can be either ObjC string (e.g. @"%d") or 5075 // C string (e.g. "%d") 5076 // ObjC string uses the same format specifiers as C string, so we can use 5077 // the same format string checking logic for both ObjC and C strings. 5078 UncoveredArgHandler UncoveredArg; 5079 StringLiteralCheckType CT = 5080 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5081 format_idx, firstDataArg, Type, CallType, 5082 /*IsFunctionCall*/ true, CheckedVarArgs, 5083 UncoveredArg, 5084 /*no string offset*/ llvm::APSInt(64, false) = 0); 5085 5086 // Generate a diagnostic where an uncovered argument is detected. 5087 if (UncoveredArg.hasUncoveredArg()) { 5088 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5089 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5090 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5091 } 5092 5093 if (CT != SLCT_NotALiteral) 5094 // Literal format string found, check done! 5095 return CT == SLCT_CheckedLiteral; 5096 5097 // Strftime is particular as it always uses a single 'time' argument, 5098 // so it is safe to pass a non-literal string. 5099 if (Type == FST_Strftime) 5100 return false; 5101 5102 // Do not emit diag when the string param is a macro expansion and the 5103 // format is either NSString or CFString. This is a hack to prevent 5104 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5105 // which are usually used in place of NS and CF string literals. 5106 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5107 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5108 return false; 5109 5110 // If there are no arguments specified, warn with -Wformat-security, otherwise 5111 // warn only with -Wformat-nonliteral. 5112 if (Args.size() == firstDataArg) { 5113 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5114 << OrigFormatExpr->getSourceRange(); 5115 switch (Type) { 5116 default: 5117 break; 5118 case FST_Kprintf: 5119 case FST_FreeBSDKPrintf: 5120 case FST_Printf: 5121 Diag(FormatLoc, diag::note_format_security_fixit) 5122 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5123 break; 5124 case FST_NSString: 5125 Diag(FormatLoc, diag::note_format_security_fixit) 5126 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5127 break; 5128 } 5129 } else { 5130 Diag(FormatLoc, diag::warn_format_nonliteral) 5131 << OrigFormatExpr->getSourceRange(); 5132 } 5133 return false; 5134 } 5135 5136 namespace { 5137 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5138 protected: 5139 Sema &S; 5140 const FormatStringLiteral *FExpr; 5141 const Expr *OrigFormatExpr; 5142 const Sema::FormatStringType FSType; 5143 const unsigned FirstDataArg; 5144 const unsigned NumDataArgs; 5145 const char *Beg; // Start of format string. 5146 const bool HasVAListArg; 5147 ArrayRef<const Expr *> Args; 5148 unsigned FormatIdx; 5149 llvm::SmallBitVector CoveredArgs; 5150 bool usesPositionalArgs; 5151 bool atFirstArg; 5152 bool inFunctionCall; 5153 Sema::VariadicCallType CallType; 5154 llvm::SmallBitVector &CheckedVarArgs; 5155 UncoveredArgHandler &UncoveredArg; 5156 5157 public: 5158 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5159 const Expr *origFormatExpr, 5160 const Sema::FormatStringType type, unsigned firstDataArg, 5161 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5162 ArrayRef<const Expr *> Args, unsigned formatIdx, 5163 bool inFunctionCall, Sema::VariadicCallType callType, 5164 llvm::SmallBitVector &CheckedVarArgs, 5165 UncoveredArgHandler &UncoveredArg) 5166 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5167 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5168 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5169 usesPositionalArgs(false), atFirstArg(true), 5170 inFunctionCall(inFunctionCall), CallType(callType), 5171 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5172 CoveredArgs.resize(numDataArgs); 5173 CoveredArgs.reset(); 5174 } 5175 5176 void DoneProcessing(); 5177 5178 void HandleIncompleteSpecifier(const char *startSpecifier, 5179 unsigned specifierLen) override; 5180 5181 void HandleInvalidLengthModifier( 5182 const analyze_format_string::FormatSpecifier &FS, 5183 const analyze_format_string::ConversionSpecifier &CS, 5184 const char *startSpecifier, unsigned specifierLen, 5185 unsigned DiagID); 5186 5187 void HandleNonStandardLengthModifier( 5188 const analyze_format_string::FormatSpecifier &FS, 5189 const char *startSpecifier, unsigned specifierLen); 5190 5191 void HandleNonStandardConversionSpecifier( 5192 const analyze_format_string::ConversionSpecifier &CS, 5193 const char *startSpecifier, unsigned specifierLen); 5194 5195 void HandlePosition(const char *startPos, unsigned posLen) override; 5196 5197 void HandleInvalidPosition(const char *startSpecifier, 5198 unsigned specifierLen, 5199 analyze_format_string::PositionContext p) override; 5200 5201 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5202 5203 void HandleNullChar(const char *nullCharacter) override; 5204 5205 template <typename Range> 5206 static void 5207 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5208 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5209 bool IsStringLocation, Range StringRange, 5210 ArrayRef<FixItHint> Fixit = None); 5211 5212 protected: 5213 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5214 const char *startSpec, 5215 unsigned specifierLen, 5216 const char *csStart, unsigned csLen); 5217 5218 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5219 const char *startSpec, 5220 unsigned specifierLen); 5221 5222 SourceRange getFormatStringRange(); 5223 CharSourceRange getSpecifierRange(const char *startSpecifier, 5224 unsigned specifierLen); 5225 SourceLocation getLocationOfByte(const char *x); 5226 5227 const Expr *getDataArg(unsigned i) const; 5228 5229 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5230 const analyze_format_string::ConversionSpecifier &CS, 5231 const char *startSpecifier, unsigned specifierLen, 5232 unsigned argIndex); 5233 5234 template <typename Range> 5235 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5236 bool IsStringLocation, Range StringRange, 5237 ArrayRef<FixItHint> Fixit = None); 5238 }; 5239 } // end anonymous namespace 5240 5241 SourceRange CheckFormatHandler::getFormatStringRange() { 5242 return OrigFormatExpr->getSourceRange(); 5243 } 5244 5245 CharSourceRange CheckFormatHandler:: 5246 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5247 SourceLocation Start = getLocationOfByte(startSpecifier); 5248 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5249 5250 // Advance the end SourceLocation by one due to half-open ranges. 5251 End = End.getLocWithOffset(1); 5252 5253 return CharSourceRange::getCharRange(Start, End); 5254 } 5255 5256 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5257 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5258 S.getLangOpts(), S.Context.getTargetInfo()); 5259 } 5260 5261 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5262 unsigned specifierLen){ 5263 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5264 getLocationOfByte(startSpecifier), 5265 /*IsStringLocation*/true, 5266 getSpecifierRange(startSpecifier, specifierLen)); 5267 } 5268 5269 void CheckFormatHandler::HandleInvalidLengthModifier( 5270 const analyze_format_string::FormatSpecifier &FS, 5271 const analyze_format_string::ConversionSpecifier &CS, 5272 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5273 using namespace analyze_format_string; 5274 5275 const LengthModifier &LM = FS.getLengthModifier(); 5276 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5277 5278 // See if we know how to fix this length modifier. 5279 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5280 if (FixedLM) { 5281 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5282 getLocationOfByte(LM.getStart()), 5283 /*IsStringLocation*/true, 5284 getSpecifierRange(startSpecifier, specifierLen)); 5285 5286 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5287 << FixedLM->toString() 5288 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5289 5290 } else { 5291 FixItHint Hint; 5292 if (DiagID == diag::warn_format_nonsensical_length) 5293 Hint = FixItHint::CreateRemoval(LMRange); 5294 5295 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5296 getLocationOfByte(LM.getStart()), 5297 /*IsStringLocation*/true, 5298 getSpecifierRange(startSpecifier, specifierLen), 5299 Hint); 5300 } 5301 } 5302 5303 void CheckFormatHandler::HandleNonStandardLengthModifier( 5304 const analyze_format_string::FormatSpecifier &FS, 5305 const char *startSpecifier, unsigned specifierLen) { 5306 using namespace analyze_format_string; 5307 5308 const LengthModifier &LM = FS.getLengthModifier(); 5309 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5310 5311 // See if we know how to fix this length modifier. 5312 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5313 if (FixedLM) { 5314 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5315 << LM.toString() << 0, 5316 getLocationOfByte(LM.getStart()), 5317 /*IsStringLocation*/true, 5318 getSpecifierRange(startSpecifier, specifierLen)); 5319 5320 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5321 << FixedLM->toString() 5322 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5323 5324 } else { 5325 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5326 << LM.toString() << 0, 5327 getLocationOfByte(LM.getStart()), 5328 /*IsStringLocation*/true, 5329 getSpecifierRange(startSpecifier, specifierLen)); 5330 } 5331 } 5332 5333 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5334 const analyze_format_string::ConversionSpecifier &CS, 5335 const char *startSpecifier, unsigned specifierLen) { 5336 using namespace analyze_format_string; 5337 5338 // See if we know how to fix this conversion specifier. 5339 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5340 if (FixedCS) { 5341 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5342 << CS.toString() << /*conversion specifier*/1, 5343 getLocationOfByte(CS.getStart()), 5344 /*IsStringLocation*/true, 5345 getSpecifierRange(startSpecifier, specifierLen)); 5346 5347 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5348 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5349 << FixedCS->toString() 5350 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5351 } else { 5352 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5353 << CS.toString() << /*conversion specifier*/1, 5354 getLocationOfByte(CS.getStart()), 5355 /*IsStringLocation*/true, 5356 getSpecifierRange(startSpecifier, specifierLen)); 5357 } 5358 } 5359 5360 void CheckFormatHandler::HandlePosition(const char *startPos, 5361 unsigned posLen) { 5362 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5363 getLocationOfByte(startPos), 5364 /*IsStringLocation*/true, 5365 getSpecifierRange(startPos, posLen)); 5366 } 5367 5368 void 5369 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5370 analyze_format_string::PositionContext p) { 5371 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5372 << (unsigned) p, 5373 getLocationOfByte(startPos), /*IsStringLocation*/true, 5374 getSpecifierRange(startPos, posLen)); 5375 } 5376 5377 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5378 unsigned posLen) { 5379 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5380 getLocationOfByte(startPos), 5381 /*IsStringLocation*/true, 5382 getSpecifierRange(startPos, posLen)); 5383 } 5384 5385 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5386 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5387 // The presence of a null character is likely an error. 5388 EmitFormatDiagnostic( 5389 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5390 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5391 getFormatStringRange()); 5392 } 5393 } 5394 5395 // Note that this may return NULL if there was an error parsing or building 5396 // one of the argument expressions. 5397 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5398 return Args[FirstDataArg + i]; 5399 } 5400 5401 void CheckFormatHandler::DoneProcessing() { 5402 // Does the number of data arguments exceed the number of 5403 // format conversions in the format string? 5404 if (!HasVAListArg) { 5405 // Find any arguments that weren't covered. 5406 CoveredArgs.flip(); 5407 signed notCoveredArg = CoveredArgs.find_first(); 5408 if (notCoveredArg >= 0) { 5409 assert((unsigned)notCoveredArg < NumDataArgs); 5410 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5411 } else { 5412 UncoveredArg.setAllCovered(); 5413 } 5414 } 5415 } 5416 5417 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5418 const Expr *ArgExpr) { 5419 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5420 "Invalid state"); 5421 5422 if (!ArgExpr) 5423 return; 5424 5425 SourceLocation Loc = ArgExpr->getLocStart(); 5426 5427 if (S.getSourceManager().isInSystemMacro(Loc)) 5428 return; 5429 5430 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5431 for (auto E : DiagnosticExprs) 5432 PDiag << E->getSourceRange(); 5433 5434 CheckFormatHandler::EmitFormatDiagnostic( 5435 S, IsFunctionCall, DiagnosticExprs[0], 5436 PDiag, Loc, /*IsStringLocation*/false, 5437 DiagnosticExprs[0]->getSourceRange()); 5438 } 5439 5440 bool 5441 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5442 SourceLocation Loc, 5443 const char *startSpec, 5444 unsigned specifierLen, 5445 const char *csStart, 5446 unsigned csLen) { 5447 bool keepGoing = true; 5448 if (argIndex < NumDataArgs) { 5449 // Consider the argument coverered, even though the specifier doesn't 5450 // make sense. 5451 CoveredArgs.set(argIndex); 5452 } 5453 else { 5454 // If argIndex exceeds the number of data arguments we 5455 // don't issue a warning because that is just a cascade of warnings (and 5456 // they may have intended '%%' anyway). We don't want to continue processing 5457 // the format string after this point, however, as we will like just get 5458 // gibberish when trying to match arguments. 5459 keepGoing = false; 5460 } 5461 5462 StringRef Specifier(csStart, csLen); 5463 5464 // If the specifier in non-printable, it could be the first byte of a UTF-8 5465 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5466 // hex value. 5467 std::string CodePointStr; 5468 if (!llvm::sys::locale::isPrint(*csStart)) { 5469 llvm::UTF32 CodePoint; 5470 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5471 const llvm::UTF8 *E = 5472 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5473 llvm::ConversionResult Result = 5474 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5475 5476 if (Result != llvm::conversionOK) { 5477 unsigned char FirstChar = *csStart; 5478 CodePoint = (llvm::UTF32)FirstChar; 5479 } 5480 5481 llvm::raw_string_ostream OS(CodePointStr); 5482 if (CodePoint < 256) 5483 OS << "\\x" << llvm::format("%02x", CodePoint); 5484 else if (CodePoint <= 0xFFFF) 5485 OS << "\\u" << llvm::format("%04x", CodePoint); 5486 else 5487 OS << "\\U" << llvm::format("%08x", CodePoint); 5488 OS.flush(); 5489 Specifier = CodePointStr; 5490 } 5491 5492 EmitFormatDiagnostic( 5493 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5494 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5495 5496 return keepGoing; 5497 } 5498 5499 void 5500 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5501 const char *startSpec, 5502 unsigned specifierLen) { 5503 EmitFormatDiagnostic( 5504 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5505 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5506 } 5507 5508 bool 5509 CheckFormatHandler::CheckNumArgs( 5510 const analyze_format_string::FormatSpecifier &FS, 5511 const analyze_format_string::ConversionSpecifier &CS, 5512 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5513 5514 if (argIndex >= NumDataArgs) { 5515 PartialDiagnostic PDiag = FS.usesPositionalArg() 5516 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5517 << (argIndex+1) << NumDataArgs) 5518 : S.PDiag(diag::warn_printf_insufficient_data_args); 5519 EmitFormatDiagnostic( 5520 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5521 getSpecifierRange(startSpecifier, specifierLen)); 5522 5523 // Since more arguments than conversion tokens are given, by extension 5524 // all arguments are covered, so mark this as so. 5525 UncoveredArg.setAllCovered(); 5526 return false; 5527 } 5528 return true; 5529 } 5530 5531 template<typename Range> 5532 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5533 SourceLocation Loc, 5534 bool IsStringLocation, 5535 Range StringRange, 5536 ArrayRef<FixItHint> FixIt) { 5537 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5538 Loc, IsStringLocation, StringRange, FixIt); 5539 } 5540 5541 /// \brief If the format string is not within the funcion call, emit a note 5542 /// so that the function call and string are in diagnostic messages. 5543 /// 5544 /// \param InFunctionCall if true, the format string is within the function 5545 /// call and only one diagnostic message will be produced. Otherwise, an 5546 /// extra note will be emitted pointing to location of the format string. 5547 /// 5548 /// \param ArgumentExpr the expression that is passed as the format string 5549 /// argument in the function call. Used for getting locations when two 5550 /// diagnostics are emitted. 5551 /// 5552 /// \param PDiag the callee should already have provided any strings for the 5553 /// diagnostic message. This function only adds locations and fixits 5554 /// to diagnostics. 5555 /// 5556 /// \param Loc primary location for diagnostic. If two diagnostics are 5557 /// required, one will be at Loc and a new SourceLocation will be created for 5558 /// the other one. 5559 /// 5560 /// \param IsStringLocation if true, Loc points to the format string should be 5561 /// used for the note. Otherwise, Loc points to the argument list and will 5562 /// be used with PDiag. 5563 /// 5564 /// \param StringRange some or all of the string to highlight. This is 5565 /// templated so it can accept either a CharSourceRange or a SourceRange. 5566 /// 5567 /// \param FixIt optional fix it hint for the format string. 5568 template <typename Range> 5569 void CheckFormatHandler::EmitFormatDiagnostic( 5570 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5571 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5572 Range StringRange, ArrayRef<FixItHint> FixIt) { 5573 if (InFunctionCall) { 5574 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5575 D << StringRange; 5576 D << FixIt; 5577 } else { 5578 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5579 << ArgumentExpr->getSourceRange(); 5580 5581 const Sema::SemaDiagnosticBuilder &Note = 5582 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5583 diag::note_format_string_defined); 5584 5585 Note << StringRange; 5586 Note << FixIt; 5587 } 5588 } 5589 5590 //===--- CHECK: Printf format string checking ------------------------------===// 5591 5592 namespace { 5593 class CheckPrintfHandler : public CheckFormatHandler { 5594 public: 5595 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5596 const Expr *origFormatExpr, 5597 const Sema::FormatStringType type, unsigned firstDataArg, 5598 unsigned numDataArgs, bool isObjC, const char *beg, 5599 bool hasVAListArg, ArrayRef<const Expr *> Args, 5600 unsigned formatIdx, bool inFunctionCall, 5601 Sema::VariadicCallType CallType, 5602 llvm::SmallBitVector &CheckedVarArgs, 5603 UncoveredArgHandler &UncoveredArg) 5604 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5605 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5606 inFunctionCall, CallType, CheckedVarArgs, 5607 UncoveredArg) {} 5608 5609 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5610 5611 /// Returns true if '%@' specifiers are allowed in the format string. 5612 bool allowsObjCArg() const { 5613 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5614 FSType == Sema::FST_OSTrace; 5615 } 5616 5617 bool HandleInvalidPrintfConversionSpecifier( 5618 const analyze_printf::PrintfSpecifier &FS, 5619 const char *startSpecifier, 5620 unsigned specifierLen) override; 5621 5622 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5623 const char *startSpecifier, 5624 unsigned specifierLen) override; 5625 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5626 const char *StartSpecifier, 5627 unsigned SpecifierLen, 5628 const Expr *E); 5629 5630 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5631 const char *startSpecifier, unsigned specifierLen); 5632 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5633 const analyze_printf::OptionalAmount &Amt, 5634 unsigned type, 5635 const char *startSpecifier, unsigned specifierLen); 5636 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5637 const analyze_printf::OptionalFlag &flag, 5638 const char *startSpecifier, unsigned specifierLen); 5639 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5640 const analyze_printf::OptionalFlag &ignoredFlag, 5641 const analyze_printf::OptionalFlag &flag, 5642 const char *startSpecifier, unsigned specifierLen); 5643 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5644 const Expr *E); 5645 5646 void HandleEmptyObjCModifierFlag(const char *startFlag, 5647 unsigned flagLen) override; 5648 5649 void HandleInvalidObjCModifierFlag(const char *startFlag, 5650 unsigned flagLen) override; 5651 5652 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5653 const char *flagsEnd, 5654 const char *conversionPosition) 5655 override; 5656 }; 5657 } // end anonymous namespace 5658 5659 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5660 const analyze_printf::PrintfSpecifier &FS, 5661 const char *startSpecifier, 5662 unsigned specifierLen) { 5663 const analyze_printf::PrintfConversionSpecifier &CS = 5664 FS.getConversionSpecifier(); 5665 5666 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5667 getLocationOfByte(CS.getStart()), 5668 startSpecifier, specifierLen, 5669 CS.getStart(), CS.getLength()); 5670 } 5671 5672 bool CheckPrintfHandler::HandleAmount( 5673 const analyze_format_string::OptionalAmount &Amt, 5674 unsigned k, const char *startSpecifier, 5675 unsigned specifierLen) { 5676 if (Amt.hasDataArgument()) { 5677 if (!HasVAListArg) { 5678 unsigned argIndex = Amt.getArgIndex(); 5679 if (argIndex >= NumDataArgs) { 5680 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5681 << k, 5682 getLocationOfByte(Amt.getStart()), 5683 /*IsStringLocation*/true, 5684 getSpecifierRange(startSpecifier, specifierLen)); 5685 // Don't do any more checking. We will just emit 5686 // spurious errors. 5687 return false; 5688 } 5689 5690 // Type check the data argument. It should be an 'int'. 5691 // Although not in conformance with C99, we also allow the argument to be 5692 // an 'unsigned int' as that is a reasonably safe case. GCC also 5693 // doesn't emit a warning for that case. 5694 CoveredArgs.set(argIndex); 5695 const Expr *Arg = getDataArg(argIndex); 5696 if (!Arg) 5697 return false; 5698 5699 QualType T = Arg->getType(); 5700 5701 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5702 assert(AT.isValid()); 5703 5704 if (!AT.matchesType(S.Context, T)) { 5705 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5706 << k << AT.getRepresentativeTypeName(S.Context) 5707 << T << Arg->getSourceRange(), 5708 getLocationOfByte(Amt.getStart()), 5709 /*IsStringLocation*/true, 5710 getSpecifierRange(startSpecifier, specifierLen)); 5711 // Don't do any more checking. We will just emit 5712 // spurious errors. 5713 return false; 5714 } 5715 } 5716 } 5717 return true; 5718 } 5719 5720 void CheckPrintfHandler::HandleInvalidAmount( 5721 const analyze_printf::PrintfSpecifier &FS, 5722 const analyze_printf::OptionalAmount &Amt, 5723 unsigned type, 5724 const char *startSpecifier, 5725 unsigned specifierLen) { 5726 const analyze_printf::PrintfConversionSpecifier &CS = 5727 FS.getConversionSpecifier(); 5728 5729 FixItHint fixit = 5730 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5731 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5732 Amt.getConstantLength())) 5733 : FixItHint(); 5734 5735 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5736 << type << CS.toString(), 5737 getLocationOfByte(Amt.getStart()), 5738 /*IsStringLocation*/true, 5739 getSpecifierRange(startSpecifier, specifierLen), 5740 fixit); 5741 } 5742 5743 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5744 const analyze_printf::OptionalFlag &flag, 5745 const char *startSpecifier, 5746 unsigned specifierLen) { 5747 // Warn about pointless flag with a fixit removal. 5748 const analyze_printf::PrintfConversionSpecifier &CS = 5749 FS.getConversionSpecifier(); 5750 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5751 << flag.toString() << CS.toString(), 5752 getLocationOfByte(flag.getPosition()), 5753 /*IsStringLocation*/true, 5754 getSpecifierRange(startSpecifier, specifierLen), 5755 FixItHint::CreateRemoval( 5756 getSpecifierRange(flag.getPosition(), 1))); 5757 } 5758 5759 void CheckPrintfHandler::HandleIgnoredFlag( 5760 const analyze_printf::PrintfSpecifier &FS, 5761 const analyze_printf::OptionalFlag &ignoredFlag, 5762 const analyze_printf::OptionalFlag &flag, 5763 const char *startSpecifier, 5764 unsigned specifierLen) { 5765 // Warn about ignored flag with a fixit removal. 5766 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5767 << ignoredFlag.toString() << flag.toString(), 5768 getLocationOfByte(ignoredFlag.getPosition()), 5769 /*IsStringLocation*/true, 5770 getSpecifierRange(startSpecifier, specifierLen), 5771 FixItHint::CreateRemoval( 5772 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5773 } 5774 5775 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5776 // bool IsStringLocation, Range StringRange, 5777 // ArrayRef<FixItHint> Fixit = None); 5778 5779 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5780 unsigned flagLen) { 5781 // Warn about an empty flag. 5782 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5783 getLocationOfByte(startFlag), 5784 /*IsStringLocation*/true, 5785 getSpecifierRange(startFlag, flagLen)); 5786 } 5787 5788 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5789 unsigned flagLen) { 5790 // Warn about an invalid flag. 5791 auto Range = getSpecifierRange(startFlag, flagLen); 5792 StringRef flag(startFlag, flagLen); 5793 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5794 getLocationOfByte(startFlag), 5795 /*IsStringLocation*/true, 5796 Range, FixItHint::CreateRemoval(Range)); 5797 } 5798 5799 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5800 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5801 // Warn about using '[...]' without a '@' conversion. 5802 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5803 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5804 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5805 getLocationOfByte(conversionPosition), 5806 /*IsStringLocation*/true, 5807 Range, FixItHint::CreateRemoval(Range)); 5808 } 5809 5810 // Determines if the specified is a C++ class or struct containing 5811 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5812 // "c_str()"). 5813 template<typename MemberKind> 5814 static llvm::SmallPtrSet<MemberKind*, 1> 5815 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5816 const RecordType *RT = Ty->getAs<RecordType>(); 5817 llvm::SmallPtrSet<MemberKind*, 1> Results; 5818 5819 if (!RT) 5820 return Results; 5821 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5822 if (!RD || !RD->getDefinition()) 5823 return Results; 5824 5825 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5826 Sema::LookupMemberName); 5827 R.suppressDiagnostics(); 5828 5829 // We just need to include all members of the right kind turned up by the 5830 // filter, at this point. 5831 if (S.LookupQualifiedName(R, RT->getDecl())) 5832 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5833 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5834 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5835 Results.insert(FK); 5836 } 5837 return Results; 5838 } 5839 5840 /// Check if we could call '.c_str()' on an object. 5841 /// 5842 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5843 /// allow the call, or if it would be ambiguous). 5844 bool Sema::hasCStrMethod(const Expr *E) { 5845 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5846 MethodSet Results = 5847 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5848 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5849 MI != ME; ++MI) 5850 if ((*MI)->getMinRequiredArguments() == 0) 5851 return true; 5852 return false; 5853 } 5854 5855 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5856 // better diagnostic if so. AT is assumed to be valid. 5857 // Returns true when a c_str() conversion method is found. 5858 bool CheckPrintfHandler::checkForCStrMembers( 5859 const analyze_printf::ArgType &AT, const Expr *E) { 5860 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5861 5862 MethodSet Results = 5863 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5864 5865 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5866 MI != ME; ++MI) { 5867 const CXXMethodDecl *Method = *MI; 5868 if (Method->getMinRequiredArguments() == 0 && 5869 AT.matchesType(S.Context, Method->getReturnType())) { 5870 // FIXME: Suggest parens if the expression needs them. 5871 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5872 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5873 << "c_str()" 5874 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5875 return true; 5876 } 5877 } 5878 5879 return false; 5880 } 5881 5882 bool 5883 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5884 &FS, 5885 const char *startSpecifier, 5886 unsigned specifierLen) { 5887 using namespace analyze_format_string; 5888 using namespace analyze_printf; 5889 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5890 5891 if (FS.consumesDataArgument()) { 5892 if (atFirstArg) { 5893 atFirstArg = false; 5894 usesPositionalArgs = FS.usesPositionalArg(); 5895 } 5896 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5897 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5898 startSpecifier, specifierLen); 5899 return false; 5900 } 5901 } 5902 5903 // First check if the field width, precision, and conversion specifier 5904 // have matching data arguments. 5905 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5906 startSpecifier, specifierLen)) { 5907 return false; 5908 } 5909 5910 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5911 startSpecifier, specifierLen)) { 5912 return false; 5913 } 5914 5915 if (!CS.consumesDataArgument()) { 5916 // FIXME: Technically specifying a precision or field width here 5917 // makes no sense. Worth issuing a warning at some point. 5918 return true; 5919 } 5920 5921 // Consume the argument. 5922 unsigned argIndex = FS.getArgIndex(); 5923 if (argIndex < NumDataArgs) { 5924 // The check to see if the argIndex is valid will come later. 5925 // We set the bit here because we may exit early from this 5926 // function if we encounter some other error. 5927 CoveredArgs.set(argIndex); 5928 } 5929 5930 // FreeBSD kernel extensions. 5931 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5932 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5933 // We need at least two arguments. 5934 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5935 return false; 5936 5937 // Claim the second argument. 5938 CoveredArgs.set(argIndex + 1); 5939 5940 // Type check the first argument (int for %b, pointer for %D) 5941 const Expr *Ex = getDataArg(argIndex); 5942 const analyze_printf::ArgType &AT = 5943 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5944 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5945 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5946 EmitFormatDiagnostic( 5947 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5948 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5949 << false << Ex->getSourceRange(), 5950 Ex->getLocStart(), /*IsStringLocation*/false, 5951 getSpecifierRange(startSpecifier, specifierLen)); 5952 5953 // Type check the second argument (char * for both %b and %D) 5954 Ex = getDataArg(argIndex + 1); 5955 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5956 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5957 EmitFormatDiagnostic( 5958 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5959 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5960 << false << Ex->getSourceRange(), 5961 Ex->getLocStart(), /*IsStringLocation*/false, 5962 getSpecifierRange(startSpecifier, specifierLen)); 5963 5964 return true; 5965 } 5966 5967 // Check for using an Objective-C specific conversion specifier 5968 // in a non-ObjC literal. 5969 if (!allowsObjCArg() && CS.isObjCArg()) { 5970 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5971 specifierLen); 5972 } 5973 5974 // %P can only be used with os_log. 5975 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 5976 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5977 specifierLen); 5978 } 5979 5980 // %n is not allowed with os_log. 5981 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 5982 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 5983 getLocationOfByte(CS.getStart()), 5984 /*IsStringLocation*/ false, 5985 getSpecifierRange(startSpecifier, specifierLen)); 5986 5987 return true; 5988 } 5989 5990 // Only scalars are allowed for os_trace. 5991 if (FSType == Sema::FST_OSTrace && 5992 (CS.getKind() == ConversionSpecifier::PArg || 5993 CS.getKind() == ConversionSpecifier::sArg || 5994 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 5995 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5996 specifierLen); 5997 } 5998 5999 // Check for use of public/private annotation outside of os_log(). 6000 if (FSType != Sema::FST_OSLog) { 6001 if (FS.isPublic().isSet()) { 6002 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6003 << "public", 6004 getLocationOfByte(FS.isPublic().getPosition()), 6005 /*IsStringLocation*/ false, 6006 getSpecifierRange(startSpecifier, specifierLen)); 6007 } 6008 if (FS.isPrivate().isSet()) { 6009 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6010 << "private", 6011 getLocationOfByte(FS.isPrivate().getPosition()), 6012 /*IsStringLocation*/ false, 6013 getSpecifierRange(startSpecifier, specifierLen)); 6014 } 6015 } 6016 6017 // Check for invalid use of field width 6018 if (!FS.hasValidFieldWidth()) { 6019 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6020 startSpecifier, specifierLen); 6021 } 6022 6023 // Check for invalid use of precision 6024 if (!FS.hasValidPrecision()) { 6025 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6026 startSpecifier, specifierLen); 6027 } 6028 6029 // Precision is mandatory for %P specifier. 6030 if (CS.getKind() == ConversionSpecifier::PArg && 6031 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6032 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6033 getLocationOfByte(startSpecifier), 6034 /*IsStringLocation*/ false, 6035 getSpecifierRange(startSpecifier, specifierLen)); 6036 } 6037 6038 // Check each flag does not conflict with any other component. 6039 if (!FS.hasValidThousandsGroupingPrefix()) 6040 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6041 if (!FS.hasValidLeadingZeros()) 6042 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6043 if (!FS.hasValidPlusPrefix()) 6044 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6045 if (!FS.hasValidSpacePrefix()) 6046 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6047 if (!FS.hasValidAlternativeForm()) 6048 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6049 if (!FS.hasValidLeftJustified()) 6050 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6051 6052 // Check that flags are not ignored by another flag 6053 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6054 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6055 startSpecifier, specifierLen); 6056 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6057 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6058 startSpecifier, specifierLen); 6059 6060 // Check the length modifier is valid with the given conversion specifier. 6061 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6062 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6063 diag::warn_format_nonsensical_length); 6064 else if (!FS.hasStandardLengthModifier()) 6065 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6066 else if (!FS.hasStandardLengthConversionCombination()) 6067 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6068 diag::warn_format_non_standard_conversion_spec); 6069 6070 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6071 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6072 6073 // The remaining checks depend on the data arguments. 6074 if (HasVAListArg) 6075 return true; 6076 6077 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6078 return false; 6079 6080 const Expr *Arg = getDataArg(argIndex); 6081 if (!Arg) 6082 return true; 6083 6084 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6085 } 6086 6087 static bool requiresParensToAddCast(const Expr *E) { 6088 // FIXME: We should have a general way to reason about operator 6089 // precedence and whether parens are actually needed here. 6090 // Take care of a few common cases where they aren't. 6091 const Expr *Inside = E->IgnoreImpCasts(); 6092 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6093 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6094 6095 switch (Inside->getStmtClass()) { 6096 case Stmt::ArraySubscriptExprClass: 6097 case Stmt::CallExprClass: 6098 case Stmt::CharacterLiteralClass: 6099 case Stmt::CXXBoolLiteralExprClass: 6100 case Stmt::DeclRefExprClass: 6101 case Stmt::FloatingLiteralClass: 6102 case Stmt::IntegerLiteralClass: 6103 case Stmt::MemberExprClass: 6104 case Stmt::ObjCArrayLiteralClass: 6105 case Stmt::ObjCBoolLiteralExprClass: 6106 case Stmt::ObjCBoxedExprClass: 6107 case Stmt::ObjCDictionaryLiteralClass: 6108 case Stmt::ObjCEncodeExprClass: 6109 case Stmt::ObjCIvarRefExprClass: 6110 case Stmt::ObjCMessageExprClass: 6111 case Stmt::ObjCPropertyRefExprClass: 6112 case Stmt::ObjCStringLiteralClass: 6113 case Stmt::ObjCSubscriptRefExprClass: 6114 case Stmt::ParenExprClass: 6115 case Stmt::StringLiteralClass: 6116 case Stmt::UnaryOperatorClass: 6117 return false; 6118 default: 6119 return true; 6120 } 6121 } 6122 6123 static std::pair<QualType, StringRef> 6124 shouldNotPrintDirectly(const ASTContext &Context, 6125 QualType IntendedTy, 6126 const Expr *E) { 6127 // Use a 'while' to peel off layers of typedefs. 6128 QualType TyTy = IntendedTy; 6129 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6130 StringRef Name = UserTy->getDecl()->getName(); 6131 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6132 .Case("CFIndex", Context.LongTy) 6133 .Case("NSInteger", Context.LongTy) 6134 .Case("NSUInteger", Context.UnsignedLongTy) 6135 .Case("SInt32", Context.IntTy) 6136 .Case("UInt32", Context.UnsignedIntTy) 6137 .Default(QualType()); 6138 6139 if (!CastTy.isNull()) 6140 return std::make_pair(CastTy, Name); 6141 6142 TyTy = UserTy->desugar(); 6143 } 6144 6145 // Strip parens if necessary. 6146 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6147 return shouldNotPrintDirectly(Context, 6148 PE->getSubExpr()->getType(), 6149 PE->getSubExpr()); 6150 6151 // If this is a conditional expression, then its result type is constructed 6152 // via usual arithmetic conversions and thus there might be no necessary 6153 // typedef sugar there. Recurse to operands to check for NSInteger & 6154 // Co. usage condition. 6155 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6156 QualType TrueTy, FalseTy; 6157 StringRef TrueName, FalseName; 6158 6159 std::tie(TrueTy, TrueName) = 6160 shouldNotPrintDirectly(Context, 6161 CO->getTrueExpr()->getType(), 6162 CO->getTrueExpr()); 6163 std::tie(FalseTy, FalseName) = 6164 shouldNotPrintDirectly(Context, 6165 CO->getFalseExpr()->getType(), 6166 CO->getFalseExpr()); 6167 6168 if (TrueTy == FalseTy) 6169 return std::make_pair(TrueTy, TrueName); 6170 else if (TrueTy.isNull()) 6171 return std::make_pair(FalseTy, FalseName); 6172 else if (FalseTy.isNull()) 6173 return std::make_pair(TrueTy, TrueName); 6174 } 6175 6176 return std::make_pair(QualType(), StringRef()); 6177 } 6178 6179 bool 6180 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6181 const char *StartSpecifier, 6182 unsigned SpecifierLen, 6183 const Expr *E) { 6184 using namespace analyze_format_string; 6185 using namespace analyze_printf; 6186 // Now type check the data expression that matches the 6187 // format specifier. 6188 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6189 if (!AT.isValid()) 6190 return true; 6191 6192 QualType ExprTy = E->getType(); 6193 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6194 ExprTy = TET->getUnderlyingExpr()->getType(); 6195 } 6196 6197 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6198 6199 if (match == analyze_printf::ArgType::Match) { 6200 return true; 6201 } 6202 6203 // Look through argument promotions for our error message's reported type. 6204 // This includes the integral and floating promotions, but excludes array 6205 // and function pointer decay; seeing that an argument intended to be a 6206 // string has type 'char [6]' is probably more confusing than 'char *'. 6207 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6208 if (ICE->getCastKind() == CK_IntegralCast || 6209 ICE->getCastKind() == CK_FloatingCast) { 6210 E = ICE->getSubExpr(); 6211 ExprTy = E->getType(); 6212 6213 // Check if we didn't match because of an implicit cast from a 'char' 6214 // or 'short' to an 'int'. This is done because printf is a varargs 6215 // function. 6216 if (ICE->getType() == S.Context.IntTy || 6217 ICE->getType() == S.Context.UnsignedIntTy) { 6218 // All further checking is done on the subexpression. 6219 if (AT.matchesType(S.Context, ExprTy)) 6220 return true; 6221 } 6222 } 6223 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6224 // Special case for 'a', which has type 'int' in C. 6225 // Note, however, that we do /not/ want to treat multibyte constants like 6226 // 'MooV' as characters! This form is deprecated but still exists. 6227 if (ExprTy == S.Context.IntTy) 6228 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6229 ExprTy = S.Context.CharTy; 6230 } 6231 6232 // Look through enums to their underlying type. 6233 bool IsEnum = false; 6234 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6235 ExprTy = EnumTy->getDecl()->getIntegerType(); 6236 IsEnum = true; 6237 } 6238 6239 // %C in an Objective-C context prints a unichar, not a wchar_t. 6240 // If the argument is an integer of some kind, believe the %C and suggest 6241 // a cast instead of changing the conversion specifier. 6242 QualType IntendedTy = ExprTy; 6243 if (isObjCContext() && 6244 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6245 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6246 !ExprTy->isCharType()) { 6247 // 'unichar' is defined as a typedef of unsigned short, but we should 6248 // prefer using the typedef if it is visible. 6249 IntendedTy = S.Context.UnsignedShortTy; 6250 6251 // While we are here, check if the value is an IntegerLiteral that happens 6252 // to be within the valid range. 6253 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6254 const llvm::APInt &V = IL->getValue(); 6255 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6256 return true; 6257 } 6258 6259 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6260 Sema::LookupOrdinaryName); 6261 if (S.LookupName(Result, S.getCurScope())) { 6262 NamedDecl *ND = Result.getFoundDecl(); 6263 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6264 if (TD->getUnderlyingType() == IntendedTy) 6265 IntendedTy = S.Context.getTypedefType(TD); 6266 } 6267 } 6268 } 6269 6270 // Special-case some of Darwin's platform-independence types by suggesting 6271 // casts to primitive types that are known to be large enough. 6272 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6273 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6274 QualType CastTy; 6275 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6276 if (!CastTy.isNull()) { 6277 IntendedTy = CastTy; 6278 ShouldNotPrintDirectly = true; 6279 } 6280 } 6281 6282 // We may be able to offer a FixItHint if it is a supported type. 6283 PrintfSpecifier fixedFS = FS; 6284 bool success = 6285 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6286 6287 if (success) { 6288 // Get the fix string from the fixed format specifier 6289 SmallString<16> buf; 6290 llvm::raw_svector_ostream os(buf); 6291 fixedFS.toString(os); 6292 6293 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6294 6295 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6296 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6297 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6298 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6299 } 6300 // In this case, the specifier is wrong and should be changed to match 6301 // the argument. 6302 EmitFormatDiagnostic(S.PDiag(diag) 6303 << AT.getRepresentativeTypeName(S.Context) 6304 << IntendedTy << IsEnum << E->getSourceRange(), 6305 E->getLocStart(), 6306 /*IsStringLocation*/ false, SpecRange, 6307 FixItHint::CreateReplacement(SpecRange, os.str())); 6308 } else { 6309 // The canonical type for formatting this value is different from the 6310 // actual type of the expression. (This occurs, for example, with Darwin's 6311 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6312 // should be printed as 'long' for 64-bit compatibility.) 6313 // Rather than emitting a normal format/argument mismatch, we want to 6314 // add a cast to the recommended type (and correct the format string 6315 // if necessary). 6316 SmallString<16> CastBuf; 6317 llvm::raw_svector_ostream CastFix(CastBuf); 6318 CastFix << "("; 6319 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6320 CastFix << ")"; 6321 6322 SmallVector<FixItHint,4> Hints; 6323 if (!AT.matchesType(S.Context, IntendedTy)) 6324 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6325 6326 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6327 // If there's already a cast present, just replace it. 6328 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6329 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6330 6331 } else if (!requiresParensToAddCast(E)) { 6332 // If the expression has high enough precedence, 6333 // just write the C-style cast. 6334 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6335 CastFix.str())); 6336 } else { 6337 // Otherwise, add parens around the expression as well as the cast. 6338 CastFix << "("; 6339 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6340 CastFix.str())); 6341 6342 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6343 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6344 } 6345 6346 if (ShouldNotPrintDirectly) { 6347 // The expression has a type that should not be printed directly. 6348 // We extract the name from the typedef because we don't want to show 6349 // the underlying type in the diagnostic. 6350 StringRef Name; 6351 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6352 Name = TypedefTy->getDecl()->getName(); 6353 else 6354 Name = CastTyName; 6355 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6356 << Name << IntendedTy << IsEnum 6357 << E->getSourceRange(), 6358 E->getLocStart(), /*IsStringLocation=*/false, 6359 SpecRange, Hints); 6360 } else { 6361 // In this case, the expression could be printed using a different 6362 // specifier, but we've decided that the specifier is probably correct 6363 // and we should cast instead. Just use the normal warning message. 6364 EmitFormatDiagnostic( 6365 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6366 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6367 << E->getSourceRange(), 6368 E->getLocStart(), /*IsStringLocation*/false, 6369 SpecRange, Hints); 6370 } 6371 } 6372 } else { 6373 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6374 SpecifierLen); 6375 // Since the warning for passing non-POD types to variadic functions 6376 // was deferred until now, we emit a warning for non-POD 6377 // arguments here. 6378 switch (S.isValidVarArgType(ExprTy)) { 6379 case Sema::VAK_Valid: 6380 case Sema::VAK_ValidInCXX11: { 6381 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6382 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6383 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6384 } 6385 6386 EmitFormatDiagnostic( 6387 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6388 << IsEnum << CSR << E->getSourceRange(), 6389 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6390 break; 6391 } 6392 case Sema::VAK_Undefined: 6393 case Sema::VAK_MSVCUndefined: 6394 EmitFormatDiagnostic( 6395 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6396 << S.getLangOpts().CPlusPlus11 6397 << ExprTy 6398 << CallType 6399 << AT.getRepresentativeTypeName(S.Context) 6400 << CSR 6401 << E->getSourceRange(), 6402 E->getLocStart(), /*IsStringLocation*/false, CSR); 6403 checkForCStrMembers(AT, E); 6404 break; 6405 6406 case Sema::VAK_Invalid: 6407 if (ExprTy->isObjCObjectType()) 6408 EmitFormatDiagnostic( 6409 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6410 << S.getLangOpts().CPlusPlus11 6411 << ExprTy 6412 << CallType 6413 << AT.getRepresentativeTypeName(S.Context) 6414 << CSR 6415 << E->getSourceRange(), 6416 E->getLocStart(), /*IsStringLocation*/false, CSR); 6417 else 6418 // FIXME: If this is an initializer list, suggest removing the braces 6419 // or inserting a cast to the target type. 6420 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6421 << isa<InitListExpr>(E) << ExprTy << CallType 6422 << AT.getRepresentativeTypeName(S.Context) 6423 << E->getSourceRange(); 6424 break; 6425 } 6426 6427 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6428 "format string specifier index out of range"); 6429 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6430 } 6431 6432 return true; 6433 } 6434 6435 //===--- CHECK: Scanf format string checking ------------------------------===// 6436 6437 namespace { 6438 class CheckScanfHandler : public CheckFormatHandler { 6439 public: 6440 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6441 const Expr *origFormatExpr, Sema::FormatStringType type, 6442 unsigned firstDataArg, unsigned numDataArgs, 6443 const char *beg, bool hasVAListArg, 6444 ArrayRef<const Expr *> Args, unsigned formatIdx, 6445 bool inFunctionCall, Sema::VariadicCallType CallType, 6446 llvm::SmallBitVector &CheckedVarArgs, 6447 UncoveredArgHandler &UncoveredArg) 6448 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6449 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6450 inFunctionCall, CallType, CheckedVarArgs, 6451 UncoveredArg) {} 6452 6453 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6454 const char *startSpecifier, 6455 unsigned specifierLen) override; 6456 6457 bool HandleInvalidScanfConversionSpecifier( 6458 const analyze_scanf::ScanfSpecifier &FS, 6459 const char *startSpecifier, 6460 unsigned specifierLen) override; 6461 6462 void HandleIncompleteScanList(const char *start, const char *end) override; 6463 }; 6464 } // end anonymous namespace 6465 6466 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6467 const char *end) { 6468 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6469 getLocationOfByte(end), /*IsStringLocation*/true, 6470 getSpecifierRange(start, end - start)); 6471 } 6472 6473 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6474 const analyze_scanf::ScanfSpecifier &FS, 6475 const char *startSpecifier, 6476 unsigned specifierLen) { 6477 6478 const analyze_scanf::ScanfConversionSpecifier &CS = 6479 FS.getConversionSpecifier(); 6480 6481 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6482 getLocationOfByte(CS.getStart()), 6483 startSpecifier, specifierLen, 6484 CS.getStart(), CS.getLength()); 6485 } 6486 6487 bool CheckScanfHandler::HandleScanfSpecifier( 6488 const analyze_scanf::ScanfSpecifier &FS, 6489 const char *startSpecifier, 6490 unsigned specifierLen) { 6491 using namespace analyze_scanf; 6492 using namespace analyze_format_string; 6493 6494 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6495 6496 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6497 // be used to decide if we are using positional arguments consistently. 6498 if (FS.consumesDataArgument()) { 6499 if (atFirstArg) { 6500 atFirstArg = false; 6501 usesPositionalArgs = FS.usesPositionalArg(); 6502 } 6503 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6504 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6505 startSpecifier, specifierLen); 6506 return false; 6507 } 6508 } 6509 6510 // Check if the field with is non-zero. 6511 const OptionalAmount &Amt = FS.getFieldWidth(); 6512 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6513 if (Amt.getConstantAmount() == 0) { 6514 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6515 Amt.getConstantLength()); 6516 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6517 getLocationOfByte(Amt.getStart()), 6518 /*IsStringLocation*/true, R, 6519 FixItHint::CreateRemoval(R)); 6520 } 6521 } 6522 6523 if (!FS.consumesDataArgument()) { 6524 // FIXME: Technically specifying a precision or field width here 6525 // makes no sense. Worth issuing a warning at some point. 6526 return true; 6527 } 6528 6529 // Consume the argument. 6530 unsigned argIndex = FS.getArgIndex(); 6531 if (argIndex < NumDataArgs) { 6532 // The check to see if the argIndex is valid will come later. 6533 // We set the bit here because we may exit early from this 6534 // function if we encounter some other error. 6535 CoveredArgs.set(argIndex); 6536 } 6537 6538 // Check the length modifier is valid with the given conversion specifier. 6539 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6540 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6541 diag::warn_format_nonsensical_length); 6542 else if (!FS.hasStandardLengthModifier()) 6543 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6544 else if (!FS.hasStandardLengthConversionCombination()) 6545 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6546 diag::warn_format_non_standard_conversion_spec); 6547 6548 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6549 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6550 6551 // The remaining checks depend on the data arguments. 6552 if (HasVAListArg) 6553 return true; 6554 6555 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6556 return false; 6557 6558 // Check that the argument type matches the format specifier. 6559 const Expr *Ex = getDataArg(argIndex); 6560 if (!Ex) 6561 return true; 6562 6563 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6564 6565 if (!AT.isValid()) { 6566 return true; 6567 } 6568 6569 analyze_format_string::ArgType::MatchKind match = 6570 AT.matchesType(S.Context, Ex->getType()); 6571 if (match == analyze_format_string::ArgType::Match) { 6572 return true; 6573 } 6574 6575 ScanfSpecifier fixedFS = FS; 6576 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6577 S.getLangOpts(), S.Context); 6578 6579 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6580 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6581 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6582 } 6583 6584 if (success) { 6585 // Get the fix string from the fixed format specifier. 6586 SmallString<128> buf; 6587 llvm::raw_svector_ostream os(buf); 6588 fixedFS.toString(os); 6589 6590 EmitFormatDiagnostic( 6591 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6592 << Ex->getType() << false << Ex->getSourceRange(), 6593 Ex->getLocStart(), 6594 /*IsStringLocation*/ false, 6595 getSpecifierRange(startSpecifier, specifierLen), 6596 FixItHint::CreateReplacement( 6597 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6598 } else { 6599 EmitFormatDiagnostic(S.PDiag(diag) 6600 << AT.getRepresentativeTypeName(S.Context) 6601 << Ex->getType() << false << Ex->getSourceRange(), 6602 Ex->getLocStart(), 6603 /*IsStringLocation*/ false, 6604 getSpecifierRange(startSpecifier, specifierLen)); 6605 } 6606 6607 return true; 6608 } 6609 6610 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6611 const Expr *OrigFormatExpr, 6612 ArrayRef<const Expr *> Args, 6613 bool HasVAListArg, unsigned format_idx, 6614 unsigned firstDataArg, 6615 Sema::FormatStringType Type, 6616 bool inFunctionCall, 6617 Sema::VariadicCallType CallType, 6618 llvm::SmallBitVector &CheckedVarArgs, 6619 UncoveredArgHandler &UncoveredArg) { 6620 // CHECK: is the format string a wide literal? 6621 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6622 CheckFormatHandler::EmitFormatDiagnostic( 6623 S, inFunctionCall, Args[format_idx], 6624 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6625 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6626 return; 6627 } 6628 6629 // Str - The format string. NOTE: this is NOT null-terminated! 6630 StringRef StrRef = FExpr->getString(); 6631 const char *Str = StrRef.data(); 6632 // Account for cases where the string literal is truncated in a declaration. 6633 const ConstantArrayType *T = 6634 S.Context.getAsConstantArrayType(FExpr->getType()); 6635 assert(T && "String literal not of constant array type!"); 6636 size_t TypeSize = T->getSize().getZExtValue(); 6637 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6638 const unsigned numDataArgs = Args.size() - firstDataArg; 6639 6640 // Emit a warning if the string literal is truncated and does not contain an 6641 // embedded null character. 6642 if (TypeSize <= StrRef.size() && 6643 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6644 CheckFormatHandler::EmitFormatDiagnostic( 6645 S, inFunctionCall, Args[format_idx], 6646 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6647 FExpr->getLocStart(), 6648 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6649 return; 6650 } 6651 6652 // CHECK: empty format string? 6653 if (StrLen == 0 && numDataArgs > 0) { 6654 CheckFormatHandler::EmitFormatDiagnostic( 6655 S, inFunctionCall, Args[format_idx], 6656 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6657 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6658 return; 6659 } 6660 6661 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6662 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6663 Type == Sema::FST_OSTrace) { 6664 CheckPrintfHandler H( 6665 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6666 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6667 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6668 CheckedVarArgs, UncoveredArg); 6669 6670 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6671 S.getLangOpts(), 6672 S.Context.getTargetInfo(), 6673 Type == Sema::FST_FreeBSDKPrintf)) 6674 H.DoneProcessing(); 6675 } else if (Type == Sema::FST_Scanf) { 6676 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6677 numDataArgs, Str, HasVAListArg, Args, format_idx, 6678 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6679 6680 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6681 S.getLangOpts(), 6682 S.Context.getTargetInfo())) 6683 H.DoneProcessing(); 6684 } // TODO: handle other formats 6685 } 6686 6687 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6688 // Str - The format string. NOTE: this is NOT null-terminated! 6689 StringRef StrRef = FExpr->getString(); 6690 const char *Str = StrRef.data(); 6691 // Account for cases where the string literal is truncated in a declaration. 6692 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6693 assert(T && "String literal not of constant array type!"); 6694 size_t TypeSize = T->getSize().getZExtValue(); 6695 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6696 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6697 getLangOpts(), 6698 Context.getTargetInfo()); 6699 } 6700 6701 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6702 6703 // Returns the related absolute value function that is larger, of 0 if one 6704 // does not exist. 6705 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6706 switch (AbsFunction) { 6707 default: 6708 return 0; 6709 6710 case Builtin::BI__builtin_abs: 6711 return Builtin::BI__builtin_labs; 6712 case Builtin::BI__builtin_labs: 6713 return Builtin::BI__builtin_llabs; 6714 case Builtin::BI__builtin_llabs: 6715 return 0; 6716 6717 case Builtin::BI__builtin_fabsf: 6718 return Builtin::BI__builtin_fabs; 6719 case Builtin::BI__builtin_fabs: 6720 return Builtin::BI__builtin_fabsl; 6721 case Builtin::BI__builtin_fabsl: 6722 return 0; 6723 6724 case Builtin::BI__builtin_cabsf: 6725 return Builtin::BI__builtin_cabs; 6726 case Builtin::BI__builtin_cabs: 6727 return Builtin::BI__builtin_cabsl; 6728 case Builtin::BI__builtin_cabsl: 6729 return 0; 6730 6731 case Builtin::BIabs: 6732 return Builtin::BIlabs; 6733 case Builtin::BIlabs: 6734 return Builtin::BIllabs; 6735 case Builtin::BIllabs: 6736 return 0; 6737 6738 case Builtin::BIfabsf: 6739 return Builtin::BIfabs; 6740 case Builtin::BIfabs: 6741 return Builtin::BIfabsl; 6742 case Builtin::BIfabsl: 6743 return 0; 6744 6745 case Builtin::BIcabsf: 6746 return Builtin::BIcabs; 6747 case Builtin::BIcabs: 6748 return Builtin::BIcabsl; 6749 case Builtin::BIcabsl: 6750 return 0; 6751 } 6752 } 6753 6754 // Returns the argument type of the absolute value function. 6755 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6756 unsigned AbsType) { 6757 if (AbsType == 0) 6758 return QualType(); 6759 6760 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6761 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6762 if (Error != ASTContext::GE_None) 6763 return QualType(); 6764 6765 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6766 if (!FT) 6767 return QualType(); 6768 6769 if (FT->getNumParams() != 1) 6770 return QualType(); 6771 6772 return FT->getParamType(0); 6773 } 6774 6775 // Returns the best absolute value function, or zero, based on type and 6776 // current absolute value function. 6777 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6778 unsigned AbsFunctionKind) { 6779 unsigned BestKind = 0; 6780 uint64_t ArgSize = Context.getTypeSize(ArgType); 6781 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6782 Kind = getLargerAbsoluteValueFunction(Kind)) { 6783 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6784 if (Context.getTypeSize(ParamType) >= ArgSize) { 6785 if (BestKind == 0) 6786 BestKind = Kind; 6787 else if (Context.hasSameType(ParamType, ArgType)) { 6788 BestKind = Kind; 6789 break; 6790 } 6791 } 6792 } 6793 return BestKind; 6794 } 6795 6796 enum AbsoluteValueKind { 6797 AVK_Integer, 6798 AVK_Floating, 6799 AVK_Complex 6800 }; 6801 6802 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6803 if (T->isIntegralOrEnumerationType()) 6804 return AVK_Integer; 6805 if (T->isRealFloatingType()) 6806 return AVK_Floating; 6807 if (T->isAnyComplexType()) 6808 return AVK_Complex; 6809 6810 llvm_unreachable("Type not integer, floating, or complex"); 6811 } 6812 6813 // Changes the absolute value function to a different type. Preserves whether 6814 // the function is a builtin. 6815 static unsigned changeAbsFunction(unsigned AbsKind, 6816 AbsoluteValueKind ValueKind) { 6817 switch (ValueKind) { 6818 case AVK_Integer: 6819 switch (AbsKind) { 6820 default: 6821 return 0; 6822 case Builtin::BI__builtin_fabsf: 6823 case Builtin::BI__builtin_fabs: 6824 case Builtin::BI__builtin_fabsl: 6825 case Builtin::BI__builtin_cabsf: 6826 case Builtin::BI__builtin_cabs: 6827 case Builtin::BI__builtin_cabsl: 6828 return Builtin::BI__builtin_abs; 6829 case Builtin::BIfabsf: 6830 case Builtin::BIfabs: 6831 case Builtin::BIfabsl: 6832 case Builtin::BIcabsf: 6833 case Builtin::BIcabs: 6834 case Builtin::BIcabsl: 6835 return Builtin::BIabs; 6836 } 6837 case AVK_Floating: 6838 switch (AbsKind) { 6839 default: 6840 return 0; 6841 case Builtin::BI__builtin_abs: 6842 case Builtin::BI__builtin_labs: 6843 case Builtin::BI__builtin_llabs: 6844 case Builtin::BI__builtin_cabsf: 6845 case Builtin::BI__builtin_cabs: 6846 case Builtin::BI__builtin_cabsl: 6847 return Builtin::BI__builtin_fabsf; 6848 case Builtin::BIabs: 6849 case Builtin::BIlabs: 6850 case Builtin::BIllabs: 6851 case Builtin::BIcabsf: 6852 case Builtin::BIcabs: 6853 case Builtin::BIcabsl: 6854 return Builtin::BIfabsf; 6855 } 6856 case AVK_Complex: 6857 switch (AbsKind) { 6858 default: 6859 return 0; 6860 case Builtin::BI__builtin_abs: 6861 case Builtin::BI__builtin_labs: 6862 case Builtin::BI__builtin_llabs: 6863 case Builtin::BI__builtin_fabsf: 6864 case Builtin::BI__builtin_fabs: 6865 case Builtin::BI__builtin_fabsl: 6866 return Builtin::BI__builtin_cabsf; 6867 case Builtin::BIabs: 6868 case Builtin::BIlabs: 6869 case Builtin::BIllabs: 6870 case Builtin::BIfabsf: 6871 case Builtin::BIfabs: 6872 case Builtin::BIfabsl: 6873 return Builtin::BIcabsf; 6874 } 6875 } 6876 llvm_unreachable("Unable to convert function"); 6877 } 6878 6879 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6880 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6881 if (!FnInfo) 6882 return 0; 6883 6884 switch (FDecl->getBuiltinID()) { 6885 default: 6886 return 0; 6887 case Builtin::BI__builtin_abs: 6888 case Builtin::BI__builtin_fabs: 6889 case Builtin::BI__builtin_fabsf: 6890 case Builtin::BI__builtin_fabsl: 6891 case Builtin::BI__builtin_labs: 6892 case Builtin::BI__builtin_llabs: 6893 case Builtin::BI__builtin_cabs: 6894 case Builtin::BI__builtin_cabsf: 6895 case Builtin::BI__builtin_cabsl: 6896 case Builtin::BIabs: 6897 case Builtin::BIlabs: 6898 case Builtin::BIllabs: 6899 case Builtin::BIfabs: 6900 case Builtin::BIfabsf: 6901 case Builtin::BIfabsl: 6902 case Builtin::BIcabs: 6903 case Builtin::BIcabsf: 6904 case Builtin::BIcabsl: 6905 return FDecl->getBuiltinID(); 6906 } 6907 llvm_unreachable("Unknown Builtin type"); 6908 } 6909 6910 // If the replacement is valid, emit a note with replacement function. 6911 // Additionally, suggest including the proper header if not already included. 6912 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6913 unsigned AbsKind, QualType ArgType) { 6914 bool EmitHeaderHint = true; 6915 const char *HeaderName = nullptr; 6916 const char *FunctionName = nullptr; 6917 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6918 FunctionName = "std::abs"; 6919 if (ArgType->isIntegralOrEnumerationType()) { 6920 HeaderName = "cstdlib"; 6921 } else if (ArgType->isRealFloatingType()) { 6922 HeaderName = "cmath"; 6923 } else { 6924 llvm_unreachable("Invalid Type"); 6925 } 6926 6927 // Lookup all std::abs 6928 if (NamespaceDecl *Std = S.getStdNamespace()) { 6929 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6930 R.suppressDiagnostics(); 6931 S.LookupQualifiedName(R, Std); 6932 6933 for (const auto *I : R) { 6934 const FunctionDecl *FDecl = nullptr; 6935 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6936 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6937 } else { 6938 FDecl = dyn_cast<FunctionDecl>(I); 6939 } 6940 if (!FDecl) 6941 continue; 6942 6943 // Found std::abs(), check that they are the right ones. 6944 if (FDecl->getNumParams() != 1) 6945 continue; 6946 6947 // Check that the parameter type can handle the argument. 6948 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6949 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6950 S.Context.getTypeSize(ArgType) <= 6951 S.Context.getTypeSize(ParamType)) { 6952 // Found a function, don't need the header hint. 6953 EmitHeaderHint = false; 6954 break; 6955 } 6956 } 6957 } 6958 } else { 6959 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6960 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6961 6962 if (HeaderName) { 6963 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6964 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6965 R.suppressDiagnostics(); 6966 S.LookupName(R, S.getCurScope()); 6967 6968 if (R.isSingleResult()) { 6969 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6970 if (FD && FD->getBuiltinID() == AbsKind) { 6971 EmitHeaderHint = false; 6972 } else { 6973 return; 6974 } 6975 } else if (!R.empty()) { 6976 return; 6977 } 6978 } 6979 } 6980 6981 S.Diag(Loc, diag::note_replace_abs_function) 6982 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 6983 6984 if (!HeaderName) 6985 return; 6986 6987 if (!EmitHeaderHint) 6988 return; 6989 6990 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 6991 << FunctionName; 6992 } 6993 6994 template <std::size_t StrLen> 6995 static bool IsStdFunction(const FunctionDecl *FDecl, 6996 const char (&Str)[StrLen]) { 6997 if (!FDecl) 6998 return false; 6999 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 7000 return false; 7001 if (!FDecl->isInStdNamespace()) 7002 return false; 7003 7004 return true; 7005 } 7006 7007 // Warn when using the wrong abs() function. 7008 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7009 const FunctionDecl *FDecl) { 7010 if (Call->getNumArgs() != 1) 7011 return; 7012 7013 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7014 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7015 if (AbsKind == 0 && !IsStdAbs) 7016 return; 7017 7018 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7019 QualType ParamType = Call->getArg(0)->getType(); 7020 7021 // Unsigned types cannot be negative. Suggest removing the absolute value 7022 // function call. 7023 if (ArgType->isUnsignedIntegerType()) { 7024 const char *FunctionName = 7025 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7026 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7027 Diag(Call->getExprLoc(), diag::note_remove_abs) 7028 << FunctionName 7029 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7030 return; 7031 } 7032 7033 // Taking the absolute value of a pointer is very suspicious, they probably 7034 // wanted to index into an array, dereference a pointer, call a function, etc. 7035 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7036 unsigned DiagType = 0; 7037 if (ArgType->isFunctionType()) 7038 DiagType = 1; 7039 else if (ArgType->isArrayType()) 7040 DiagType = 2; 7041 7042 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7043 return; 7044 } 7045 7046 // std::abs has overloads which prevent most of the absolute value problems 7047 // from occurring. 7048 if (IsStdAbs) 7049 return; 7050 7051 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7052 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7053 7054 // The argument and parameter are the same kind. Check if they are the right 7055 // size. 7056 if (ArgValueKind == ParamValueKind) { 7057 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7058 return; 7059 7060 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7061 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7062 << FDecl << ArgType << ParamType; 7063 7064 if (NewAbsKind == 0) 7065 return; 7066 7067 emitReplacement(*this, Call->getExprLoc(), 7068 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7069 return; 7070 } 7071 7072 // ArgValueKind != ParamValueKind 7073 // The wrong type of absolute value function was used. Attempt to find the 7074 // proper one. 7075 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7076 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7077 if (NewAbsKind == 0) 7078 return; 7079 7080 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7081 << FDecl << ParamValueKind << ArgValueKind; 7082 7083 emitReplacement(*this, Call->getExprLoc(), 7084 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7085 } 7086 7087 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7088 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7089 const FunctionDecl *FDecl) { 7090 if (!Call || !FDecl) return; 7091 7092 // Ignore template specializations and macros. 7093 if (inTemplateInstantiation()) return; 7094 if (Call->getExprLoc().isMacroID()) return; 7095 7096 // Only care about the one template argument, two function parameter std::max 7097 if (Call->getNumArgs() != 2) return; 7098 if (!IsStdFunction(FDecl, "max")) return; 7099 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7100 if (!ArgList) return; 7101 if (ArgList->size() != 1) return; 7102 7103 // Check that template type argument is unsigned integer. 7104 const auto& TA = ArgList->get(0); 7105 if (TA.getKind() != TemplateArgument::Type) return; 7106 QualType ArgType = TA.getAsType(); 7107 if (!ArgType->isUnsignedIntegerType()) return; 7108 7109 // See if either argument is a literal zero. 7110 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7111 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7112 if (!MTE) return false; 7113 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7114 if (!Num) return false; 7115 if (Num->getValue() != 0) return false; 7116 return true; 7117 }; 7118 7119 const Expr *FirstArg = Call->getArg(0); 7120 const Expr *SecondArg = Call->getArg(1); 7121 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7122 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7123 7124 // Only warn when exactly one argument is zero. 7125 if (IsFirstArgZero == IsSecondArgZero) return; 7126 7127 SourceRange FirstRange = FirstArg->getSourceRange(); 7128 SourceRange SecondRange = SecondArg->getSourceRange(); 7129 7130 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7131 7132 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7133 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7134 7135 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7136 SourceRange RemovalRange; 7137 if (IsFirstArgZero) { 7138 RemovalRange = SourceRange(FirstRange.getBegin(), 7139 SecondRange.getBegin().getLocWithOffset(-1)); 7140 } else { 7141 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7142 SecondRange.getEnd()); 7143 } 7144 7145 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7146 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7147 << FixItHint::CreateRemoval(RemovalRange); 7148 } 7149 7150 //===--- CHECK: Standard memory functions ---------------------------------===// 7151 7152 /// \brief Takes the expression passed to the size_t parameter of functions 7153 /// such as memcmp, strncat, etc and warns if it's a comparison. 7154 /// 7155 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7156 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7157 IdentifierInfo *FnName, 7158 SourceLocation FnLoc, 7159 SourceLocation RParenLoc) { 7160 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7161 if (!Size) 7162 return false; 7163 7164 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 7165 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 7166 return false; 7167 7168 SourceRange SizeRange = Size->getSourceRange(); 7169 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7170 << SizeRange << FnName; 7171 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7172 << FnName << FixItHint::CreateInsertion( 7173 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7174 << FixItHint::CreateRemoval(RParenLoc); 7175 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7176 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7177 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7178 ")"); 7179 7180 return true; 7181 } 7182 7183 /// \brief Determine whether the given type is or contains a dynamic class type 7184 /// (e.g., whether it has a vtable). 7185 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7186 bool &IsContained) { 7187 // Look through array types while ignoring qualifiers. 7188 const Type *Ty = T->getBaseElementTypeUnsafe(); 7189 IsContained = false; 7190 7191 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7192 RD = RD ? RD->getDefinition() : nullptr; 7193 if (!RD || RD->isInvalidDecl()) 7194 return nullptr; 7195 7196 if (RD->isDynamicClass()) 7197 return RD; 7198 7199 // Check all the fields. If any bases were dynamic, the class is dynamic. 7200 // It's impossible for a class to transitively contain itself by value, so 7201 // infinite recursion is impossible. 7202 for (auto *FD : RD->fields()) { 7203 bool SubContained; 7204 if (const CXXRecordDecl *ContainedRD = 7205 getContainedDynamicClass(FD->getType(), SubContained)) { 7206 IsContained = true; 7207 return ContainedRD; 7208 } 7209 } 7210 7211 return nullptr; 7212 } 7213 7214 /// \brief If E is a sizeof expression, returns its argument expression, 7215 /// otherwise returns NULL. 7216 static const Expr *getSizeOfExprArg(const Expr *E) { 7217 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7218 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7219 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 7220 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7221 7222 return nullptr; 7223 } 7224 7225 /// \brief If E is a sizeof expression, returns its argument type. 7226 static QualType getSizeOfArgType(const Expr *E) { 7227 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7228 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7229 if (SizeOf->getKind() == clang::UETT_SizeOf) 7230 return SizeOf->getTypeOfArgument(); 7231 7232 return QualType(); 7233 } 7234 7235 /// \brief Check for dangerous or invalid arguments to memset(). 7236 /// 7237 /// This issues warnings on known problematic, dangerous or unspecified 7238 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7239 /// function calls. 7240 /// 7241 /// \param Call The call expression to diagnose. 7242 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7243 unsigned BId, 7244 IdentifierInfo *FnName) { 7245 assert(BId != 0); 7246 7247 // It is possible to have a non-standard definition of memset. Validate 7248 // we have enough arguments, and if not, abort further checking. 7249 unsigned ExpectedNumArgs = 7250 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7251 if (Call->getNumArgs() < ExpectedNumArgs) 7252 return; 7253 7254 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7255 BId == Builtin::BIstrndup ? 1 : 2); 7256 unsigned LenArg = 7257 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7258 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7259 7260 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7261 Call->getLocStart(), Call->getRParenLoc())) 7262 return; 7263 7264 // We have special checking when the length is a sizeof expression. 7265 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7266 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7267 llvm::FoldingSetNodeID SizeOfArgID; 7268 7269 // Although widely used, 'bzero' is not a standard function. Be more strict 7270 // with the argument types before allowing diagnostics and only allow the 7271 // form bzero(ptr, sizeof(...)). 7272 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7273 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7274 return; 7275 7276 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7277 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7278 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7279 7280 QualType DestTy = Dest->getType(); 7281 QualType PointeeTy; 7282 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7283 PointeeTy = DestPtrTy->getPointeeType(); 7284 7285 // Never warn about void type pointers. This can be used to suppress 7286 // false positives. 7287 if (PointeeTy->isVoidType()) 7288 continue; 7289 7290 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7291 // actually comparing the expressions for equality. Because computing the 7292 // expression IDs can be expensive, we only do this if the diagnostic is 7293 // enabled. 7294 if (SizeOfArg && 7295 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7296 SizeOfArg->getExprLoc())) { 7297 // We only compute IDs for expressions if the warning is enabled, and 7298 // cache the sizeof arg's ID. 7299 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7300 SizeOfArg->Profile(SizeOfArgID, Context, true); 7301 llvm::FoldingSetNodeID DestID; 7302 Dest->Profile(DestID, Context, true); 7303 if (DestID == SizeOfArgID) { 7304 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7305 // over sizeof(src) as well. 7306 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7307 StringRef ReadableName = FnName->getName(); 7308 7309 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7310 if (UnaryOp->getOpcode() == UO_AddrOf) 7311 ActionIdx = 1; // If its an address-of operator, just remove it. 7312 if (!PointeeTy->isIncompleteType() && 7313 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7314 ActionIdx = 2; // If the pointee's size is sizeof(char), 7315 // suggest an explicit length. 7316 7317 // If the function is defined as a builtin macro, do not show macro 7318 // expansion. 7319 SourceLocation SL = SizeOfArg->getExprLoc(); 7320 SourceRange DSR = Dest->getSourceRange(); 7321 SourceRange SSR = SizeOfArg->getSourceRange(); 7322 SourceManager &SM = getSourceManager(); 7323 7324 if (SM.isMacroArgExpansion(SL)) { 7325 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7326 SL = SM.getSpellingLoc(SL); 7327 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7328 SM.getSpellingLoc(DSR.getEnd())); 7329 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7330 SM.getSpellingLoc(SSR.getEnd())); 7331 } 7332 7333 DiagRuntimeBehavior(SL, SizeOfArg, 7334 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7335 << ReadableName 7336 << PointeeTy 7337 << DestTy 7338 << DSR 7339 << SSR); 7340 DiagRuntimeBehavior(SL, SizeOfArg, 7341 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7342 << ActionIdx 7343 << SSR); 7344 7345 break; 7346 } 7347 } 7348 7349 // Also check for cases where the sizeof argument is the exact same 7350 // type as the memory argument, and where it points to a user-defined 7351 // record type. 7352 if (SizeOfArgTy != QualType()) { 7353 if (PointeeTy->isRecordType() && 7354 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7355 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7356 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7357 << FnName << SizeOfArgTy << ArgIdx 7358 << PointeeTy << Dest->getSourceRange() 7359 << LenExpr->getSourceRange()); 7360 break; 7361 } 7362 } 7363 } else if (DestTy->isArrayType()) { 7364 PointeeTy = DestTy; 7365 } 7366 7367 if (PointeeTy == QualType()) 7368 continue; 7369 7370 // Always complain about dynamic classes. 7371 bool IsContained; 7372 if (const CXXRecordDecl *ContainedRD = 7373 getContainedDynamicClass(PointeeTy, IsContained)) { 7374 7375 unsigned OperationType = 0; 7376 // "overwritten" if we're warning about the destination for any call 7377 // but memcmp; otherwise a verb appropriate to the call. 7378 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7379 if (BId == Builtin::BImemcpy) 7380 OperationType = 1; 7381 else if(BId == Builtin::BImemmove) 7382 OperationType = 2; 7383 else if (BId == Builtin::BImemcmp) 7384 OperationType = 3; 7385 } 7386 7387 DiagRuntimeBehavior( 7388 Dest->getExprLoc(), Dest, 7389 PDiag(diag::warn_dyn_class_memaccess) 7390 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7391 << FnName << IsContained << ContainedRD << OperationType 7392 << Call->getCallee()->getSourceRange()); 7393 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7394 BId != Builtin::BImemset) 7395 DiagRuntimeBehavior( 7396 Dest->getExprLoc(), Dest, 7397 PDiag(diag::warn_arc_object_memaccess) 7398 << ArgIdx << FnName << PointeeTy 7399 << Call->getCallee()->getSourceRange()); 7400 else 7401 continue; 7402 7403 DiagRuntimeBehavior( 7404 Dest->getExprLoc(), Dest, 7405 PDiag(diag::note_bad_memaccess_silence) 7406 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7407 break; 7408 } 7409 } 7410 7411 // A little helper routine: ignore addition and subtraction of integer literals. 7412 // This intentionally does not ignore all integer constant expressions because 7413 // we don't want to remove sizeof(). 7414 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7415 Ex = Ex->IgnoreParenCasts(); 7416 7417 for (;;) { 7418 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7419 if (!BO || !BO->isAdditiveOp()) 7420 break; 7421 7422 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7423 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7424 7425 if (isa<IntegerLiteral>(RHS)) 7426 Ex = LHS; 7427 else if (isa<IntegerLiteral>(LHS)) 7428 Ex = RHS; 7429 else 7430 break; 7431 } 7432 7433 return Ex; 7434 } 7435 7436 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7437 ASTContext &Context) { 7438 // Only handle constant-sized or VLAs, but not flexible members. 7439 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7440 // Only issue the FIXIT for arrays of size > 1. 7441 if (CAT->getSize().getSExtValue() <= 1) 7442 return false; 7443 } else if (!Ty->isVariableArrayType()) { 7444 return false; 7445 } 7446 return true; 7447 } 7448 7449 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7450 // be the size of the source, instead of the destination. 7451 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7452 IdentifierInfo *FnName) { 7453 7454 // Don't crash if the user has the wrong number of arguments 7455 unsigned NumArgs = Call->getNumArgs(); 7456 if ((NumArgs != 3) && (NumArgs != 4)) 7457 return; 7458 7459 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7460 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7461 const Expr *CompareWithSrc = nullptr; 7462 7463 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7464 Call->getLocStart(), Call->getRParenLoc())) 7465 return; 7466 7467 // Look for 'strlcpy(dst, x, sizeof(x))' 7468 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7469 CompareWithSrc = Ex; 7470 else { 7471 // Look for 'strlcpy(dst, x, strlen(x))' 7472 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7473 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7474 SizeCall->getNumArgs() == 1) 7475 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7476 } 7477 } 7478 7479 if (!CompareWithSrc) 7480 return; 7481 7482 // Determine if the argument to sizeof/strlen is equal to the source 7483 // argument. In principle there's all kinds of things you could do 7484 // here, for instance creating an == expression and evaluating it with 7485 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7486 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7487 if (!SrcArgDRE) 7488 return; 7489 7490 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7491 if (!CompareWithSrcDRE || 7492 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7493 return; 7494 7495 const Expr *OriginalSizeArg = Call->getArg(2); 7496 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7497 << OriginalSizeArg->getSourceRange() << FnName; 7498 7499 // Output a FIXIT hint if the destination is an array (rather than a 7500 // pointer to an array). This could be enhanced to handle some 7501 // pointers if we know the actual size, like if DstArg is 'array+2' 7502 // we could say 'sizeof(array)-2'. 7503 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7504 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7505 return; 7506 7507 SmallString<128> sizeString; 7508 llvm::raw_svector_ostream OS(sizeString); 7509 OS << "sizeof("; 7510 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7511 OS << ")"; 7512 7513 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7514 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7515 OS.str()); 7516 } 7517 7518 /// Check if two expressions refer to the same declaration. 7519 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7520 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7521 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7522 return D1->getDecl() == D2->getDecl(); 7523 return false; 7524 } 7525 7526 static const Expr *getStrlenExprArg(const Expr *E) { 7527 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7528 const FunctionDecl *FD = CE->getDirectCallee(); 7529 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7530 return nullptr; 7531 return CE->getArg(0)->IgnoreParenCasts(); 7532 } 7533 return nullptr; 7534 } 7535 7536 // Warn on anti-patterns as the 'size' argument to strncat. 7537 // The correct size argument should look like following: 7538 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7539 void Sema::CheckStrncatArguments(const CallExpr *CE, 7540 IdentifierInfo *FnName) { 7541 // Don't crash if the user has the wrong number of arguments. 7542 if (CE->getNumArgs() < 3) 7543 return; 7544 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7545 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7546 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7547 7548 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7549 CE->getRParenLoc())) 7550 return; 7551 7552 // Identify common expressions, which are wrongly used as the size argument 7553 // to strncat and may lead to buffer overflows. 7554 unsigned PatternType = 0; 7555 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7556 // - sizeof(dst) 7557 if (referToTheSameDecl(SizeOfArg, DstArg)) 7558 PatternType = 1; 7559 // - sizeof(src) 7560 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7561 PatternType = 2; 7562 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7563 if (BE->getOpcode() == BO_Sub) { 7564 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7565 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7566 // - sizeof(dst) - strlen(dst) 7567 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7568 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7569 PatternType = 1; 7570 // - sizeof(src) - (anything) 7571 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7572 PatternType = 2; 7573 } 7574 } 7575 7576 if (PatternType == 0) 7577 return; 7578 7579 // Generate the diagnostic. 7580 SourceLocation SL = LenArg->getLocStart(); 7581 SourceRange SR = LenArg->getSourceRange(); 7582 SourceManager &SM = getSourceManager(); 7583 7584 // If the function is defined as a builtin macro, do not show macro expansion. 7585 if (SM.isMacroArgExpansion(SL)) { 7586 SL = SM.getSpellingLoc(SL); 7587 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7588 SM.getSpellingLoc(SR.getEnd())); 7589 } 7590 7591 // Check if the destination is an array (rather than a pointer to an array). 7592 QualType DstTy = DstArg->getType(); 7593 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7594 Context); 7595 if (!isKnownSizeArray) { 7596 if (PatternType == 1) 7597 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7598 else 7599 Diag(SL, diag::warn_strncat_src_size) << SR; 7600 return; 7601 } 7602 7603 if (PatternType == 1) 7604 Diag(SL, diag::warn_strncat_large_size) << SR; 7605 else 7606 Diag(SL, diag::warn_strncat_src_size) << SR; 7607 7608 SmallString<128> sizeString; 7609 llvm::raw_svector_ostream OS(sizeString); 7610 OS << "sizeof("; 7611 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7612 OS << ") - "; 7613 OS << "strlen("; 7614 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7615 OS << ") - 1"; 7616 7617 Diag(SL, diag::note_strncat_wrong_size) 7618 << FixItHint::CreateReplacement(SR, OS.str()); 7619 } 7620 7621 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7622 7623 static const Expr *EvalVal(const Expr *E, 7624 SmallVectorImpl<const DeclRefExpr *> &refVars, 7625 const Decl *ParentDecl); 7626 static const Expr *EvalAddr(const Expr *E, 7627 SmallVectorImpl<const DeclRefExpr *> &refVars, 7628 const Decl *ParentDecl); 7629 7630 /// CheckReturnStackAddr - Check if a return statement returns the address 7631 /// of a stack variable. 7632 static void 7633 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7634 SourceLocation ReturnLoc) { 7635 7636 const Expr *stackE = nullptr; 7637 SmallVector<const DeclRefExpr *, 8> refVars; 7638 7639 // Perform checking for returned stack addresses, local blocks, 7640 // label addresses or references to temporaries. 7641 if (lhsType->isPointerType() || 7642 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7643 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7644 } else if (lhsType->isReferenceType()) { 7645 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7646 } 7647 7648 if (!stackE) 7649 return; // Nothing suspicious was found. 7650 7651 // Parameters are initialized in the calling scope, so taking the address 7652 // of a parameter reference doesn't need a warning. 7653 for (auto *DRE : refVars) 7654 if (isa<ParmVarDecl>(DRE->getDecl())) 7655 return; 7656 7657 SourceLocation diagLoc; 7658 SourceRange diagRange; 7659 if (refVars.empty()) { 7660 diagLoc = stackE->getLocStart(); 7661 diagRange = stackE->getSourceRange(); 7662 } else { 7663 // We followed through a reference variable. 'stackE' contains the 7664 // problematic expression but we will warn at the return statement pointing 7665 // at the reference variable. We will later display the "trail" of 7666 // reference variables using notes. 7667 diagLoc = refVars[0]->getLocStart(); 7668 diagRange = refVars[0]->getSourceRange(); 7669 } 7670 7671 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7672 // address of local var 7673 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7674 << DR->getDecl()->getDeclName() << diagRange; 7675 } else if (isa<BlockExpr>(stackE)) { // local block. 7676 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7677 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7678 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7679 } else { // local temporary. 7680 // If there is an LValue->RValue conversion, then the value of the 7681 // reference type is used, not the reference. 7682 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7683 if (ICE->getCastKind() == CK_LValueToRValue) { 7684 return; 7685 } 7686 } 7687 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7688 << lhsType->isReferenceType() << diagRange; 7689 } 7690 7691 // Display the "trail" of reference variables that we followed until we 7692 // found the problematic expression using notes. 7693 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7694 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7695 // If this var binds to another reference var, show the range of the next 7696 // var, otherwise the var binds to the problematic expression, in which case 7697 // show the range of the expression. 7698 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7699 : stackE->getSourceRange(); 7700 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7701 << VD->getDeclName() << range; 7702 } 7703 } 7704 7705 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7706 /// check if the expression in a return statement evaluates to an address 7707 /// to a location on the stack, a local block, an address of a label, or a 7708 /// reference to local temporary. The recursion is used to traverse the 7709 /// AST of the return expression, with recursion backtracking when we 7710 /// encounter a subexpression that (1) clearly does not lead to one of the 7711 /// above problematic expressions (2) is something we cannot determine leads to 7712 /// a problematic expression based on such local checking. 7713 /// 7714 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7715 /// the expression that they point to. Such variables are added to the 7716 /// 'refVars' vector so that we know what the reference variable "trail" was. 7717 /// 7718 /// EvalAddr processes expressions that are pointers that are used as 7719 /// references (and not L-values). EvalVal handles all other values. 7720 /// At the base case of the recursion is a check for the above problematic 7721 /// expressions. 7722 /// 7723 /// This implementation handles: 7724 /// 7725 /// * pointer-to-pointer casts 7726 /// * implicit conversions from array references to pointers 7727 /// * taking the address of fields 7728 /// * arbitrary interplay between "&" and "*" operators 7729 /// * pointer arithmetic from an address of a stack variable 7730 /// * taking the address of an array element where the array is on the stack 7731 static const Expr *EvalAddr(const Expr *E, 7732 SmallVectorImpl<const DeclRefExpr *> &refVars, 7733 const Decl *ParentDecl) { 7734 if (E->isTypeDependent()) 7735 return nullptr; 7736 7737 // We should only be called for evaluating pointer expressions. 7738 assert((E->getType()->isAnyPointerType() || 7739 E->getType()->isBlockPointerType() || 7740 E->getType()->isObjCQualifiedIdType()) && 7741 "EvalAddr only works on pointers"); 7742 7743 E = E->IgnoreParens(); 7744 7745 // Our "symbolic interpreter" is just a dispatch off the currently 7746 // viewed AST node. We then recursively traverse the AST by calling 7747 // EvalAddr and EvalVal appropriately. 7748 switch (E->getStmtClass()) { 7749 case Stmt::DeclRefExprClass: { 7750 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7751 7752 // If we leave the immediate function, the lifetime isn't about to end. 7753 if (DR->refersToEnclosingVariableOrCapture()) 7754 return nullptr; 7755 7756 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7757 // If this is a reference variable, follow through to the expression that 7758 // it points to. 7759 if (V->hasLocalStorage() && 7760 V->getType()->isReferenceType() && V->hasInit()) { 7761 // Add the reference variable to the "trail". 7762 refVars.push_back(DR); 7763 return EvalAddr(V->getInit(), refVars, ParentDecl); 7764 } 7765 7766 return nullptr; 7767 } 7768 7769 case Stmt::UnaryOperatorClass: { 7770 // The only unary operator that make sense to handle here 7771 // is AddrOf. All others don't make sense as pointers. 7772 const UnaryOperator *U = cast<UnaryOperator>(E); 7773 7774 if (U->getOpcode() == UO_AddrOf) 7775 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7776 return nullptr; 7777 } 7778 7779 case Stmt::BinaryOperatorClass: { 7780 // Handle pointer arithmetic. All other binary operators are not valid 7781 // in this context. 7782 const BinaryOperator *B = cast<BinaryOperator>(E); 7783 BinaryOperatorKind op = B->getOpcode(); 7784 7785 if (op != BO_Add && op != BO_Sub) 7786 return nullptr; 7787 7788 const Expr *Base = B->getLHS(); 7789 7790 // Determine which argument is the real pointer base. It could be 7791 // the RHS argument instead of the LHS. 7792 if (!Base->getType()->isPointerType()) 7793 Base = B->getRHS(); 7794 7795 assert(Base->getType()->isPointerType()); 7796 return EvalAddr(Base, refVars, ParentDecl); 7797 } 7798 7799 // For conditional operators we need to see if either the LHS or RHS are 7800 // valid DeclRefExpr*s. If one of them is valid, we return it. 7801 case Stmt::ConditionalOperatorClass: { 7802 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7803 7804 // Handle the GNU extension for missing LHS. 7805 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7806 if (const Expr *LHSExpr = C->getLHS()) { 7807 // In C++, we can have a throw-expression, which has 'void' type. 7808 if (!LHSExpr->getType()->isVoidType()) 7809 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7810 return LHS; 7811 } 7812 7813 // In C++, we can have a throw-expression, which has 'void' type. 7814 if (C->getRHS()->getType()->isVoidType()) 7815 return nullptr; 7816 7817 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7818 } 7819 7820 case Stmt::BlockExprClass: 7821 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7822 return E; // local block. 7823 return nullptr; 7824 7825 case Stmt::AddrLabelExprClass: 7826 return E; // address of label. 7827 7828 case Stmt::ExprWithCleanupsClass: 7829 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7830 ParentDecl); 7831 7832 // For casts, we need to handle conversions from arrays to 7833 // pointer values, and pointer-to-pointer conversions. 7834 case Stmt::ImplicitCastExprClass: 7835 case Stmt::CStyleCastExprClass: 7836 case Stmt::CXXFunctionalCastExprClass: 7837 case Stmt::ObjCBridgedCastExprClass: 7838 case Stmt::CXXStaticCastExprClass: 7839 case Stmt::CXXDynamicCastExprClass: 7840 case Stmt::CXXConstCastExprClass: 7841 case Stmt::CXXReinterpretCastExprClass: { 7842 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7843 switch (cast<CastExpr>(E)->getCastKind()) { 7844 case CK_LValueToRValue: 7845 case CK_NoOp: 7846 case CK_BaseToDerived: 7847 case CK_DerivedToBase: 7848 case CK_UncheckedDerivedToBase: 7849 case CK_Dynamic: 7850 case CK_CPointerToObjCPointerCast: 7851 case CK_BlockPointerToObjCPointerCast: 7852 case CK_AnyPointerToBlockPointerCast: 7853 return EvalAddr(SubExpr, refVars, ParentDecl); 7854 7855 case CK_ArrayToPointerDecay: 7856 return EvalVal(SubExpr, refVars, ParentDecl); 7857 7858 case CK_BitCast: 7859 if (SubExpr->getType()->isAnyPointerType() || 7860 SubExpr->getType()->isBlockPointerType() || 7861 SubExpr->getType()->isObjCQualifiedIdType()) 7862 return EvalAddr(SubExpr, refVars, ParentDecl); 7863 else 7864 return nullptr; 7865 7866 default: 7867 return nullptr; 7868 } 7869 } 7870 7871 case Stmt::MaterializeTemporaryExprClass: 7872 if (const Expr *Result = 7873 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7874 refVars, ParentDecl)) 7875 return Result; 7876 return E; 7877 7878 // Everything else: we simply don't reason about them. 7879 default: 7880 return nullptr; 7881 } 7882 } 7883 7884 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7885 /// See the comments for EvalAddr for more details. 7886 static const Expr *EvalVal(const Expr *E, 7887 SmallVectorImpl<const DeclRefExpr *> &refVars, 7888 const Decl *ParentDecl) { 7889 do { 7890 // We should only be called for evaluating non-pointer expressions, or 7891 // expressions with a pointer type that are not used as references but 7892 // instead 7893 // are l-values (e.g., DeclRefExpr with a pointer type). 7894 7895 // Our "symbolic interpreter" is just a dispatch off the currently 7896 // viewed AST node. We then recursively traverse the AST by calling 7897 // EvalAddr and EvalVal appropriately. 7898 7899 E = E->IgnoreParens(); 7900 switch (E->getStmtClass()) { 7901 case Stmt::ImplicitCastExprClass: { 7902 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7903 if (IE->getValueKind() == VK_LValue) { 7904 E = IE->getSubExpr(); 7905 continue; 7906 } 7907 return nullptr; 7908 } 7909 7910 case Stmt::ExprWithCleanupsClass: 7911 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7912 ParentDecl); 7913 7914 case Stmt::DeclRefExprClass: { 7915 // When we hit a DeclRefExpr we are looking at code that refers to a 7916 // variable's name. If it's not a reference variable we check if it has 7917 // local storage within the function, and if so, return the expression. 7918 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7919 7920 // If we leave the immediate function, the lifetime isn't about to end. 7921 if (DR->refersToEnclosingVariableOrCapture()) 7922 return nullptr; 7923 7924 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7925 // Check if it refers to itself, e.g. "int& i = i;". 7926 if (V == ParentDecl) 7927 return DR; 7928 7929 if (V->hasLocalStorage()) { 7930 if (!V->getType()->isReferenceType()) 7931 return DR; 7932 7933 // Reference variable, follow through to the expression that 7934 // it points to. 7935 if (V->hasInit()) { 7936 // Add the reference variable to the "trail". 7937 refVars.push_back(DR); 7938 return EvalVal(V->getInit(), refVars, V); 7939 } 7940 } 7941 } 7942 7943 return nullptr; 7944 } 7945 7946 case Stmt::UnaryOperatorClass: { 7947 // The only unary operator that make sense to handle here 7948 // is Deref. All others don't resolve to a "name." This includes 7949 // handling all sorts of rvalues passed to a unary operator. 7950 const UnaryOperator *U = cast<UnaryOperator>(E); 7951 7952 if (U->getOpcode() == UO_Deref) 7953 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7954 7955 return nullptr; 7956 } 7957 7958 case Stmt::ArraySubscriptExprClass: { 7959 // Array subscripts are potential references to data on the stack. We 7960 // retrieve the DeclRefExpr* for the array variable if it indeed 7961 // has local storage. 7962 const auto *ASE = cast<ArraySubscriptExpr>(E); 7963 if (ASE->isTypeDependent()) 7964 return nullptr; 7965 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7966 } 7967 7968 case Stmt::OMPArraySectionExprClass: { 7969 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7970 ParentDecl); 7971 } 7972 7973 case Stmt::ConditionalOperatorClass: { 7974 // For conditional operators we need to see if either the LHS or RHS are 7975 // non-NULL Expr's. If one is non-NULL, we return it. 7976 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7977 7978 // Handle the GNU extension for missing LHS. 7979 if (const Expr *LHSExpr = C->getLHS()) { 7980 // In C++, we can have a throw-expression, which has 'void' type. 7981 if (!LHSExpr->getType()->isVoidType()) 7982 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 7983 return LHS; 7984 } 7985 7986 // In C++, we can have a throw-expression, which has 'void' type. 7987 if (C->getRHS()->getType()->isVoidType()) 7988 return nullptr; 7989 7990 return EvalVal(C->getRHS(), refVars, ParentDecl); 7991 } 7992 7993 // Accesses to members are potential references to data on the stack. 7994 case Stmt::MemberExprClass: { 7995 const MemberExpr *M = cast<MemberExpr>(E); 7996 7997 // Check for indirect access. We only want direct field accesses. 7998 if (M->isArrow()) 7999 return nullptr; 8000 8001 // Check whether the member type is itself a reference, in which case 8002 // we're not going to refer to the member, but to what the member refers 8003 // to. 8004 if (M->getMemberDecl()->getType()->isReferenceType()) 8005 return nullptr; 8006 8007 return EvalVal(M->getBase(), refVars, ParentDecl); 8008 } 8009 8010 case Stmt::MaterializeTemporaryExprClass: 8011 if (const Expr *Result = 8012 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8013 refVars, ParentDecl)) 8014 return Result; 8015 return E; 8016 8017 default: 8018 // Check that we don't return or take the address of a reference to a 8019 // temporary. This is only useful in C++. 8020 if (!E->isTypeDependent() && E->isRValue()) 8021 return E; 8022 8023 // Everything else: we simply don't reason about them. 8024 return nullptr; 8025 } 8026 } while (true); 8027 } 8028 8029 void 8030 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8031 SourceLocation ReturnLoc, 8032 bool isObjCMethod, 8033 const AttrVec *Attrs, 8034 const FunctionDecl *FD) { 8035 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8036 8037 // Check if the return value is null but should not be. 8038 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8039 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8040 CheckNonNullExpr(*this, RetValExp)) 8041 Diag(ReturnLoc, diag::warn_null_ret) 8042 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8043 8044 // C++11 [basic.stc.dynamic.allocation]p4: 8045 // If an allocation function declared with a non-throwing 8046 // exception-specification fails to allocate storage, it shall return 8047 // a null pointer. Any other allocation function that fails to allocate 8048 // storage shall indicate failure only by throwing an exception [...] 8049 if (FD) { 8050 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8051 if (Op == OO_New || Op == OO_Array_New) { 8052 const FunctionProtoType *Proto 8053 = FD->getType()->castAs<FunctionProtoType>(); 8054 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 8055 CheckNonNullExpr(*this, RetValExp)) 8056 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8057 << FD << getLangOpts().CPlusPlus11; 8058 } 8059 } 8060 } 8061 8062 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8063 8064 /// Check for comparisons of floating point operands using != and ==. 8065 /// Issue a warning if these are no self-comparisons, as they are not likely 8066 /// to do what the programmer intended. 8067 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8068 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8069 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8070 8071 // Special case: check for x == x (which is OK). 8072 // Do not emit warnings for such cases. 8073 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8074 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8075 if (DRL->getDecl() == DRR->getDecl()) 8076 return; 8077 8078 // Special case: check for comparisons against literals that can be exactly 8079 // represented by APFloat. In such cases, do not emit a warning. This 8080 // is a heuristic: often comparison against such literals are used to 8081 // detect if a value in a variable has not changed. This clearly can 8082 // lead to false negatives. 8083 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8084 if (FLL->isExact()) 8085 return; 8086 } else 8087 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8088 if (FLR->isExact()) 8089 return; 8090 8091 // Check for comparisons with builtin types. 8092 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8093 if (CL->getBuiltinCallee()) 8094 return; 8095 8096 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8097 if (CR->getBuiltinCallee()) 8098 return; 8099 8100 // Emit the diagnostic. 8101 Diag(Loc, diag::warn_floatingpoint_eq) 8102 << LHS->getSourceRange() << RHS->getSourceRange(); 8103 } 8104 8105 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8106 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8107 8108 namespace { 8109 8110 /// Structure recording the 'active' range of an integer-valued 8111 /// expression. 8112 struct IntRange { 8113 /// The number of bits active in the int. 8114 unsigned Width; 8115 8116 /// True if the int is known not to have negative values. 8117 bool NonNegative; 8118 8119 IntRange(unsigned Width, bool NonNegative) 8120 : Width(Width), NonNegative(NonNegative) 8121 {} 8122 8123 /// Returns the range of the bool type. 8124 static IntRange forBoolType() { 8125 return IntRange(1, true); 8126 } 8127 8128 /// Returns the range of an opaque value of the given integral type. 8129 static IntRange forValueOfType(ASTContext &C, QualType T) { 8130 return forValueOfCanonicalType(C, 8131 T->getCanonicalTypeInternal().getTypePtr()); 8132 } 8133 8134 /// Returns the range of an opaque value of a canonical integral type. 8135 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8136 assert(T->isCanonicalUnqualified()); 8137 8138 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8139 T = VT->getElementType().getTypePtr(); 8140 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8141 T = CT->getElementType().getTypePtr(); 8142 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8143 T = AT->getValueType().getTypePtr(); 8144 8145 // For enum types, use the known bit width of the enumerators. 8146 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8147 EnumDecl *Enum = ET->getDecl(); 8148 if (!Enum->isCompleteDefinition()) 8149 return IntRange(C.getIntWidth(QualType(T, 0)), false); 8150 8151 unsigned NumPositive = Enum->getNumPositiveBits(); 8152 unsigned NumNegative = Enum->getNumNegativeBits(); 8153 8154 if (NumNegative == 0) 8155 return IntRange(NumPositive, true/*NonNegative*/); 8156 else 8157 return IntRange(std::max(NumPositive + 1, NumNegative), 8158 false/*NonNegative*/); 8159 } 8160 8161 const BuiltinType *BT = cast<BuiltinType>(T); 8162 assert(BT->isInteger()); 8163 8164 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8165 } 8166 8167 /// Returns the "target" range of a canonical integral type, i.e. 8168 /// the range of values expressible in the type. 8169 /// 8170 /// This matches forValueOfCanonicalType except that enums have the 8171 /// full range of their type, not the range of their enumerators. 8172 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8173 assert(T->isCanonicalUnqualified()); 8174 8175 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8176 T = VT->getElementType().getTypePtr(); 8177 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8178 T = CT->getElementType().getTypePtr(); 8179 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8180 T = AT->getValueType().getTypePtr(); 8181 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8182 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8183 8184 const BuiltinType *BT = cast<BuiltinType>(T); 8185 assert(BT->isInteger()); 8186 8187 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8188 } 8189 8190 /// Returns the supremum of two ranges: i.e. their conservative merge. 8191 static IntRange join(IntRange L, IntRange R) { 8192 return IntRange(std::max(L.Width, R.Width), 8193 L.NonNegative && R.NonNegative); 8194 } 8195 8196 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8197 static IntRange meet(IntRange L, IntRange R) { 8198 return IntRange(std::min(L.Width, R.Width), 8199 L.NonNegative || R.NonNegative); 8200 } 8201 }; 8202 8203 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 8204 if (value.isSigned() && value.isNegative()) 8205 return IntRange(value.getMinSignedBits(), false); 8206 8207 if (value.getBitWidth() > MaxWidth) 8208 value = value.trunc(MaxWidth); 8209 8210 // isNonNegative() just checks the sign bit without considering 8211 // signedness. 8212 return IntRange(value.getActiveBits(), true); 8213 } 8214 8215 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8216 unsigned MaxWidth) { 8217 if (result.isInt()) 8218 return GetValueRange(C, result.getInt(), MaxWidth); 8219 8220 if (result.isVector()) { 8221 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8222 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8223 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8224 R = IntRange::join(R, El); 8225 } 8226 return R; 8227 } 8228 8229 if (result.isComplexInt()) { 8230 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8231 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8232 return IntRange::join(R, I); 8233 } 8234 8235 // This can happen with lossless casts to intptr_t of "based" lvalues. 8236 // Assume it might use arbitrary bits. 8237 // FIXME: The only reason we need to pass the type in here is to get 8238 // the sign right on this one case. It would be nice if APValue 8239 // preserved this. 8240 assert(result.isLValue() || result.isAddrLabelDiff()); 8241 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8242 } 8243 8244 QualType GetExprType(const Expr *E) { 8245 QualType Ty = E->getType(); 8246 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8247 Ty = AtomicRHS->getValueType(); 8248 return Ty; 8249 } 8250 8251 /// Pseudo-evaluate the given integer expression, estimating the 8252 /// range of values it might take. 8253 /// 8254 /// \param MaxWidth - the width to which the value will be truncated 8255 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8256 E = E->IgnoreParens(); 8257 8258 // Try a full evaluation first. 8259 Expr::EvalResult result; 8260 if (E->EvaluateAsRValue(result, C)) 8261 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8262 8263 // I think we only want to look through implicit casts here; if the 8264 // user has an explicit widening cast, we should treat the value as 8265 // being of the new, wider type. 8266 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8267 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8268 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8269 8270 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8271 8272 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8273 CE->getCastKind() == CK_BooleanToSignedIntegral; 8274 8275 // Assume that non-integer casts can span the full range of the type. 8276 if (!isIntegerCast) 8277 return OutputTypeRange; 8278 8279 IntRange SubRange 8280 = GetExprRange(C, CE->getSubExpr(), 8281 std::min(MaxWidth, OutputTypeRange.Width)); 8282 8283 // Bail out if the subexpr's range is as wide as the cast type. 8284 if (SubRange.Width >= OutputTypeRange.Width) 8285 return OutputTypeRange; 8286 8287 // Otherwise, we take the smaller width, and we're non-negative if 8288 // either the output type or the subexpr is. 8289 return IntRange(SubRange.Width, 8290 SubRange.NonNegative || OutputTypeRange.NonNegative); 8291 } 8292 8293 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8294 // If we can fold the condition, just take that operand. 8295 bool CondResult; 8296 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8297 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8298 : CO->getFalseExpr(), 8299 MaxWidth); 8300 8301 // Otherwise, conservatively merge. 8302 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8303 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8304 return IntRange::join(L, R); 8305 } 8306 8307 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8308 switch (BO->getOpcode()) { 8309 8310 // Boolean-valued operations are single-bit and positive. 8311 case BO_LAnd: 8312 case BO_LOr: 8313 case BO_LT: 8314 case BO_GT: 8315 case BO_LE: 8316 case BO_GE: 8317 case BO_EQ: 8318 case BO_NE: 8319 return IntRange::forBoolType(); 8320 8321 // The type of the assignments is the type of the LHS, so the RHS 8322 // is not necessarily the same type. 8323 case BO_MulAssign: 8324 case BO_DivAssign: 8325 case BO_RemAssign: 8326 case BO_AddAssign: 8327 case BO_SubAssign: 8328 case BO_XorAssign: 8329 case BO_OrAssign: 8330 // TODO: bitfields? 8331 return IntRange::forValueOfType(C, GetExprType(E)); 8332 8333 // Simple assignments just pass through the RHS, which will have 8334 // been coerced to the LHS type. 8335 case BO_Assign: 8336 // TODO: bitfields? 8337 return GetExprRange(C, BO->getRHS(), MaxWidth); 8338 8339 // Operations with opaque sources are black-listed. 8340 case BO_PtrMemD: 8341 case BO_PtrMemI: 8342 return IntRange::forValueOfType(C, GetExprType(E)); 8343 8344 // Bitwise-and uses the *infinum* of the two source ranges. 8345 case BO_And: 8346 case BO_AndAssign: 8347 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8348 GetExprRange(C, BO->getRHS(), MaxWidth)); 8349 8350 // Left shift gets black-listed based on a judgement call. 8351 case BO_Shl: 8352 // ...except that we want to treat '1 << (blah)' as logically 8353 // positive. It's an important idiom. 8354 if (IntegerLiteral *I 8355 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8356 if (I->getValue() == 1) { 8357 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8358 return IntRange(R.Width, /*NonNegative*/ true); 8359 } 8360 } 8361 // fallthrough 8362 8363 case BO_ShlAssign: 8364 return IntRange::forValueOfType(C, GetExprType(E)); 8365 8366 // Right shift by a constant can narrow its left argument. 8367 case BO_Shr: 8368 case BO_ShrAssign: { 8369 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8370 8371 // If the shift amount is a positive constant, drop the width by 8372 // that much. 8373 llvm::APSInt shift; 8374 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8375 shift.isNonNegative()) { 8376 unsigned zext = shift.getZExtValue(); 8377 if (zext >= L.Width) 8378 L.Width = (L.NonNegative ? 0 : 1); 8379 else 8380 L.Width -= zext; 8381 } 8382 8383 return L; 8384 } 8385 8386 // Comma acts as its right operand. 8387 case BO_Comma: 8388 return GetExprRange(C, BO->getRHS(), MaxWidth); 8389 8390 // Black-list pointer subtractions. 8391 case BO_Sub: 8392 if (BO->getLHS()->getType()->isPointerType()) 8393 return IntRange::forValueOfType(C, GetExprType(E)); 8394 break; 8395 8396 // The width of a division result is mostly determined by the size 8397 // of the LHS. 8398 case BO_Div: { 8399 // Don't 'pre-truncate' the operands. 8400 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8401 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8402 8403 // If the divisor is constant, use that. 8404 llvm::APSInt divisor; 8405 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8406 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8407 if (log2 >= L.Width) 8408 L.Width = (L.NonNegative ? 0 : 1); 8409 else 8410 L.Width = std::min(L.Width - log2, MaxWidth); 8411 return L; 8412 } 8413 8414 // Otherwise, just use the LHS's width. 8415 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8416 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8417 } 8418 8419 // The result of a remainder can't be larger than the result of 8420 // either side. 8421 case BO_Rem: { 8422 // Don't 'pre-truncate' the operands. 8423 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8424 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8425 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8426 8427 IntRange meet = IntRange::meet(L, R); 8428 meet.Width = std::min(meet.Width, MaxWidth); 8429 return meet; 8430 } 8431 8432 // The default behavior is okay for these. 8433 case BO_Mul: 8434 case BO_Add: 8435 case BO_Xor: 8436 case BO_Or: 8437 break; 8438 } 8439 8440 // The default case is to treat the operation as if it were closed 8441 // on the narrowest type that encompasses both operands. 8442 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8443 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8444 return IntRange::join(L, R); 8445 } 8446 8447 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8448 switch (UO->getOpcode()) { 8449 // Boolean-valued operations are white-listed. 8450 case UO_LNot: 8451 return IntRange::forBoolType(); 8452 8453 // Operations with opaque sources are black-listed. 8454 case UO_Deref: 8455 case UO_AddrOf: // should be impossible 8456 return IntRange::forValueOfType(C, GetExprType(E)); 8457 8458 default: 8459 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8460 } 8461 } 8462 8463 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8464 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8465 8466 if (const auto *BitField = E->getSourceBitField()) 8467 return IntRange(BitField->getBitWidthValue(C), 8468 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8469 8470 return IntRange::forValueOfType(C, GetExprType(E)); 8471 } 8472 8473 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8474 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8475 } 8476 8477 /// Checks whether the given value, which currently has the given 8478 /// source semantics, has the same value when coerced through the 8479 /// target semantics. 8480 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8481 const llvm::fltSemantics &Src, 8482 const llvm::fltSemantics &Tgt) { 8483 llvm::APFloat truncated = value; 8484 8485 bool ignored; 8486 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8487 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8488 8489 return truncated.bitwiseIsEqual(value); 8490 } 8491 8492 /// Checks whether the given value, which currently has the given 8493 /// source semantics, has the same value when coerced through the 8494 /// target semantics. 8495 /// 8496 /// The value might be a vector of floats (or a complex number). 8497 bool IsSameFloatAfterCast(const APValue &value, 8498 const llvm::fltSemantics &Src, 8499 const llvm::fltSemantics &Tgt) { 8500 if (value.isFloat()) 8501 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8502 8503 if (value.isVector()) { 8504 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8505 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8506 return false; 8507 return true; 8508 } 8509 8510 assert(value.isComplexFloat()); 8511 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8512 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8513 } 8514 8515 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8516 8517 bool IsZero(Sema &S, Expr *E) { 8518 // Suppress cases where we are comparing against an enum constant. 8519 if (const DeclRefExpr *DR = 8520 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8521 if (isa<EnumConstantDecl>(DR->getDecl())) 8522 return false; 8523 8524 // Suppress cases where the '0' value is expanded from a macro. 8525 if (E->getLocStart().isMacroID()) 8526 return false; 8527 8528 llvm::APSInt Value; 8529 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 8530 } 8531 8532 bool HasEnumType(Expr *E) { 8533 // Strip off implicit integral promotions. 8534 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8535 if (ICE->getCastKind() != CK_IntegralCast && 8536 ICE->getCastKind() != CK_NoOp) 8537 break; 8538 E = ICE->getSubExpr(); 8539 } 8540 8541 return E->getType()->isEnumeralType(); 8542 } 8543 8544 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 8545 // Disable warning in template instantiations. 8546 if (S.inTemplateInstantiation()) 8547 return; 8548 8549 BinaryOperatorKind op = E->getOpcode(); 8550 if (E->isValueDependent()) 8551 return; 8552 8553 if (op == BO_LT && IsZero(S, E->getRHS())) { 8554 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8555 << "< 0" << "false" << HasEnumType(E->getLHS()) 8556 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8557 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 8558 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8559 << ">= 0" << "true" << HasEnumType(E->getLHS()) 8560 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8561 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 8562 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8563 << "0 >" << "false" << HasEnumType(E->getRHS()) 8564 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8565 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 8566 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8567 << "0 <=" << "true" << HasEnumType(E->getRHS()) 8568 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8569 } 8570 } 8571 8572 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8573 Expr *Other, const llvm::APSInt &Value, 8574 bool RhsConstant) { 8575 // Disable warning in template instantiations. 8576 if (S.inTemplateInstantiation()) 8577 return; 8578 8579 // TODO: Investigate using GetExprRange() to get tighter bounds 8580 // on the bit ranges. 8581 QualType OtherT = Other->getType(); 8582 if (const auto *AT = OtherT->getAs<AtomicType>()) 8583 OtherT = AT->getValueType(); 8584 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8585 unsigned OtherWidth = OtherRange.Width; 8586 8587 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8588 8589 // 0 values are handled later by CheckTrivialUnsignedComparison(). 8590 if ((Value == 0) && (!OtherIsBooleanType)) 8591 return; 8592 8593 BinaryOperatorKind op = E->getOpcode(); 8594 bool IsTrue = true; 8595 8596 // Used for diagnostic printout. 8597 enum { 8598 LiteralConstant = 0, 8599 CXXBoolLiteralTrue, 8600 CXXBoolLiteralFalse 8601 } LiteralOrBoolConstant = LiteralConstant; 8602 8603 if (!OtherIsBooleanType) { 8604 QualType ConstantT = Constant->getType(); 8605 QualType CommonT = E->getLHS()->getType(); 8606 8607 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8608 return; 8609 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8610 "comparison with non-integer type"); 8611 8612 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8613 bool CommonSigned = CommonT->isSignedIntegerType(); 8614 8615 bool EqualityOnly = false; 8616 8617 if (CommonSigned) { 8618 // The common type is signed, therefore no signed to unsigned conversion. 8619 if (!OtherRange.NonNegative) { 8620 // Check that the constant is representable in type OtherT. 8621 if (ConstantSigned) { 8622 if (OtherWidth >= Value.getMinSignedBits()) 8623 return; 8624 } else { // !ConstantSigned 8625 if (OtherWidth >= Value.getActiveBits() + 1) 8626 return; 8627 } 8628 } else { // !OtherSigned 8629 // Check that the constant is representable in type OtherT. 8630 // Negative values are out of range. 8631 if (ConstantSigned) { 8632 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8633 return; 8634 } else { // !ConstantSigned 8635 if (OtherWidth >= Value.getActiveBits()) 8636 return; 8637 } 8638 } 8639 } else { // !CommonSigned 8640 if (OtherRange.NonNegative) { 8641 if (OtherWidth >= Value.getActiveBits()) 8642 return; 8643 } else { // OtherSigned 8644 assert(!ConstantSigned && 8645 "Two signed types converted to unsigned types."); 8646 // Check to see if the constant is representable in OtherT. 8647 if (OtherWidth > Value.getActiveBits()) 8648 return; 8649 // Check to see if the constant is equivalent to a negative value 8650 // cast to CommonT. 8651 if (S.Context.getIntWidth(ConstantT) == 8652 S.Context.getIntWidth(CommonT) && 8653 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8654 return; 8655 // The constant value rests between values that OtherT can represent 8656 // after conversion. Relational comparison still works, but equality 8657 // comparisons will be tautological. 8658 EqualityOnly = true; 8659 } 8660 } 8661 8662 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8663 8664 if (op == BO_EQ || op == BO_NE) { 8665 IsTrue = op == BO_NE; 8666 } else if (EqualityOnly) { 8667 return; 8668 } else if (RhsConstant) { 8669 if (op == BO_GT || op == BO_GE) 8670 IsTrue = !PositiveConstant; 8671 else // op == BO_LT || op == BO_LE 8672 IsTrue = PositiveConstant; 8673 } else { 8674 if (op == BO_LT || op == BO_LE) 8675 IsTrue = !PositiveConstant; 8676 else // op == BO_GT || op == BO_GE 8677 IsTrue = PositiveConstant; 8678 } 8679 } else { 8680 // Other isKnownToHaveBooleanValue 8681 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8682 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8683 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8684 8685 static const struct LinkedConditions { 8686 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8687 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8688 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8689 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8690 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8691 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8692 8693 } TruthTable = { 8694 // Constant on LHS. | Constant on RHS. | 8695 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8696 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8697 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8698 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8699 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8700 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8701 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8702 }; 8703 8704 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8705 8706 enum ConstantValue ConstVal = Zero; 8707 if (Value.isUnsigned() || Value.isNonNegative()) { 8708 if (Value == 0) { 8709 LiteralOrBoolConstant = 8710 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8711 ConstVal = Zero; 8712 } else if (Value == 1) { 8713 LiteralOrBoolConstant = 8714 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8715 ConstVal = One; 8716 } else { 8717 LiteralOrBoolConstant = LiteralConstant; 8718 ConstVal = GT_One; 8719 } 8720 } else { 8721 ConstVal = LT_Zero; 8722 } 8723 8724 CompareBoolWithConstantResult CmpRes; 8725 8726 switch (op) { 8727 case BO_LT: 8728 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8729 break; 8730 case BO_GT: 8731 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8732 break; 8733 case BO_LE: 8734 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8735 break; 8736 case BO_GE: 8737 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8738 break; 8739 case BO_EQ: 8740 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8741 break; 8742 case BO_NE: 8743 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8744 break; 8745 default: 8746 CmpRes = Unkwn; 8747 break; 8748 } 8749 8750 if (CmpRes == AFals) { 8751 IsTrue = false; 8752 } else if (CmpRes == ATrue) { 8753 IsTrue = true; 8754 } else { 8755 return; 8756 } 8757 } 8758 8759 // If this is a comparison to an enum constant, include that 8760 // constant in the diagnostic. 8761 const EnumConstantDecl *ED = nullptr; 8762 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8763 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8764 8765 SmallString<64> PrettySourceValue; 8766 llvm::raw_svector_ostream OS(PrettySourceValue); 8767 if (ED) 8768 OS << '\'' << *ED << "' (" << Value << ")"; 8769 else 8770 OS << Value; 8771 8772 S.DiagRuntimeBehavior( 8773 E->getOperatorLoc(), E, 8774 S.PDiag(diag::warn_out_of_range_compare) 8775 << OS.str() << LiteralOrBoolConstant 8776 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8777 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8778 } 8779 8780 /// Analyze the operands of the given comparison. Implements the 8781 /// fallback case from AnalyzeComparison. 8782 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8783 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8784 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8785 } 8786 8787 /// \brief Implements -Wsign-compare. 8788 /// 8789 /// \param E the binary operator to check for warnings 8790 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8791 // The type the comparison is being performed in. 8792 QualType T = E->getLHS()->getType(); 8793 8794 // Only analyze comparison operators where both sides have been converted to 8795 // the same type. 8796 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8797 return AnalyzeImpConvsInComparison(S, E); 8798 8799 // Don't analyze value-dependent comparisons directly. 8800 if (E->isValueDependent()) 8801 return AnalyzeImpConvsInComparison(S, E); 8802 8803 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8804 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8805 8806 bool IsComparisonConstant = false; 8807 8808 // Check whether an integer constant comparison results in a value 8809 // of 'true' or 'false'. 8810 if (T->isIntegralType(S.Context)) { 8811 llvm::APSInt RHSValue; 8812 bool IsRHSIntegralLiteral = 8813 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8814 llvm::APSInt LHSValue; 8815 bool IsLHSIntegralLiteral = 8816 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8817 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8818 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8819 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8820 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8821 else 8822 IsComparisonConstant = 8823 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8824 } else if (!T->hasUnsignedIntegerRepresentation()) 8825 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8826 8827 // We don't do anything special if this isn't an unsigned integral 8828 // comparison: we're only interested in integral comparisons, and 8829 // signed comparisons only happen in cases we don't care to warn about. 8830 // 8831 // We also don't care about value-dependent expressions or expressions 8832 // whose result is a constant. 8833 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 8834 return AnalyzeImpConvsInComparison(S, E); 8835 8836 // Check to see if one of the (unmodified) operands is of different 8837 // signedness. 8838 Expr *signedOperand, *unsignedOperand; 8839 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8840 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8841 "unsigned comparison between two signed integer expressions?"); 8842 signedOperand = LHS; 8843 unsignedOperand = RHS; 8844 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8845 signedOperand = RHS; 8846 unsignedOperand = LHS; 8847 } else { 8848 CheckTrivialUnsignedComparison(S, E); 8849 return AnalyzeImpConvsInComparison(S, E); 8850 } 8851 8852 // Otherwise, calculate the effective range of the signed operand. 8853 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8854 8855 // Go ahead and analyze implicit conversions in the operands. Note 8856 // that we skip the implicit conversions on both sides. 8857 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8858 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8859 8860 // If the signed range is non-negative, -Wsign-compare won't fire, 8861 // but we should still check for comparisons which are always true 8862 // or false. 8863 if (signedRange.NonNegative) 8864 return CheckTrivialUnsignedComparison(S, E); 8865 8866 // For (in)equality comparisons, if the unsigned operand is a 8867 // constant which cannot collide with a overflowed signed operand, 8868 // then reinterpreting the signed operand as unsigned will not 8869 // change the result of the comparison. 8870 if (E->isEqualityOp()) { 8871 unsigned comparisonWidth = S.Context.getIntWidth(T); 8872 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8873 8874 // We should never be unable to prove that the unsigned operand is 8875 // non-negative. 8876 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8877 8878 if (unsignedRange.Width < comparisonWidth) 8879 return; 8880 } 8881 8882 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8883 S.PDiag(diag::warn_mixed_sign_comparison) 8884 << LHS->getType() << RHS->getType() 8885 << LHS->getSourceRange() << RHS->getSourceRange()); 8886 } 8887 8888 /// Analyzes an attempt to assign the given value to a bitfield. 8889 /// 8890 /// Returns true if there was something fishy about the attempt. 8891 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8892 SourceLocation InitLoc) { 8893 assert(Bitfield->isBitField()); 8894 if (Bitfield->isInvalidDecl()) 8895 return false; 8896 8897 // White-list bool bitfields. 8898 QualType BitfieldType = Bitfield->getType(); 8899 if (BitfieldType->isBooleanType()) 8900 return false; 8901 8902 if (BitfieldType->isEnumeralType()) { 8903 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 8904 // If the underlying enum type was not explicitly specified as an unsigned 8905 // type and the enum contain only positive values, MSVC++ will cause an 8906 // inconsistency by storing this as a signed type. 8907 if (S.getLangOpts().CPlusPlus11 && 8908 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 8909 BitfieldEnumDecl->getNumPositiveBits() > 0 && 8910 BitfieldEnumDecl->getNumNegativeBits() == 0) { 8911 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 8912 << BitfieldEnumDecl->getNameAsString(); 8913 } 8914 } 8915 8916 if (Bitfield->getType()->isBooleanType()) 8917 return false; 8918 8919 // Ignore value- or type-dependent expressions. 8920 if (Bitfield->getBitWidth()->isValueDependent() || 8921 Bitfield->getBitWidth()->isTypeDependent() || 8922 Init->isValueDependent() || 8923 Init->isTypeDependent()) 8924 return false; 8925 8926 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8927 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8928 8929 llvm::APSInt Value; 8930 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 8931 Expr::SE_AllowSideEffects)) { 8932 // The RHS is not constant. If the RHS has an enum type, make sure the 8933 // bitfield is wide enough to hold all the values of the enum without 8934 // truncation. 8935 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 8936 EnumDecl *ED = EnumTy->getDecl(); 8937 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 8938 8939 // Enum types are implicitly signed on Windows, so check if there are any 8940 // negative enumerators to see if the enum was intended to be signed or 8941 // not. 8942 bool SignedEnum = ED->getNumNegativeBits() > 0; 8943 8944 // Check for surprising sign changes when assigning enum values to a 8945 // bitfield of different signedness. If the bitfield is signed and we 8946 // have exactly the right number of bits to store this unsigned enum, 8947 // suggest changing the enum to an unsigned type. This typically happens 8948 // on Windows where unfixed enums always use an underlying type of 'int'. 8949 unsigned DiagID = 0; 8950 if (SignedEnum && !SignedBitfield) { 8951 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 8952 } else if (SignedBitfield && !SignedEnum && 8953 ED->getNumPositiveBits() == FieldWidth) { 8954 DiagID = diag::warn_signed_bitfield_enum_conversion; 8955 } 8956 8957 if (DiagID) { 8958 S.Diag(InitLoc, DiagID) << Bitfield << ED; 8959 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 8960 SourceRange TypeRange = 8961 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 8962 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 8963 << SignedEnum << TypeRange; 8964 } 8965 8966 // Compute the required bitwidth. If the enum has negative values, we need 8967 // one more bit than the normal number of positive bits to represent the 8968 // sign bit. 8969 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 8970 ED->getNumNegativeBits()) 8971 : ED->getNumPositiveBits(); 8972 8973 // Check the bitwidth. 8974 if (BitsNeeded > FieldWidth) { 8975 Expr *WidthExpr = Bitfield->getBitWidth(); 8976 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 8977 << Bitfield << ED; 8978 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 8979 << BitsNeeded << ED << WidthExpr->getSourceRange(); 8980 } 8981 } 8982 8983 return false; 8984 } 8985 8986 unsigned OriginalWidth = Value.getBitWidth(); 8987 8988 if (!Value.isSigned() || Value.isNegative()) 8989 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 8990 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 8991 OriginalWidth = Value.getMinSignedBits(); 8992 8993 if (OriginalWidth <= FieldWidth) 8994 return false; 8995 8996 // Compute the value which the bitfield will contain. 8997 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 8998 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 8999 9000 // Check whether the stored value is equal to the original value. 9001 TruncatedValue = TruncatedValue.extend(OriginalWidth); 9002 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 9003 return false; 9004 9005 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9006 // therefore don't strictly fit into a signed bitfield of width 1. 9007 if (FieldWidth == 1 && Value == 1) 9008 return false; 9009 9010 std::string PrettyValue = Value.toString(10); 9011 std::string PrettyTrunc = TruncatedValue.toString(10); 9012 9013 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9014 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9015 << Init->getSourceRange(); 9016 9017 return true; 9018 } 9019 9020 /// Analyze the given simple or compound assignment for warning-worthy 9021 /// operations. 9022 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9023 // Just recurse on the LHS. 9024 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9025 9026 // We want to recurse on the RHS as normal unless we're assigning to 9027 // a bitfield. 9028 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9029 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9030 E->getOperatorLoc())) { 9031 // Recurse, ignoring any implicit conversions on the RHS. 9032 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9033 E->getOperatorLoc()); 9034 } 9035 } 9036 9037 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9038 } 9039 9040 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9041 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9042 SourceLocation CContext, unsigned diag, 9043 bool pruneControlFlow = false) { 9044 if (pruneControlFlow) { 9045 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9046 S.PDiag(diag) 9047 << SourceType << T << E->getSourceRange() 9048 << SourceRange(CContext)); 9049 return; 9050 } 9051 S.Diag(E->getExprLoc(), diag) 9052 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9053 } 9054 9055 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9056 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 9057 unsigned diag, bool pruneControlFlow = false) { 9058 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9059 } 9060 9061 9062 /// Diagnose an implicit cast from a floating point value to an integer value. 9063 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9064 9065 SourceLocation CContext) { 9066 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9067 const bool PruneWarnings = S.inTemplateInstantiation(); 9068 9069 Expr *InnerE = E->IgnoreParenImpCasts(); 9070 // We also want to warn on, e.g., "int i = -1.234" 9071 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9072 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9073 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9074 9075 const bool IsLiteral = 9076 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9077 9078 llvm::APFloat Value(0.0); 9079 bool IsConstant = 9080 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9081 if (!IsConstant) { 9082 return DiagnoseImpCast(S, E, T, CContext, 9083 diag::warn_impcast_float_integer, PruneWarnings); 9084 } 9085 9086 bool isExact = false; 9087 9088 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9089 T->hasUnsignedIntegerRepresentation()); 9090 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 9091 &isExact) == llvm::APFloat::opOK && 9092 isExact) { 9093 if (IsLiteral) return; 9094 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9095 PruneWarnings); 9096 } 9097 9098 unsigned DiagID = 0; 9099 if (IsLiteral) { 9100 // Warn on floating point literal to integer. 9101 DiagID = diag::warn_impcast_literal_float_to_integer; 9102 } else if (IntegerValue == 0) { 9103 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9104 return DiagnoseImpCast(S, E, T, CContext, 9105 diag::warn_impcast_float_integer, PruneWarnings); 9106 } 9107 // Warn on non-zero to zero conversion. 9108 DiagID = diag::warn_impcast_float_to_integer_zero; 9109 } else { 9110 if (IntegerValue.isUnsigned()) { 9111 if (!IntegerValue.isMaxValue()) { 9112 return DiagnoseImpCast(S, E, T, CContext, 9113 diag::warn_impcast_float_integer, PruneWarnings); 9114 } 9115 } else { // IntegerValue.isSigned() 9116 if (!IntegerValue.isMaxSignedValue() && 9117 !IntegerValue.isMinSignedValue()) { 9118 return DiagnoseImpCast(S, E, T, CContext, 9119 diag::warn_impcast_float_integer, PruneWarnings); 9120 } 9121 } 9122 // Warn on evaluatable floating point expression to integer conversion. 9123 DiagID = diag::warn_impcast_float_to_integer; 9124 } 9125 9126 // FIXME: Force the precision of the source value down so we don't print 9127 // digits which are usually useless (we don't really care here if we 9128 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9129 // would automatically print the shortest representation, but it's a bit 9130 // tricky to implement. 9131 SmallString<16> PrettySourceValue; 9132 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9133 precision = (precision * 59 + 195) / 196; 9134 Value.toString(PrettySourceValue, precision); 9135 9136 SmallString<16> PrettyTargetValue; 9137 if (IsBool) 9138 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9139 else 9140 IntegerValue.toString(PrettyTargetValue); 9141 9142 if (PruneWarnings) { 9143 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9144 S.PDiag(DiagID) 9145 << E->getType() << T.getUnqualifiedType() 9146 << PrettySourceValue << PrettyTargetValue 9147 << E->getSourceRange() << SourceRange(CContext)); 9148 } else { 9149 S.Diag(E->getExprLoc(), DiagID) 9150 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9151 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9152 } 9153 } 9154 9155 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 9156 if (!Range.Width) return "0"; 9157 9158 llvm::APSInt ValueInRange = Value; 9159 ValueInRange.setIsSigned(!Range.NonNegative); 9160 ValueInRange = ValueInRange.trunc(Range.Width); 9161 return ValueInRange.toString(10); 9162 } 9163 9164 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9165 if (!isa<ImplicitCastExpr>(Ex)) 9166 return false; 9167 9168 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9169 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9170 const Type *Source = 9171 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9172 if (Target->isDependentType()) 9173 return false; 9174 9175 const BuiltinType *FloatCandidateBT = 9176 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9177 const Type *BoolCandidateType = ToBool ? Target : Source; 9178 9179 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9180 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9181 } 9182 9183 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9184 SourceLocation CC) { 9185 unsigned NumArgs = TheCall->getNumArgs(); 9186 for (unsigned i = 0; i < NumArgs; ++i) { 9187 Expr *CurrA = TheCall->getArg(i); 9188 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9189 continue; 9190 9191 bool IsSwapped = ((i > 0) && 9192 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9193 IsSwapped |= ((i < (NumArgs - 1)) && 9194 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9195 if (IsSwapped) { 9196 // Warn on this floating-point to bool conversion. 9197 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9198 CurrA->getType(), CC, 9199 diag::warn_impcast_floating_point_to_bool); 9200 } 9201 } 9202 } 9203 9204 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 9205 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9206 E->getExprLoc())) 9207 return; 9208 9209 // Don't warn on functions which have return type nullptr_t. 9210 if (isa<CallExpr>(E)) 9211 return; 9212 9213 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9214 const Expr::NullPointerConstantKind NullKind = 9215 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9216 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9217 return; 9218 9219 // Return if target type is a safe conversion. 9220 if (T->isAnyPointerType() || T->isBlockPointerType() || 9221 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9222 return; 9223 9224 SourceLocation Loc = E->getSourceRange().getBegin(); 9225 9226 // Venture through the macro stacks to get to the source of macro arguments. 9227 // The new location is a better location than the complete location that was 9228 // passed in. 9229 while (S.SourceMgr.isMacroArgExpansion(Loc)) 9230 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 9231 9232 while (S.SourceMgr.isMacroArgExpansion(CC)) 9233 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 9234 9235 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9236 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9237 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9238 Loc, S.SourceMgr, S.getLangOpts()); 9239 if (MacroName == "NULL") 9240 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 9241 } 9242 9243 // Only warn if the null and context location are in the same macro expansion. 9244 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9245 return; 9246 9247 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9248 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 9249 << FixItHint::CreateReplacement(Loc, 9250 S.getFixItZeroLiteralForType(T, Loc)); 9251 } 9252 9253 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9254 ObjCArrayLiteral *ArrayLiteral); 9255 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9256 ObjCDictionaryLiteral *DictionaryLiteral); 9257 9258 /// Check a single element within a collection literal against the 9259 /// target element type. 9260 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 9261 Expr *Element, unsigned ElementKind) { 9262 // Skip a bitcast to 'id' or qualified 'id'. 9263 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9264 if (ICE->getCastKind() == CK_BitCast && 9265 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9266 Element = ICE->getSubExpr(); 9267 } 9268 9269 QualType ElementType = Element->getType(); 9270 ExprResult ElementResult(Element); 9271 if (ElementType->getAs<ObjCObjectPointerType>() && 9272 S.CheckSingleAssignmentConstraints(TargetElementType, 9273 ElementResult, 9274 false, false) 9275 != Sema::Compatible) { 9276 S.Diag(Element->getLocStart(), 9277 diag::warn_objc_collection_literal_element) 9278 << ElementType << ElementKind << TargetElementType 9279 << Element->getSourceRange(); 9280 } 9281 9282 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9283 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9284 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9285 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9286 } 9287 9288 /// Check an Objective-C array literal being converted to the given 9289 /// target type. 9290 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9291 ObjCArrayLiteral *ArrayLiteral) { 9292 if (!S.NSArrayDecl) 9293 return; 9294 9295 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9296 if (!TargetObjCPtr) 9297 return; 9298 9299 if (TargetObjCPtr->isUnspecialized() || 9300 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9301 != S.NSArrayDecl->getCanonicalDecl()) 9302 return; 9303 9304 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9305 if (TypeArgs.size() != 1) 9306 return; 9307 9308 QualType TargetElementType = TypeArgs[0]; 9309 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9310 checkObjCCollectionLiteralElement(S, TargetElementType, 9311 ArrayLiteral->getElement(I), 9312 0); 9313 } 9314 } 9315 9316 /// Check an Objective-C dictionary literal being converted to the given 9317 /// target type. 9318 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9319 ObjCDictionaryLiteral *DictionaryLiteral) { 9320 if (!S.NSDictionaryDecl) 9321 return; 9322 9323 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9324 if (!TargetObjCPtr) 9325 return; 9326 9327 if (TargetObjCPtr->isUnspecialized() || 9328 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9329 != S.NSDictionaryDecl->getCanonicalDecl()) 9330 return; 9331 9332 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9333 if (TypeArgs.size() != 2) 9334 return; 9335 9336 QualType TargetKeyType = TypeArgs[0]; 9337 QualType TargetObjectType = TypeArgs[1]; 9338 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9339 auto Element = DictionaryLiteral->getKeyValueElement(I); 9340 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9341 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9342 } 9343 } 9344 9345 // Helper function to filter out cases for constant width constant conversion. 9346 // Don't warn on char array initialization or for non-decimal values. 9347 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9348 SourceLocation CC) { 9349 // If initializing from a constant, and the constant starts with '0', 9350 // then it is a binary, octal, or hexadecimal. Allow these constants 9351 // to fill all the bits, even if there is a sign change. 9352 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9353 const char FirstLiteralCharacter = 9354 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9355 if (FirstLiteralCharacter == '0') 9356 return false; 9357 } 9358 9359 // If the CC location points to a '{', and the type is char, then assume 9360 // assume it is an array initialization. 9361 if (CC.isValid() && T->isCharType()) { 9362 const char FirstContextCharacter = 9363 S.getSourceManager().getCharacterData(CC)[0]; 9364 if (FirstContextCharacter == '{') 9365 return false; 9366 } 9367 9368 return true; 9369 } 9370 9371 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 9372 SourceLocation CC, bool *ICContext = nullptr) { 9373 if (E->isTypeDependent() || E->isValueDependent()) return; 9374 9375 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9376 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9377 if (Source == Target) return; 9378 if (Target->isDependentType()) return; 9379 9380 // If the conversion context location is invalid don't complain. We also 9381 // don't want to emit a warning if the issue occurs from the expansion of 9382 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9383 // delay this check as long as possible. Once we detect we are in that 9384 // scenario, we just return. 9385 if (CC.isInvalid()) 9386 return; 9387 9388 // Diagnose implicit casts to bool. 9389 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9390 if (isa<StringLiteral>(E)) 9391 // Warn on string literal to bool. Checks for string literals in logical 9392 // and expressions, for instance, assert(0 && "error here"), are 9393 // prevented by a check in AnalyzeImplicitConversions(). 9394 return DiagnoseImpCast(S, E, T, CC, 9395 diag::warn_impcast_string_literal_to_bool); 9396 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9397 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9398 // This covers the literal expressions that evaluate to Objective-C 9399 // objects. 9400 return DiagnoseImpCast(S, E, T, CC, 9401 diag::warn_impcast_objective_c_literal_to_bool); 9402 } 9403 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9404 // Warn on pointer to bool conversion that is always true. 9405 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9406 SourceRange(CC)); 9407 } 9408 } 9409 9410 // Check implicit casts from Objective-C collection literals to specialized 9411 // collection types, e.g., NSArray<NSString *> *. 9412 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9413 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9414 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9415 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9416 9417 // Strip vector types. 9418 if (isa<VectorType>(Source)) { 9419 if (!isa<VectorType>(Target)) { 9420 if (S.SourceMgr.isInSystemMacro(CC)) 9421 return; 9422 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9423 } 9424 9425 // If the vector cast is cast between two vectors of the same size, it is 9426 // a bitcast, not a conversion. 9427 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9428 return; 9429 9430 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9431 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9432 } 9433 if (auto VecTy = dyn_cast<VectorType>(Target)) 9434 Target = VecTy->getElementType().getTypePtr(); 9435 9436 // Strip complex types. 9437 if (isa<ComplexType>(Source)) { 9438 if (!isa<ComplexType>(Target)) { 9439 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 9440 return; 9441 9442 return DiagnoseImpCast(S, E, T, CC, 9443 S.getLangOpts().CPlusPlus 9444 ? diag::err_impcast_complex_scalar 9445 : diag::warn_impcast_complex_scalar); 9446 } 9447 9448 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9449 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9450 } 9451 9452 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9453 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9454 9455 // If the source is floating point... 9456 if (SourceBT && SourceBT->isFloatingPoint()) { 9457 // ...and the target is floating point... 9458 if (TargetBT && TargetBT->isFloatingPoint()) { 9459 // ...then warn if we're dropping FP rank. 9460 9461 // Builtin FP kinds are ordered by increasing FP rank. 9462 if (SourceBT->getKind() > TargetBT->getKind()) { 9463 // Don't warn about float constants that are precisely 9464 // representable in the target type. 9465 Expr::EvalResult result; 9466 if (E->EvaluateAsRValue(result, S.Context)) { 9467 // Value might be a float, a float vector, or a float complex. 9468 if (IsSameFloatAfterCast(result.Val, 9469 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9470 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9471 return; 9472 } 9473 9474 if (S.SourceMgr.isInSystemMacro(CC)) 9475 return; 9476 9477 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9478 } 9479 // ... or possibly if we're increasing rank, too 9480 else if (TargetBT->getKind() > SourceBT->getKind()) { 9481 if (S.SourceMgr.isInSystemMacro(CC)) 9482 return; 9483 9484 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9485 } 9486 return; 9487 } 9488 9489 // If the target is integral, always warn. 9490 if (TargetBT && TargetBT->isInteger()) { 9491 if (S.SourceMgr.isInSystemMacro(CC)) 9492 return; 9493 9494 DiagnoseFloatingImpCast(S, E, T, CC); 9495 } 9496 9497 // Detect the case where a call result is converted from floating-point to 9498 // to bool, and the final argument to the call is converted from bool, to 9499 // discover this typo: 9500 // 9501 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9502 // 9503 // FIXME: This is an incredibly special case; is there some more general 9504 // way to detect this class of misplaced-parentheses bug? 9505 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9506 // Check last argument of function call to see if it is an 9507 // implicit cast from a type matching the type the result 9508 // is being cast to. 9509 CallExpr *CEx = cast<CallExpr>(E); 9510 if (unsigned NumArgs = CEx->getNumArgs()) { 9511 Expr *LastA = CEx->getArg(NumArgs - 1); 9512 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9513 if (isa<ImplicitCastExpr>(LastA) && 9514 InnerE->getType()->isBooleanType()) { 9515 // Warn on this floating-point to bool conversion 9516 DiagnoseImpCast(S, E, T, CC, 9517 diag::warn_impcast_floating_point_to_bool); 9518 } 9519 } 9520 } 9521 return; 9522 } 9523 9524 DiagnoseNullConversion(S, E, T, CC); 9525 9526 S.DiscardMisalignedMemberAddress(Target, E); 9527 9528 if (!Source->isIntegerType() || !Target->isIntegerType()) 9529 return; 9530 9531 // TODO: remove this early return once the false positives for constant->bool 9532 // in templates, macros, etc, are reduced or removed. 9533 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9534 return; 9535 9536 IntRange SourceRange = GetExprRange(S.Context, E); 9537 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9538 9539 if (SourceRange.Width > TargetRange.Width) { 9540 // If the source is a constant, use a default-on diagnostic. 9541 // TODO: this should happen for bitfield stores, too. 9542 llvm::APSInt Value(32); 9543 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9544 if (S.SourceMgr.isInSystemMacro(CC)) 9545 return; 9546 9547 std::string PrettySourceValue = Value.toString(10); 9548 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9549 9550 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9551 S.PDiag(diag::warn_impcast_integer_precision_constant) 9552 << PrettySourceValue << PrettyTargetValue 9553 << E->getType() << T << E->getSourceRange() 9554 << clang::SourceRange(CC)); 9555 return; 9556 } 9557 9558 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9559 if (S.SourceMgr.isInSystemMacro(CC)) 9560 return; 9561 9562 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9563 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9564 /* pruneControlFlow */ true); 9565 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9566 } 9567 9568 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9569 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9570 // Warn when doing a signed to signed conversion, warn if the positive 9571 // source value is exactly the width of the target type, which will 9572 // cause a negative value to be stored. 9573 9574 llvm::APSInt Value; 9575 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9576 !S.SourceMgr.isInSystemMacro(CC)) { 9577 if (isSameWidthConstantConversion(S, E, T, CC)) { 9578 std::string PrettySourceValue = Value.toString(10); 9579 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9580 9581 S.DiagRuntimeBehavior( 9582 E->getExprLoc(), E, 9583 S.PDiag(diag::warn_impcast_integer_precision_constant) 9584 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9585 << E->getSourceRange() << clang::SourceRange(CC)); 9586 return; 9587 } 9588 } 9589 9590 // Fall through for non-constants to give a sign conversion warning. 9591 } 9592 9593 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9594 (!TargetRange.NonNegative && SourceRange.NonNegative && 9595 SourceRange.Width == TargetRange.Width)) { 9596 if (S.SourceMgr.isInSystemMacro(CC)) 9597 return; 9598 9599 unsigned DiagID = diag::warn_impcast_integer_sign; 9600 9601 // Traditionally, gcc has warned about this under -Wsign-compare. 9602 // We also want to warn about it in -Wconversion. 9603 // So if -Wconversion is off, use a completely identical diagnostic 9604 // in the sign-compare group. 9605 // The conditional-checking code will 9606 if (ICContext) { 9607 DiagID = diag::warn_impcast_integer_sign_conditional; 9608 *ICContext = true; 9609 } 9610 9611 return DiagnoseImpCast(S, E, T, CC, DiagID); 9612 } 9613 9614 // Diagnose conversions between different enumeration types. 9615 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9616 // type, to give us better diagnostics. 9617 QualType SourceType = E->getType(); 9618 if (!S.getLangOpts().CPlusPlus) { 9619 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9620 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9621 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9622 SourceType = S.Context.getTypeDeclType(Enum); 9623 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9624 } 9625 } 9626 9627 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9628 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9629 if (SourceEnum->getDecl()->hasNameForLinkage() && 9630 TargetEnum->getDecl()->hasNameForLinkage() && 9631 SourceEnum != TargetEnum) { 9632 if (S.SourceMgr.isInSystemMacro(CC)) 9633 return; 9634 9635 return DiagnoseImpCast(S, E, SourceType, T, CC, 9636 diag::warn_impcast_different_enum_types); 9637 } 9638 } 9639 9640 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9641 SourceLocation CC, QualType T); 9642 9643 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9644 SourceLocation CC, bool &ICContext) { 9645 E = E->IgnoreParenImpCasts(); 9646 9647 if (isa<ConditionalOperator>(E)) 9648 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9649 9650 AnalyzeImplicitConversions(S, E, CC); 9651 if (E->getType() != T) 9652 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9653 } 9654 9655 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9656 SourceLocation CC, QualType T) { 9657 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9658 9659 bool Suspicious = false; 9660 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9661 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9662 9663 // If -Wconversion would have warned about either of the candidates 9664 // for a signedness conversion to the context type... 9665 if (!Suspicious) return; 9666 9667 // ...but it's currently ignored... 9668 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9669 return; 9670 9671 // ...then check whether it would have warned about either of the 9672 // candidates for a signedness conversion to the condition type. 9673 if (E->getType() == T) return; 9674 9675 Suspicious = false; 9676 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9677 E->getType(), CC, &Suspicious); 9678 if (!Suspicious) 9679 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9680 E->getType(), CC, &Suspicious); 9681 } 9682 9683 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9684 /// Input argument E is a logical expression. 9685 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9686 if (S.getLangOpts().Bool) 9687 return; 9688 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9689 } 9690 9691 /// AnalyzeImplicitConversions - Find and report any interesting 9692 /// implicit conversions in the given expression. There are a couple 9693 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9694 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9695 QualType T = OrigE->getType(); 9696 Expr *E = OrigE->IgnoreParenImpCasts(); 9697 9698 if (E->isTypeDependent() || E->isValueDependent()) 9699 return; 9700 9701 // For conditional operators, we analyze the arguments as if they 9702 // were being fed directly into the output. 9703 if (isa<ConditionalOperator>(E)) { 9704 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9705 CheckConditionalOperator(S, CO, CC, T); 9706 return; 9707 } 9708 9709 // Check implicit argument conversions for function calls. 9710 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9711 CheckImplicitArgumentConversions(S, Call, CC); 9712 9713 // Go ahead and check any implicit conversions we might have skipped. 9714 // The non-canonical typecheck is just an optimization; 9715 // CheckImplicitConversion will filter out dead implicit conversions. 9716 if (E->getType() != T) 9717 CheckImplicitConversion(S, E, T, CC); 9718 9719 // Now continue drilling into this expression. 9720 9721 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9722 // The bound subexpressions in a PseudoObjectExpr are not reachable 9723 // as transitive children. 9724 // FIXME: Use a more uniform representation for this. 9725 for (auto *SE : POE->semantics()) 9726 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9727 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9728 } 9729 9730 // Skip past explicit casts. 9731 if (isa<ExplicitCastExpr>(E)) { 9732 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9733 return AnalyzeImplicitConversions(S, E, CC); 9734 } 9735 9736 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9737 // Do a somewhat different check with comparison operators. 9738 if (BO->isComparisonOp()) 9739 return AnalyzeComparison(S, BO); 9740 9741 // And with simple assignments. 9742 if (BO->getOpcode() == BO_Assign) 9743 return AnalyzeAssignment(S, BO); 9744 } 9745 9746 // These break the otherwise-useful invariant below. Fortunately, 9747 // we don't really need to recurse into them, because any internal 9748 // expressions should have been analyzed already when they were 9749 // built into statements. 9750 if (isa<StmtExpr>(E)) return; 9751 9752 // Don't descend into unevaluated contexts. 9753 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9754 9755 // Now just recurse over the expression's children. 9756 CC = E->getExprLoc(); 9757 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9758 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9759 for (Stmt *SubStmt : E->children()) { 9760 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9761 if (!ChildExpr) 9762 continue; 9763 9764 if (IsLogicalAndOperator && 9765 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9766 // Ignore checking string literals that are in logical and operators. 9767 // This is a common pattern for asserts. 9768 continue; 9769 AnalyzeImplicitConversions(S, ChildExpr, CC); 9770 } 9771 9772 if (BO && BO->isLogicalOp()) { 9773 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9774 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9775 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9776 9777 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9778 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9779 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9780 } 9781 9782 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9783 if (U->getOpcode() == UO_LNot) 9784 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9785 } 9786 9787 } // end anonymous namespace 9788 9789 /// Diagnose integer type and any valid implicit convertion to it. 9790 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 9791 // Taking into account implicit conversions, 9792 // allow any integer. 9793 if (!E->getType()->isIntegerType()) { 9794 S.Diag(E->getLocStart(), 9795 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9796 return true; 9797 } 9798 // Potentially emit standard warnings for implicit conversions if enabled 9799 // using -Wconversion. 9800 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 9801 return false; 9802 } 9803 9804 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9805 // Returns true when emitting a warning about taking the address of a reference. 9806 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9807 const PartialDiagnostic &PD) { 9808 E = E->IgnoreParenImpCasts(); 9809 9810 const FunctionDecl *FD = nullptr; 9811 9812 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9813 if (!DRE->getDecl()->getType()->isReferenceType()) 9814 return false; 9815 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9816 if (!M->getMemberDecl()->getType()->isReferenceType()) 9817 return false; 9818 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9819 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9820 return false; 9821 FD = Call->getDirectCallee(); 9822 } else { 9823 return false; 9824 } 9825 9826 SemaRef.Diag(E->getExprLoc(), PD); 9827 9828 // If possible, point to location of function. 9829 if (FD) { 9830 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9831 } 9832 9833 return true; 9834 } 9835 9836 // Returns true if the SourceLocation is expanded from any macro body. 9837 // Returns false if the SourceLocation is invalid, is from not in a macro 9838 // expansion, or is from expanded from a top-level macro argument. 9839 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9840 if (Loc.isInvalid()) 9841 return false; 9842 9843 while (Loc.isMacroID()) { 9844 if (SM.isMacroBodyExpansion(Loc)) 9845 return true; 9846 Loc = SM.getImmediateMacroCallerLoc(Loc); 9847 } 9848 9849 return false; 9850 } 9851 9852 /// \brief Diagnose pointers that are always non-null. 9853 /// \param E the expression containing the pointer 9854 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9855 /// compared to a null pointer 9856 /// \param IsEqual True when the comparison is equal to a null pointer 9857 /// \param Range Extra SourceRange to highlight in the diagnostic 9858 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9859 Expr::NullPointerConstantKind NullKind, 9860 bool IsEqual, SourceRange Range) { 9861 if (!E) 9862 return; 9863 9864 // Don't warn inside macros. 9865 if (E->getExprLoc().isMacroID()) { 9866 const SourceManager &SM = getSourceManager(); 9867 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9868 IsInAnyMacroBody(SM, Range.getBegin())) 9869 return; 9870 } 9871 E = E->IgnoreImpCasts(); 9872 9873 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9874 9875 if (isa<CXXThisExpr>(E)) { 9876 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9877 : diag::warn_this_bool_conversion; 9878 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9879 return; 9880 } 9881 9882 bool IsAddressOf = false; 9883 9884 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9885 if (UO->getOpcode() != UO_AddrOf) 9886 return; 9887 IsAddressOf = true; 9888 E = UO->getSubExpr(); 9889 } 9890 9891 if (IsAddressOf) { 9892 unsigned DiagID = IsCompare 9893 ? diag::warn_address_of_reference_null_compare 9894 : diag::warn_address_of_reference_bool_conversion; 9895 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 9896 << IsEqual; 9897 if (CheckForReference(*this, E, PD)) { 9898 return; 9899 } 9900 } 9901 9902 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 9903 bool IsParam = isa<NonNullAttr>(NonnullAttr); 9904 std::string Str; 9905 llvm::raw_string_ostream S(Str); 9906 E->printPretty(S, nullptr, getPrintingPolicy()); 9907 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 9908 : diag::warn_cast_nonnull_to_bool; 9909 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 9910 << E->getSourceRange() << Range << IsEqual; 9911 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 9912 }; 9913 9914 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 9915 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 9916 if (auto *Callee = Call->getDirectCallee()) { 9917 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 9918 ComplainAboutNonnullParamOrCall(A); 9919 return; 9920 } 9921 } 9922 } 9923 9924 // Expect to find a single Decl. Skip anything more complicated. 9925 ValueDecl *D = nullptr; 9926 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 9927 D = R->getDecl(); 9928 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9929 D = M->getMemberDecl(); 9930 } 9931 9932 // Weak Decls can be null. 9933 if (!D || D->isWeak()) 9934 return; 9935 9936 // Check for parameter decl with nonnull attribute 9937 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 9938 if (getCurFunction() && 9939 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 9940 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 9941 ComplainAboutNonnullParamOrCall(A); 9942 return; 9943 } 9944 9945 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 9946 auto ParamIter = llvm::find(FD->parameters(), PV); 9947 assert(ParamIter != FD->param_end()); 9948 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 9949 9950 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 9951 if (!NonNull->args_size()) { 9952 ComplainAboutNonnullParamOrCall(NonNull); 9953 return; 9954 } 9955 9956 for (unsigned ArgNo : NonNull->args()) { 9957 if (ArgNo == ParamNo) { 9958 ComplainAboutNonnullParamOrCall(NonNull); 9959 return; 9960 } 9961 } 9962 } 9963 } 9964 } 9965 } 9966 9967 QualType T = D->getType(); 9968 const bool IsArray = T->isArrayType(); 9969 const bool IsFunction = T->isFunctionType(); 9970 9971 // Address of function is used to silence the function warning. 9972 if (IsAddressOf && IsFunction) { 9973 return; 9974 } 9975 9976 // Found nothing. 9977 if (!IsAddressOf && !IsFunction && !IsArray) 9978 return; 9979 9980 // Pretty print the expression for the diagnostic. 9981 std::string Str; 9982 llvm::raw_string_ostream S(Str); 9983 E->printPretty(S, nullptr, getPrintingPolicy()); 9984 9985 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 9986 : diag::warn_impcast_pointer_to_bool; 9987 enum { 9988 AddressOf, 9989 FunctionPointer, 9990 ArrayPointer 9991 } DiagType; 9992 if (IsAddressOf) 9993 DiagType = AddressOf; 9994 else if (IsFunction) 9995 DiagType = FunctionPointer; 9996 else if (IsArray) 9997 DiagType = ArrayPointer; 9998 else 9999 llvm_unreachable("Could not determine diagnostic."); 10000 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 10001 << Range << IsEqual; 10002 10003 if (!IsFunction) 10004 return; 10005 10006 // Suggest '&' to silence the function warning. 10007 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10008 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10009 10010 // Check to see if '()' fixit should be emitted. 10011 QualType ReturnType; 10012 UnresolvedSet<4> NonTemplateOverloads; 10013 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10014 if (ReturnType.isNull()) 10015 return; 10016 10017 if (IsCompare) { 10018 // There are two cases here. If there is null constant, the only suggest 10019 // for a pointer return type. If the null is 0, then suggest if the return 10020 // type is a pointer or an integer type. 10021 if (!ReturnType->isPointerType()) { 10022 if (NullKind == Expr::NPCK_ZeroExpression || 10023 NullKind == Expr::NPCK_ZeroLiteral) { 10024 if (!ReturnType->isIntegerType()) 10025 return; 10026 } else { 10027 return; 10028 } 10029 } 10030 } else { // !IsCompare 10031 // For function to bool, only suggest if the function pointer has bool 10032 // return type. 10033 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10034 return; 10035 } 10036 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10037 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10038 } 10039 10040 /// Diagnoses "dangerous" implicit conversions within the given 10041 /// expression (which is a full expression). Implements -Wconversion 10042 /// and -Wsign-compare. 10043 /// 10044 /// \param CC the "context" location of the implicit conversion, i.e. 10045 /// the most location of the syntactic entity requiring the implicit 10046 /// conversion 10047 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10048 // Don't diagnose in unevaluated contexts. 10049 if (isUnevaluatedContext()) 10050 return; 10051 10052 // Don't diagnose for value- or type-dependent expressions. 10053 if (E->isTypeDependent() || E->isValueDependent()) 10054 return; 10055 10056 // Check for array bounds violations in cases where the check isn't triggered 10057 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10058 // ArraySubscriptExpr is on the RHS of a variable initialization. 10059 CheckArrayAccess(E); 10060 10061 // This is not the right CC for (e.g.) a variable initialization. 10062 AnalyzeImplicitConversions(*this, E, CC); 10063 } 10064 10065 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10066 /// Input argument E is a logical expression. 10067 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10068 ::CheckBoolLikeConversion(*this, E, CC); 10069 } 10070 10071 /// Diagnose when expression is an integer constant expression and its evaluation 10072 /// results in integer overflow 10073 void Sema::CheckForIntOverflow (Expr *E) { 10074 // Use a work list to deal with nested struct initializers. 10075 SmallVector<Expr *, 2> Exprs(1, E); 10076 10077 do { 10078 Expr *E = Exprs.pop_back_val(); 10079 10080 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 10081 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10082 continue; 10083 } 10084 10085 if (auto InitList = dyn_cast<InitListExpr>(E)) 10086 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10087 10088 if (isa<ObjCBoxedExpr>(E)) 10089 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10090 } while (!Exprs.empty()); 10091 } 10092 10093 namespace { 10094 /// \brief Visitor for expressions which looks for unsequenced operations on the 10095 /// same object. 10096 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10097 typedef EvaluatedExprVisitor<SequenceChecker> Base; 10098 10099 /// \brief A tree of sequenced regions within an expression. Two regions are 10100 /// unsequenced if one is an ancestor or a descendent of the other. When we 10101 /// finish processing an expression with sequencing, such as a comma 10102 /// expression, we fold its tree nodes into its parent, since they are 10103 /// unsequenced with respect to nodes we will visit later. 10104 class SequenceTree { 10105 struct Value { 10106 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10107 unsigned Parent : 31; 10108 unsigned Merged : 1; 10109 }; 10110 SmallVector<Value, 8> Values; 10111 10112 public: 10113 /// \brief A region within an expression which may be sequenced with respect 10114 /// to some other region. 10115 class Seq { 10116 explicit Seq(unsigned N) : Index(N) {} 10117 unsigned Index; 10118 friend class SequenceTree; 10119 public: 10120 Seq() : Index(0) {} 10121 }; 10122 10123 SequenceTree() { Values.push_back(Value(0)); } 10124 Seq root() const { return Seq(0); } 10125 10126 /// \brief Create a new sequence of operations, which is an unsequenced 10127 /// subset of \p Parent. This sequence of operations is sequenced with 10128 /// respect to other children of \p Parent. 10129 Seq allocate(Seq Parent) { 10130 Values.push_back(Value(Parent.Index)); 10131 return Seq(Values.size() - 1); 10132 } 10133 10134 /// \brief Merge a sequence of operations into its parent. 10135 void merge(Seq S) { 10136 Values[S.Index].Merged = true; 10137 } 10138 10139 /// \brief Determine whether two operations are unsequenced. This operation 10140 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10141 /// should have been merged into its parent as appropriate. 10142 bool isUnsequenced(Seq Cur, Seq Old) { 10143 unsigned C = representative(Cur.Index); 10144 unsigned Target = representative(Old.Index); 10145 while (C >= Target) { 10146 if (C == Target) 10147 return true; 10148 C = Values[C].Parent; 10149 } 10150 return false; 10151 } 10152 10153 private: 10154 /// \brief Pick a representative for a sequence. 10155 unsigned representative(unsigned K) { 10156 if (Values[K].Merged) 10157 // Perform path compression as we go. 10158 return Values[K].Parent = representative(Values[K].Parent); 10159 return K; 10160 } 10161 }; 10162 10163 /// An object for which we can track unsequenced uses. 10164 typedef NamedDecl *Object; 10165 10166 /// Different flavors of object usage which we track. We only track the 10167 /// least-sequenced usage of each kind. 10168 enum UsageKind { 10169 /// A read of an object. Multiple unsequenced reads are OK. 10170 UK_Use, 10171 /// A modification of an object which is sequenced before the value 10172 /// computation of the expression, such as ++n in C++. 10173 UK_ModAsValue, 10174 /// A modification of an object which is not sequenced before the value 10175 /// computation of the expression, such as n++. 10176 UK_ModAsSideEffect, 10177 10178 UK_Count = UK_ModAsSideEffect + 1 10179 }; 10180 10181 struct Usage { 10182 Usage() : Use(nullptr), Seq() {} 10183 Expr *Use; 10184 SequenceTree::Seq Seq; 10185 }; 10186 10187 struct UsageInfo { 10188 UsageInfo() : Diagnosed(false) {} 10189 Usage Uses[UK_Count]; 10190 /// Have we issued a diagnostic for this variable already? 10191 bool Diagnosed; 10192 }; 10193 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 10194 10195 Sema &SemaRef; 10196 /// Sequenced regions within the expression. 10197 SequenceTree Tree; 10198 /// Declaration modifications and references which we have seen. 10199 UsageInfoMap UsageMap; 10200 /// The region we are currently within. 10201 SequenceTree::Seq Region; 10202 /// Filled in with declarations which were modified as a side-effect 10203 /// (that is, post-increment operations). 10204 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 10205 /// Expressions to check later. We defer checking these to reduce 10206 /// stack usage. 10207 SmallVectorImpl<Expr *> &WorkList; 10208 10209 /// RAII object wrapping the visitation of a sequenced subexpression of an 10210 /// expression. At the end of this process, the side-effects of the evaluation 10211 /// become sequenced with respect to the value computation of the result, so 10212 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10213 /// UK_ModAsValue. 10214 struct SequencedSubexpression { 10215 SequencedSubexpression(SequenceChecker &Self) 10216 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 10217 Self.ModAsSideEffect = &ModAsSideEffect; 10218 } 10219 ~SequencedSubexpression() { 10220 for (auto &M : llvm::reverse(ModAsSideEffect)) { 10221 UsageInfo &U = Self.UsageMap[M.first]; 10222 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 10223 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 10224 SideEffectUsage = M.second; 10225 } 10226 Self.ModAsSideEffect = OldModAsSideEffect; 10227 } 10228 10229 SequenceChecker &Self; 10230 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 10231 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 10232 }; 10233 10234 /// RAII object wrapping the visitation of a subexpression which we might 10235 /// choose to evaluate as a constant. If any subexpression is evaluated and 10236 /// found to be non-constant, this allows us to suppress the evaluation of 10237 /// the outer expression. 10238 class EvaluationTracker { 10239 public: 10240 EvaluationTracker(SequenceChecker &Self) 10241 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 10242 Self.EvalTracker = this; 10243 } 10244 ~EvaluationTracker() { 10245 Self.EvalTracker = Prev; 10246 if (Prev) 10247 Prev->EvalOK &= EvalOK; 10248 } 10249 10250 bool evaluate(const Expr *E, bool &Result) { 10251 if (!EvalOK || E->isValueDependent()) 10252 return false; 10253 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 10254 return EvalOK; 10255 } 10256 10257 private: 10258 SequenceChecker &Self; 10259 EvaluationTracker *Prev; 10260 bool EvalOK; 10261 } *EvalTracker; 10262 10263 /// \brief Find the object which is produced by the specified expression, 10264 /// if any. 10265 Object getObject(Expr *E, bool Mod) const { 10266 E = E->IgnoreParenCasts(); 10267 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10268 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 10269 return getObject(UO->getSubExpr(), Mod); 10270 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10271 if (BO->getOpcode() == BO_Comma) 10272 return getObject(BO->getRHS(), Mod); 10273 if (Mod && BO->isAssignmentOp()) 10274 return getObject(BO->getLHS(), Mod); 10275 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10276 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 10277 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 10278 return ME->getMemberDecl(); 10279 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10280 // FIXME: If this is a reference, map through to its value. 10281 return DRE->getDecl(); 10282 return nullptr; 10283 } 10284 10285 /// \brief Note that an object was modified or used by an expression. 10286 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 10287 Usage &U = UI.Uses[UK]; 10288 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 10289 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 10290 ModAsSideEffect->push_back(std::make_pair(O, U)); 10291 U.Use = Ref; 10292 U.Seq = Region; 10293 } 10294 } 10295 /// \brief Check whether a modification or use conflicts with a prior usage. 10296 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 10297 bool IsModMod) { 10298 if (UI.Diagnosed) 10299 return; 10300 10301 const Usage &U = UI.Uses[OtherKind]; 10302 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 10303 return; 10304 10305 Expr *Mod = U.Use; 10306 Expr *ModOrUse = Ref; 10307 if (OtherKind == UK_Use) 10308 std::swap(Mod, ModOrUse); 10309 10310 SemaRef.Diag(Mod->getExprLoc(), 10311 IsModMod ? diag::warn_unsequenced_mod_mod 10312 : diag::warn_unsequenced_mod_use) 10313 << O << SourceRange(ModOrUse->getExprLoc()); 10314 UI.Diagnosed = true; 10315 } 10316 10317 void notePreUse(Object O, Expr *Use) { 10318 UsageInfo &U = UsageMap[O]; 10319 // Uses conflict with other modifications. 10320 checkUsage(O, U, Use, UK_ModAsValue, false); 10321 } 10322 void notePostUse(Object O, Expr *Use) { 10323 UsageInfo &U = UsageMap[O]; 10324 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 10325 addUsage(U, O, Use, UK_Use); 10326 } 10327 10328 void notePreMod(Object O, Expr *Mod) { 10329 UsageInfo &U = UsageMap[O]; 10330 // Modifications conflict with other modifications and with uses. 10331 checkUsage(O, U, Mod, UK_ModAsValue, true); 10332 checkUsage(O, U, Mod, UK_Use, false); 10333 } 10334 void notePostMod(Object O, Expr *Use, UsageKind UK) { 10335 UsageInfo &U = UsageMap[O]; 10336 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 10337 addUsage(U, O, Use, UK); 10338 } 10339 10340 public: 10341 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 10342 : Base(S.Context), SemaRef(S), Region(Tree.root()), 10343 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 10344 Visit(E); 10345 } 10346 10347 void VisitStmt(Stmt *S) { 10348 // Skip all statements which aren't expressions for now. 10349 } 10350 10351 void VisitExpr(Expr *E) { 10352 // By default, just recurse to evaluated subexpressions. 10353 Base::VisitStmt(E); 10354 } 10355 10356 void VisitCastExpr(CastExpr *E) { 10357 Object O = Object(); 10358 if (E->getCastKind() == CK_LValueToRValue) 10359 O = getObject(E->getSubExpr(), false); 10360 10361 if (O) 10362 notePreUse(O, E); 10363 VisitExpr(E); 10364 if (O) 10365 notePostUse(O, E); 10366 } 10367 10368 void VisitBinComma(BinaryOperator *BO) { 10369 // C++11 [expr.comma]p1: 10370 // Every value computation and side effect associated with the left 10371 // expression is sequenced before every value computation and side 10372 // effect associated with the right expression. 10373 SequenceTree::Seq LHS = Tree.allocate(Region); 10374 SequenceTree::Seq RHS = Tree.allocate(Region); 10375 SequenceTree::Seq OldRegion = Region; 10376 10377 { 10378 SequencedSubexpression SeqLHS(*this); 10379 Region = LHS; 10380 Visit(BO->getLHS()); 10381 } 10382 10383 Region = RHS; 10384 Visit(BO->getRHS()); 10385 10386 Region = OldRegion; 10387 10388 // Forget that LHS and RHS are sequenced. They are both unsequenced 10389 // with respect to other stuff. 10390 Tree.merge(LHS); 10391 Tree.merge(RHS); 10392 } 10393 10394 void VisitBinAssign(BinaryOperator *BO) { 10395 // The modification is sequenced after the value computation of the LHS 10396 // and RHS, so check it before inspecting the operands and update the 10397 // map afterwards. 10398 Object O = getObject(BO->getLHS(), true); 10399 if (!O) 10400 return VisitExpr(BO); 10401 10402 notePreMod(O, BO); 10403 10404 // C++11 [expr.ass]p7: 10405 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 10406 // only once. 10407 // 10408 // Therefore, for a compound assignment operator, O is considered used 10409 // everywhere except within the evaluation of E1 itself. 10410 if (isa<CompoundAssignOperator>(BO)) 10411 notePreUse(O, BO); 10412 10413 Visit(BO->getLHS()); 10414 10415 if (isa<CompoundAssignOperator>(BO)) 10416 notePostUse(O, BO); 10417 10418 Visit(BO->getRHS()); 10419 10420 // C++11 [expr.ass]p1: 10421 // the assignment is sequenced [...] before the value computation of the 10422 // assignment expression. 10423 // C11 6.5.16/3 has no such rule. 10424 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10425 : UK_ModAsSideEffect); 10426 } 10427 10428 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 10429 VisitBinAssign(CAO); 10430 } 10431 10432 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10433 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10434 void VisitUnaryPreIncDec(UnaryOperator *UO) { 10435 Object O = getObject(UO->getSubExpr(), true); 10436 if (!O) 10437 return VisitExpr(UO); 10438 10439 notePreMod(O, UO); 10440 Visit(UO->getSubExpr()); 10441 // C++11 [expr.pre.incr]p1: 10442 // the expression ++x is equivalent to x+=1 10443 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10444 : UK_ModAsSideEffect); 10445 } 10446 10447 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10448 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10449 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10450 Object O = getObject(UO->getSubExpr(), true); 10451 if (!O) 10452 return VisitExpr(UO); 10453 10454 notePreMod(O, UO); 10455 Visit(UO->getSubExpr()); 10456 notePostMod(O, UO, UK_ModAsSideEffect); 10457 } 10458 10459 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10460 void VisitBinLOr(BinaryOperator *BO) { 10461 // The side-effects of the LHS of an '&&' are sequenced before the 10462 // value computation of the RHS, and hence before the value computation 10463 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10464 // as if they were unconditionally sequenced. 10465 EvaluationTracker Eval(*this); 10466 { 10467 SequencedSubexpression Sequenced(*this); 10468 Visit(BO->getLHS()); 10469 } 10470 10471 bool Result; 10472 if (Eval.evaluate(BO->getLHS(), Result)) { 10473 if (!Result) 10474 Visit(BO->getRHS()); 10475 } else { 10476 // Check for unsequenced operations in the RHS, treating it as an 10477 // entirely separate evaluation. 10478 // 10479 // FIXME: If there are operations in the RHS which are unsequenced 10480 // with respect to operations outside the RHS, and those operations 10481 // are unconditionally evaluated, diagnose them. 10482 WorkList.push_back(BO->getRHS()); 10483 } 10484 } 10485 void VisitBinLAnd(BinaryOperator *BO) { 10486 EvaluationTracker Eval(*this); 10487 { 10488 SequencedSubexpression Sequenced(*this); 10489 Visit(BO->getLHS()); 10490 } 10491 10492 bool Result; 10493 if (Eval.evaluate(BO->getLHS(), Result)) { 10494 if (Result) 10495 Visit(BO->getRHS()); 10496 } else { 10497 WorkList.push_back(BO->getRHS()); 10498 } 10499 } 10500 10501 // Only visit the condition, unless we can be sure which subexpression will 10502 // be chosen. 10503 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10504 EvaluationTracker Eval(*this); 10505 { 10506 SequencedSubexpression Sequenced(*this); 10507 Visit(CO->getCond()); 10508 } 10509 10510 bool Result; 10511 if (Eval.evaluate(CO->getCond(), Result)) 10512 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10513 else { 10514 WorkList.push_back(CO->getTrueExpr()); 10515 WorkList.push_back(CO->getFalseExpr()); 10516 } 10517 } 10518 10519 void VisitCallExpr(CallExpr *CE) { 10520 // C++11 [intro.execution]p15: 10521 // When calling a function [...], every value computation and side effect 10522 // associated with any argument expression, or with the postfix expression 10523 // designating the called function, is sequenced before execution of every 10524 // expression or statement in the body of the function [and thus before 10525 // the value computation of its result]. 10526 SequencedSubexpression Sequenced(*this); 10527 Base::VisitCallExpr(CE); 10528 10529 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10530 } 10531 10532 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10533 // This is a call, so all subexpressions are sequenced before the result. 10534 SequencedSubexpression Sequenced(*this); 10535 10536 if (!CCE->isListInitialization()) 10537 return VisitExpr(CCE); 10538 10539 // In C++11, list initializations are sequenced. 10540 SmallVector<SequenceTree::Seq, 32> Elts; 10541 SequenceTree::Seq Parent = Region; 10542 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10543 E = CCE->arg_end(); 10544 I != E; ++I) { 10545 Region = Tree.allocate(Parent); 10546 Elts.push_back(Region); 10547 Visit(*I); 10548 } 10549 10550 // Forget that the initializers are sequenced. 10551 Region = Parent; 10552 for (unsigned I = 0; I < Elts.size(); ++I) 10553 Tree.merge(Elts[I]); 10554 } 10555 10556 void VisitInitListExpr(InitListExpr *ILE) { 10557 if (!SemaRef.getLangOpts().CPlusPlus11) 10558 return VisitExpr(ILE); 10559 10560 // In C++11, list initializations are sequenced. 10561 SmallVector<SequenceTree::Seq, 32> Elts; 10562 SequenceTree::Seq Parent = Region; 10563 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10564 Expr *E = ILE->getInit(I); 10565 if (!E) continue; 10566 Region = Tree.allocate(Parent); 10567 Elts.push_back(Region); 10568 Visit(E); 10569 } 10570 10571 // Forget that the initializers are sequenced. 10572 Region = Parent; 10573 for (unsigned I = 0; I < Elts.size(); ++I) 10574 Tree.merge(Elts[I]); 10575 } 10576 }; 10577 } // end anonymous namespace 10578 10579 void Sema::CheckUnsequencedOperations(Expr *E) { 10580 SmallVector<Expr *, 8> WorkList; 10581 WorkList.push_back(E); 10582 while (!WorkList.empty()) { 10583 Expr *Item = WorkList.pop_back_val(); 10584 SequenceChecker(*this, Item, WorkList); 10585 } 10586 } 10587 10588 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10589 bool IsConstexpr) { 10590 CheckImplicitConversions(E, CheckLoc); 10591 if (!E->isInstantiationDependent()) 10592 CheckUnsequencedOperations(E); 10593 if (!IsConstexpr && !E->isValueDependent()) 10594 CheckForIntOverflow(E); 10595 DiagnoseMisalignedMembers(); 10596 } 10597 10598 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10599 FieldDecl *BitField, 10600 Expr *Init) { 10601 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10602 } 10603 10604 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10605 SourceLocation Loc) { 10606 if (!PType->isVariablyModifiedType()) 10607 return; 10608 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10609 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10610 return; 10611 } 10612 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10613 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10614 return; 10615 } 10616 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10617 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10618 return; 10619 } 10620 10621 const ArrayType *AT = S.Context.getAsArrayType(PType); 10622 if (!AT) 10623 return; 10624 10625 if (AT->getSizeModifier() != ArrayType::Star) { 10626 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10627 return; 10628 } 10629 10630 S.Diag(Loc, diag::err_array_star_in_function_definition); 10631 } 10632 10633 /// CheckParmsForFunctionDef - Check that the parameters of the given 10634 /// function are appropriate for the definition of a function. This 10635 /// takes care of any checks that cannot be performed on the 10636 /// declaration itself, e.g., that the types of each of the function 10637 /// parameters are complete. 10638 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10639 bool CheckParameterNames) { 10640 bool HasInvalidParm = false; 10641 for (ParmVarDecl *Param : Parameters) { 10642 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10643 // function declarator that is part of a function definition of 10644 // that function shall not have incomplete type. 10645 // 10646 // This is also C++ [dcl.fct]p6. 10647 if (!Param->isInvalidDecl() && 10648 RequireCompleteType(Param->getLocation(), Param->getType(), 10649 diag::err_typecheck_decl_incomplete_type)) { 10650 Param->setInvalidDecl(); 10651 HasInvalidParm = true; 10652 } 10653 10654 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10655 // declaration of each parameter shall include an identifier. 10656 if (CheckParameterNames && 10657 Param->getIdentifier() == nullptr && 10658 !Param->isImplicit() && 10659 !getLangOpts().CPlusPlus) 10660 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10661 10662 // C99 6.7.5.3p12: 10663 // If the function declarator is not part of a definition of that 10664 // function, parameters may have incomplete type and may use the [*] 10665 // notation in their sequences of declarator specifiers to specify 10666 // variable length array types. 10667 QualType PType = Param->getOriginalType(); 10668 // FIXME: This diagnostic should point the '[*]' if source-location 10669 // information is added for it. 10670 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10671 10672 // MSVC destroys objects passed by value in the callee. Therefore a 10673 // function definition which takes such a parameter must be able to call the 10674 // object's destructor. However, we don't perform any direct access check 10675 // on the dtor. 10676 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10677 .getCXXABI() 10678 .areArgsDestroyedLeftToRightInCallee()) { 10679 if (!Param->isInvalidDecl()) { 10680 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10681 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10682 if (!ClassDecl->isInvalidDecl() && 10683 !ClassDecl->hasIrrelevantDestructor() && 10684 !ClassDecl->isDependentContext()) { 10685 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10686 MarkFunctionReferenced(Param->getLocation(), Destructor); 10687 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10688 } 10689 } 10690 } 10691 } 10692 10693 // Parameters with the pass_object_size attribute only need to be marked 10694 // constant at function definitions. Because we lack information about 10695 // whether we're on a declaration or definition when we're instantiating the 10696 // attribute, we need to check for constness here. 10697 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10698 if (!Param->getType().isConstQualified()) 10699 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10700 << Attr->getSpelling() << 1; 10701 } 10702 10703 return HasInvalidParm; 10704 } 10705 10706 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 10707 /// or MemberExpr. 10708 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 10709 ASTContext &Context) { 10710 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 10711 return Context.getDeclAlign(DRE->getDecl()); 10712 10713 if (const auto *ME = dyn_cast<MemberExpr>(E)) 10714 return Context.getDeclAlign(ME->getMemberDecl()); 10715 10716 return TypeAlign; 10717 } 10718 10719 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10720 /// pointer cast increases the alignment requirements. 10721 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10722 // This is actually a lot of work to potentially be doing on every 10723 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10724 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10725 return; 10726 10727 // Ignore dependent types. 10728 if (T->isDependentType() || Op->getType()->isDependentType()) 10729 return; 10730 10731 // Require that the destination be a pointer type. 10732 const PointerType *DestPtr = T->getAs<PointerType>(); 10733 if (!DestPtr) return; 10734 10735 // If the destination has alignment 1, we're done. 10736 QualType DestPointee = DestPtr->getPointeeType(); 10737 if (DestPointee->isIncompleteType()) return; 10738 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10739 if (DestAlign.isOne()) return; 10740 10741 // Require that the source be a pointer type. 10742 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10743 if (!SrcPtr) return; 10744 QualType SrcPointee = SrcPtr->getPointeeType(); 10745 10746 // Whitelist casts from cv void*. We already implicitly 10747 // whitelisted casts to cv void*, since they have alignment 1. 10748 // Also whitelist casts involving incomplete types, which implicitly 10749 // includes 'void'. 10750 if (SrcPointee->isIncompleteType()) return; 10751 10752 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10753 10754 if (auto *CE = dyn_cast<CastExpr>(Op)) { 10755 if (CE->getCastKind() == CK_ArrayToPointerDecay) 10756 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 10757 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 10758 if (UO->getOpcode() == UO_AddrOf) 10759 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 10760 } 10761 10762 if (SrcAlign >= DestAlign) return; 10763 10764 Diag(TRange.getBegin(), diag::warn_cast_align) 10765 << Op->getType() << T 10766 << static_cast<unsigned>(SrcAlign.getQuantity()) 10767 << static_cast<unsigned>(DestAlign.getQuantity()) 10768 << TRange << Op->getSourceRange(); 10769 } 10770 10771 /// \brief Check whether this array fits the idiom of a size-one tail padded 10772 /// array member of a struct. 10773 /// 10774 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10775 /// commonly used to emulate flexible arrays in C89 code. 10776 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10777 const NamedDecl *ND) { 10778 if (Size != 1 || !ND) return false; 10779 10780 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10781 if (!FD) return false; 10782 10783 // Don't consider sizes resulting from macro expansions or template argument 10784 // substitution to form C89 tail-padded arrays. 10785 10786 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10787 while (TInfo) { 10788 TypeLoc TL = TInfo->getTypeLoc(); 10789 // Look through typedefs. 10790 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10791 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10792 TInfo = TDL->getTypeSourceInfo(); 10793 continue; 10794 } 10795 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10796 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10797 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10798 return false; 10799 } 10800 break; 10801 } 10802 10803 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10804 if (!RD) return false; 10805 if (RD->isUnion()) return false; 10806 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10807 if (!CRD->isStandardLayout()) return false; 10808 } 10809 10810 // See if this is the last field decl in the record. 10811 const Decl *D = FD; 10812 while ((D = D->getNextDeclInContext())) 10813 if (isa<FieldDecl>(D)) 10814 return false; 10815 return true; 10816 } 10817 10818 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10819 const ArraySubscriptExpr *ASE, 10820 bool AllowOnePastEnd, bool IndexNegated) { 10821 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10822 if (IndexExpr->isValueDependent()) 10823 return; 10824 10825 const Type *EffectiveType = 10826 BaseExpr->getType()->getPointeeOrArrayElementType(); 10827 BaseExpr = BaseExpr->IgnoreParenCasts(); 10828 const ConstantArrayType *ArrayTy = 10829 Context.getAsConstantArrayType(BaseExpr->getType()); 10830 if (!ArrayTy) 10831 return; 10832 10833 llvm::APSInt index; 10834 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10835 return; 10836 if (IndexNegated) 10837 index = -index; 10838 10839 const NamedDecl *ND = nullptr; 10840 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10841 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10842 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10843 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10844 10845 if (index.isUnsigned() || !index.isNegative()) { 10846 llvm::APInt size = ArrayTy->getSize(); 10847 if (!size.isStrictlyPositive()) 10848 return; 10849 10850 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10851 if (BaseType != EffectiveType) { 10852 // Make sure we're comparing apples to apples when comparing index to size 10853 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10854 uint64_t array_typesize = Context.getTypeSize(BaseType); 10855 // Handle ptrarith_typesize being zero, such as when casting to void* 10856 if (!ptrarith_typesize) ptrarith_typesize = 1; 10857 if (ptrarith_typesize != array_typesize) { 10858 // There's a cast to a different size type involved 10859 uint64_t ratio = array_typesize / ptrarith_typesize; 10860 // TODO: Be smarter about handling cases where array_typesize is not a 10861 // multiple of ptrarith_typesize 10862 if (ptrarith_typesize * ratio == array_typesize) 10863 size *= llvm::APInt(size.getBitWidth(), ratio); 10864 } 10865 } 10866 10867 if (size.getBitWidth() > index.getBitWidth()) 10868 index = index.zext(size.getBitWidth()); 10869 else if (size.getBitWidth() < index.getBitWidth()) 10870 size = size.zext(index.getBitWidth()); 10871 10872 // For array subscripting the index must be less than size, but for pointer 10873 // arithmetic also allow the index (offset) to be equal to size since 10874 // computing the next address after the end of the array is legal and 10875 // commonly done e.g. in C++ iterators and range-based for loops. 10876 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10877 return; 10878 10879 // Also don't warn for arrays of size 1 which are members of some 10880 // structure. These are often used to approximate flexible arrays in C89 10881 // code. 10882 if (IsTailPaddedMemberArray(*this, size, ND)) 10883 return; 10884 10885 // Suppress the warning if the subscript expression (as identified by the 10886 // ']' location) and the index expression are both from macro expansions 10887 // within a system header. 10888 if (ASE) { 10889 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 10890 ASE->getRBracketLoc()); 10891 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 10892 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 10893 IndexExpr->getLocStart()); 10894 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 10895 return; 10896 } 10897 } 10898 10899 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 10900 if (ASE) 10901 DiagID = diag::warn_array_index_exceeds_bounds; 10902 10903 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10904 PDiag(DiagID) << index.toString(10, true) 10905 << size.toString(10, true) 10906 << (unsigned)size.getLimitedValue(~0U) 10907 << IndexExpr->getSourceRange()); 10908 } else { 10909 unsigned DiagID = diag::warn_array_index_precedes_bounds; 10910 if (!ASE) { 10911 DiagID = diag::warn_ptr_arith_precedes_bounds; 10912 if (index.isNegative()) index = -index; 10913 } 10914 10915 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10916 PDiag(DiagID) << index.toString(10, true) 10917 << IndexExpr->getSourceRange()); 10918 } 10919 10920 if (!ND) { 10921 // Try harder to find a NamedDecl to point at in the note. 10922 while (const ArraySubscriptExpr *ASE = 10923 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 10924 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 10925 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10926 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10927 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10928 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10929 } 10930 10931 if (ND) 10932 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 10933 PDiag(diag::note_array_index_out_of_bounds) 10934 << ND->getDeclName()); 10935 } 10936 10937 void Sema::CheckArrayAccess(const Expr *expr) { 10938 int AllowOnePastEnd = 0; 10939 while (expr) { 10940 expr = expr->IgnoreParenImpCasts(); 10941 switch (expr->getStmtClass()) { 10942 case Stmt::ArraySubscriptExprClass: { 10943 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 10944 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 10945 AllowOnePastEnd > 0); 10946 return; 10947 } 10948 case Stmt::OMPArraySectionExprClass: { 10949 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 10950 if (ASE->getLowerBound()) 10951 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 10952 /*ASE=*/nullptr, AllowOnePastEnd > 0); 10953 return; 10954 } 10955 case Stmt::UnaryOperatorClass: { 10956 // Only unwrap the * and & unary operators 10957 const UnaryOperator *UO = cast<UnaryOperator>(expr); 10958 expr = UO->getSubExpr(); 10959 switch (UO->getOpcode()) { 10960 case UO_AddrOf: 10961 AllowOnePastEnd++; 10962 break; 10963 case UO_Deref: 10964 AllowOnePastEnd--; 10965 break; 10966 default: 10967 return; 10968 } 10969 break; 10970 } 10971 case Stmt::ConditionalOperatorClass: { 10972 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 10973 if (const Expr *lhs = cond->getLHS()) 10974 CheckArrayAccess(lhs); 10975 if (const Expr *rhs = cond->getRHS()) 10976 CheckArrayAccess(rhs); 10977 return; 10978 } 10979 case Stmt::CXXOperatorCallExprClass: { 10980 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 10981 for (const auto *Arg : OCE->arguments()) 10982 CheckArrayAccess(Arg); 10983 return; 10984 } 10985 default: 10986 return; 10987 } 10988 } 10989 } 10990 10991 //===--- CHECK: Objective-C retain cycles ----------------------------------// 10992 10993 namespace { 10994 struct RetainCycleOwner { 10995 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 10996 VarDecl *Variable; 10997 SourceRange Range; 10998 SourceLocation Loc; 10999 bool Indirect; 11000 11001 void setLocsFrom(Expr *e) { 11002 Loc = e->getExprLoc(); 11003 Range = e->getSourceRange(); 11004 } 11005 }; 11006 } // end anonymous namespace 11007 11008 /// Consider whether capturing the given variable can possibly lead to 11009 /// a retain cycle. 11010 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11011 // In ARC, it's captured strongly iff the variable has __strong 11012 // lifetime. In MRR, it's captured strongly if the variable is 11013 // __block and has an appropriate type. 11014 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11015 return false; 11016 11017 owner.Variable = var; 11018 if (ref) 11019 owner.setLocsFrom(ref); 11020 return true; 11021 } 11022 11023 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11024 while (true) { 11025 e = e->IgnoreParens(); 11026 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11027 switch (cast->getCastKind()) { 11028 case CK_BitCast: 11029 case CK_LValueBitCast: 11030 case CK_LValueToRValue: 11031 case CK_ARCReclaimReturnedObject: 11032 e = cast->getSubExpr(); 11033 continue; 11034 11035 default: 11036 return false; 11037 } 11038 } 11039 11040 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11041 ObjCIvarDecl *ivar = ref->getDecl(); 11042 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11043 return false; 11044 11045 // Try to find a retain cycle in the base. 11046 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11047 return false; 11048 11049 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11050 owner.Indirect = true; 11051 return true; 11052 } 11053 11054 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11055 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11056 if (!var) return false; 11057 return considerVariable(var, ref, owner); 11058 } 11059 11060 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11061 if (member->isArrow()) return false; 11062 11063 // Don't count this as an indirect ownership. 11064 e = member->getBase(); 11065 continue; 11066 } 11067 11068 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11069 // Only pay attention to pseudo-objects on property references. 11070 ObjCPropertyRefExpr *pre 11071 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11072 ->IgnoreParens()); 11073 if (!pre) return false; 11074 if (pre->isImplicitProperty()) return false; 11075 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11076 if (!property->isRetaining() && 11077 !(property->getPropertyIvarDecl() && 11078 property->getPropertyIvarDecl()->getType() 11079 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11080 return false; 11081 11082 owner.Indirect = true; 11083 if (pre->isSuperReceiver()) { 11084 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11085 if (!owner.Variable) 11086 return false; 11087 owner.Loc = pre->getLocation(); 11088 owner.Range = pre->getSourceRange(); 11089 return true; 11090 } 11091 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11092 ->getSourceExpr()); 11093 continue; 11094 } 11095 11096 // Array ivars? 11097 11098 return false; 11099 } 11100 } 11101 11102 namespace { 11103 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11104 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11105 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11106 Context(Context), Variable(variable), Capturer(nullptr), 11107 VarWillBeReased(false) {} 11108 ASTContext &Context; 11109 VarDecl *Variable; 11110 Expr *Capturer; 11111 bool VarWillBeReased; 11112 11113 void VisitDeclRefExpr(DeclRefExpr *ref) { 11114 if (ref->getDecl() == Variable && !Capturer) 11115 Capturer = ref; 11116 } 11117 11118 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11119 if (Capturer) return; 11120 Visit(ref->getBase()); 11121 if (Capturer && ref->isFreeIvar()) 11122 Capturer = ref; 11123 } 11124 11125 void VisitBlockExpr(BlockExpr *block) { 11126 // Look inside nested blocks 11127 if (block->getBlockDecl()->capturesVariable(Variable)) 11128 Visit(block->getBlockDecl()->getBody()); 11129 } 11130 11131 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11132 if (Capturer) return; 11133 if (OVE->getSourceExpr()) 11134 Visit(OVE->getSourceExpr()); 11135 } 11136 void VisitBinaryOperator(BinaryOperator *BinOp) { 11137 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11138 return; 11139 Expr *LHS = BinOp->getLHS(); 11140 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11141 if (DRE->getDecl() != Variable) 11142 return; 11143 if (Expr *RHS = BinOp->getRHS()) { 11144 RHS = RHS->IgnoreParenCasts(); 11145 llvm::APSInt Value; 11146 VarWillBeReased = 11147 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11148 } 11149 } 11150 } 11151 }; 11152 } // end anonymous namespace 11153 11154 /// Check whether the given argument is a block which captures a 11155 /// variable. 11156 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11157 assert(owner.Variable && owner.Loc.isValid()); 11158 11159 e = e->IgnoreParenCasts(); 11160 11161 // Look through [^{...} copy] and Block_copy(^{...}). 11162 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11163 Selector Cmd = ME->getSelector(); 11164 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11165 e = ME->getInstanceReceiver(); 11166 if (!e) 11167 return nullptr; 11168 e = e->IgnoreParenCasts(); 11169 } 11170 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11171 if (CE->getNumArgs() == 1) { 11172 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11173 if (Fn) { 11174 const IdentifierInfo *FnI = Fn->getIdentifier(); 11175 if (FnI && FnI->isStr("_Block_copy")) { 11176 e = CE->getArg(0)->IgnoreParenCasts(); 11177 } 11178 } 11179 } 11180 } 11181 11182 BlockExpr *block = dyn_cast<BlockExpr>(e); 11183 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11184 return nullptr; 11185 11186 FindCaptureVisitor visitor(S.Context, owner.Variable); 11187 visitor.Visit(block->getBlockDecl()->getBody()); 11188 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11189 } 11190 11191 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11192 RetainCycleOwner &owner) { 11193 assert(capturer); 11194 assert(owner.Variable && owner.Loc.isValid()); 11195 11196 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11197 << owner.Variable << capturer->getSourceRange(); 11198 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11199 << owner.Indirect << owner.Range; 11200 } 11201 11202 /// Check for a keyword selector that starts with the word 'add' or 11203 /// 'set'. 11204 static bool isSetterLikeSelector(Selector sel) { 11205 if (sel.isUnarySelector()) return false; 11206 11207 StringRef str = sel.getNameForSlot(0); 11208 while (!str.empty() && str.front() == '_') str = str.substr(1); 11209 if (str.startswith("set")) 11210 str = str.substr(3); 11211 else if (str.startswith("add")) { 11212 // Specially whitelist 'addOperationWithBlock:'. 11213 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 11214 return false; 11215 str = str.substr(3); 11216 } 11217 else 11218 return false; 11219 11220 if (str.empty()) return true; 11221 return !isLowercase(str.front()); 11222 } 11223 11224 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 11225 ObjCMessageExpr *Message) { 11226 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 11227 Message->getReceiverInterface(), 11228 NSAPI::ClassId_NSMutableArray); 11229 if (!IsMutableArray) { 11230 return None; 11231 } 11232 11233 Selector Sel = Message->getSelector(); 11234 11235 Optional<NSAPI::NSArrayMethodKind> MKOpt = 11236 S.NSAPIObj->getNSArrayMethodKind(Sel); 11237 if (!MKOpt) { 11238 return None; 11239 } 11240 11241 NSAPI::NSArrayMethodKind MK = *MKOpt; 11242 11243 switch (MK) { 11244 case NSAPI::NSMutableArr_addObject: 11245 case NSAPI::NSMutableArr_insertObjectAtIndex: 11246 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 11247 return 0; 11248 case NSAPI::NSMutableArr_replaceObjectAtIndex: 11249 return 1; 11250 11251 default: 11252 return None; 11253 } 11254 11255 return None; 11256 } 11257 11258 static 11259 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 11260 ObjCMessageExpr *Message) { 11261 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 11262 Message->getReceiverInterface(), 11263 NSAPI::ClassId_NSMutableDictionary); 11264 if (!IsMutableDictionary) { 11265 return None; 11266 } 11267 11268 Selector Sel = Message->getSelector(); 11269 11270 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 11271 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 11272 if (!MKOpt) { 11273 return None; 11274 } 11275 11276 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 11277 11278 switch (MK) { 11279 case NSAPI::NSMutableDict_setObjectForKey: 11280 case NSAPI::NSMutableDict_setValueForKey: 11281 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 11282 return 0; 11283 11284 default: 11285 return None; 11286 } 11287 11288 return None; 11289 } 11290 11291 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 11292 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 11293 Message->getReceiverInterface(), 11294 NSAPI::ClassId_NSMutableSet); 11295 11296 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 11297 Message->getReceiverInterface(), 11298 NSAPI::ClassId_NSMutableOrderedSet); 11299 if (!IsMutableSet && !IsMutableOrderedSet) { 11300 return None; 11301 } 11302 11303 Selector Sel = Message->getSelector(); 11304 11305 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 11306 if (!MKOpt) { 11307 return None; 11308 } 11309 11310 NSAPI::NSSetMethodKind MK = *MKOpt; 11311 11312 switch (MK) { 11313 case NSAPI::NSMutableSet_addObject: 11314 case NSAPI::NSOrderedSet_setObjectAtIndex: 11315 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 11316 case NSAPI::NSOrderedSet_insertObjectAtIndex: 11317 return 0; 11318 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 11319 return 1; 11320 } 11321 11322 return None; 11323 } 11324 11325 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 11326 if (!Message->isInstanceMessage()) { 11327 return; 11328 } 11329 11330 Optional<int> ArgOpt; 11331 11332 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 11333 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 11334 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 11335 return; 11336 } 11337 11338 int ArgIndex = *ArgOpt; 11339 11340 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 11341 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 11342 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 11343 } 11344 11345 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 11346 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11347 if (ArgRE->isObjCSelfExpr()) { 11348 Diag(Message->getSourceRange().getBegin(), 11349 diag::warn_objc_circular_container) 11350 << ArgRE->getDecl()->getName() << StringRef("super"); 11351 } 11352 } 11353 } else { 11354 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 11355 11356 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 11357 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 11358 } 11359 11360 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 11361 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11362 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 11363 ValueDecl *Decl = ReceiverRE->getDecl(); 11364 Diag(Message->getSourceRange().getBegin(), 11365 diag::warn_objc_circular_container) 11366 << Decl->getName() << Decl->getName(); 11367 if (!ArgRE->isObjCSelfExpr()) { 11368 Diag(Decl->getLocation(), 11369 diag::note_objc_circular_container_declared_here) 11370 << Decl->getName(); 11371 } 11372 } 11373 } 11374 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 11375 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 11376 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 11377 ObjCIvarDecl *Decl = IvarRE->getDecl(); 11378 Diag(Message->getSourceRange().getBegin(), 11379 diag::warn_objc_circular_container) 11380 << Decl->getName() << Decl->getName(); 11381 Diag(Decl->getLocation(), 11382 diag::note_objc_circular_container_declared_here) 11383 << Decl->getName(); 11384 } 11385 } 11386 } 11387 } 11388 } 11389 11390 /// Check a message send to see if it's likely to cause a retain cycle. 11391 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11392 // Only check instance methods whose selector looks like a setter. 11393 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 11394 return; 11395 11396 // Try to find a variable that the receiver is strongly owned by. 11397 RetainCycleOwner owner; 11398 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 11399 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 11400 return; 11401 } else { 11402 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 11403 owner.Variable = getCurMethodDecl()->getSelfDecl(); 11404 owner.Loc = msg->getSuperLoc(); 11405 owner.Range = msg->getSuperLoc(); 11406 } 11407 11408 // Check whether the receiver is captured by any of the arguments. 11409 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 11410 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 11411 return diagnoseRetainCycle(*this, capturer, owner); 11412 } 11413 11414 /// Check a property assign to see if it's likely to cause a retain cycle. 11415 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 11416 RetainCycleOwner owner; 11417 if (!findRetainCycleOwner(*this, receiver, owner)) 11418 return; 11419 11420 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 11421 diagnoseRetainCycle(*this, capturer, owner); 11422 } 11423 11424 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 11425 RetainCycleOwner Owner; 11426 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 11427 return; 11428 11429 // Because we don't have an expression for the variable, we have to set the 11430 // location explicitly here. 11431 Owner.Loc = Var->getLocation(); 11432 Owner.Range = Var->getSourceRange(); 11433 11434 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 11435 diagnoseRetainCycle(*this, Capturer, Owner); 11436 } 11437 11438 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 11439 Expr *RHS, bool isProperty) { 11440 // Check if RHS is an Objective-C object literal, which also can get 11441 // immediately zapped in a weak reference. Note that we explicitly 11442 // allow ObjCStringLiterals, since those are designed to never really die. 11443 RHS = RHS->IgnoreParenImpCasts(); 11444 11445 // This enum needs to match with the 'select' in 11446 // warn_objc_arc_literal_assign (off-by-1). 11447 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 11448 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 11449 return false; 11450 11451 S.Diag(Loc, diag::warn_arc_literal_assign) 11452 << (unsigned) Kind 11453 << (isProperty ? 0 : 1) 11454 << RHS->getSourceRange(); 11455 11456 return true; 11457 } 11458 11459 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 11460 Qualifiers::ObjCLifetime LT, 11461 Expr *RHS, bool isProperty) { 11462 // Strip off any implicit cast added to get to the one ARC-specific. 11463 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11464 if (cast->getCastKind() == CK_ARCConsumeObject) { 11465 S.Diag(Loc, diag::warn_arc_retained_assign) 11466 << (LT == Qualifiers::OCL_ExplicitNone) 11467 << (isProperty ? 0 : 1) 11468 << RHS->getSourceRange(); 11469 return true; 11470 } 11471 RHS = cast->getSubExpr(); 11472 } 11473 11474 if (LT == Qualifiers::OCL_Weak && 11475 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11476 return true; 11477 11478 return false; 11479 } 11480 11481 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11482 QualType LHS, Expr *RHS) { 11483 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11484 11485 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11486 return false; 11487 11488 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11489 return true; 11490 11491 return false; 11492 } 11493 11494 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11495 Expr *LHS, Expr *RHS) { 11496 QualType LHSType; 11497 // PropertyRef on LHS type need be directly obtained from 11498 // its declaration as it has a PseudoType. 11499 ObjCPropertyRefExpr *PRE 11500 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11501 if (PRE && !PRE->isImplicitProperty()) { 11502 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11503 if (PD) 11504 LHSType = PD->getType(); 11505 } 11506 11507 if (LHSType.isNull()) 11508 LHSType = LHS->getType(); 11509 11510 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11511 11512 if (LT == Qualifiers::OCL_Weak) { 11513 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11514 getCurFunction()->markSafeWeakUse(LHS); 11515 } 11516 11517 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11518 return; 11519 11520 // FIXME. Check for other life times. 11521 if (LT != Qualifiers::OCL_None) 11522 return; 11523 11524 if (PRE) { 11525 if (PRE->isImplicitProperty()) 11526 return; 11527 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11528 if (!PD) 11529 return; 11530 11531 unsigned Attributes = PD->getPropertyAttributes(); 11532 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11533 // when 'assign' attribute was not explicitly specified 11534 // by user, ignore it and rely on property type itself 11535 // for lifetime info. 11536 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11537 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11538 LHSType->isObjCRetainableType()) 11539 return; 11540 11541 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11542 if (cast->getCastKind() == CK_ARCConsumeObject) { 11543 Diag(Loc, diag::warn_arc_retained_property_assign) 11544 << RHS->getSourceRange(); 11545 return; 11546 } 11547 RHS = cast->getSubExpr(); 11548 } 11549 } 11550 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11551 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11552 return; 11553 } 11554 } 11555 } 11556 11557 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11558 11559 namespace { 11560 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11561 SourceLocation StmtLoc, 11562 const NullStmt *Body) { 11563 // Do not warn if the body is a macro that expands to nothing, e.g: 11564 // 11565 // #define CALL(x) 11566 // if (condition) 11567 // CALL(0); 11568 // 11569 if (Body->hasLeadingEmptyMacro()) 11570 return false; 11571 11572 // Get line numbers of statement and body. 11573 bool StmtLineInvalid; 11574 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11575 &StmtLineInvalid); 11576 if (StmtLineInvalid) 11577 return false; 11578 11579 bool BodyLineInvalid; 11580 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11581 &BodyLineInvalid); 11582 if (BodyLineInvalid) 11583 return false; 11584 11585 // Warn if null statement and body are on the same line. 11586 if (StmtLine != BodyLine) 11587 return false; 11588 11589 return true; 11590 } 11591 } // end anonymous namespace 11592 11593 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11594 const Stmt *Body, 11595 unsigned DiagID) { 11596 // Since this is a syntactic check, don't emit diagnostic for template 11597 // instantiations, this just adds noise. 11598 if (CurrentInstantiationScope) 11599 return; 11600 11601 // The body should be a null statement. 11602 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11603 if (!NBody) 11604 return; 11605 11606 // Do the usual checks. 11607 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11608 return; 11609 11610 Diag(NBody->getSemiLoc(), DiagID); 11611 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11612 } 11613 11614 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11615 const Stmt *PossibleBody) { 11616 assert(!CurrentInstantiationScope); // Ensured by caller 11617 11618 SourceLocation StmtLoc; 11619 const Stmt *Body; 11620 unsigned DiagID; 11621 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11622 StmtLoc = FS->getRParenLoc(); 11623 Body = FS->getBody(); 11624 DiagID = diag::warn_empty_for_body; 11625 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11626 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11627 Body = WS->getBody(); 11628 DiagID = diag::warn_empty_while_body; 11629 } else 11630 return; // Neither `for' nor `while'. 11631 11632 // The body should be a null statement. 11633 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11634 if (!NBody) 11635 return; 11636 11637 // Skip expensive checks if diagnostic is disabled. 11638 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11639 return; 11640 11641 // Do the usual checks. 11642 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11643 return; 11644 11645 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11646 // noise level low, emit diagnostics only if for/while is followed by a 11647 // CompoundStmt, e.g.: 11648 // for (int i = 0; i < n; i++); 11649 // { 11650 // a(i); 11651 // } 11652 // or if for/while is followed by a statement with more indentation 11653 // than for/while itself: 11654 // for (int i = 0; i < n; i++); 11655 // a(i); 11656 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11657 if (!ProbableTypo) { 11658 bool BodyColInvalid; 11659 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11660 PossibleBody->getLocStart(), 11661 &BodyColInvalid); 11662 if (BodyColInvalid) 11663 return; 11664 11665 bool StmtColInvalid; 11666 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11667 S->getLocStart(), 11668 &StmtColInvalid); 11669 if (StmtColInvalid) 11670 return; 11671 11672 if (BodyCol > StmtCol) 11673 ProbableTypo = true; 11674 } 11675 11676 if (ProbableTypo) { 11677 Diag(NBody->getSemiLoc(), DiagID); 11678 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11679 } 11680 } 11681 11682 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11683 11684 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11685 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11686 SourceLocation OpLoc) { 11687 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11688 return; 11689 11690 if (inTemplateInstantiation()) 11691 return; 11692 11693 // Strip parens and casts away. 11694 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11695 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11696 11697 // Check for a call expression 11698 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11699 if (!CE || CE->getNumArgs() != 1) 11700 return; 11701 11702 // Check for a call to std::move 11703 const FunctionDecl *FD = CE->getDirectCallee(); 11704 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 11705 !FD->getIdentifier()->isStr("move")) 11706 return; 11707 11708 // Get argument from std::move 11709 RHSExpr = CE->getArg(0); 11710 11711 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11712 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11713 11714 // Two DeclRefExpr's, check that the decls are the same. 11715 if (LHSDeclRef && RHSDeclRef) { 11716 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11717 return; 11718 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11719 RHSDeclRef->getDecl()->getCanonicalDecl()) 11720 return; 11721 11722 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11723 << LHSExpr->getSourceRange() 11724 << RHSExpr->getSourceRange(); 11725 return; 11726 } 11727 11728 // Member variables require a different approach to check for self moves. 11729 // MemberExpr's are the same if every nested MemberExpr refers to the same 11730 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11731 // the base Expr's are CXXThisExpr's. 11732 const Expr *LHSBase = LHSExpr; 11733 const Expr *RHSBase = RHSExpr; 11734 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11735 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11736 if (!LHSME || !RHSME) 11737 return; 11738 11739 while (LHSME && RHSME) { 11740 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11741 RHSME->getMemberDecl()->getCanonicalDecl()) 11742 return; 11743 11744 LHSBase = LHSME->getBase(); 11745 RHSBase = RHSME->getBase(); 11746 LHSME = dyn_cast<MemberExpr>(LHSBase); 11747 RHSME = dyn_cast<MemberExpr>(RHSBase); 11748 } 11749 11750 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11751 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11752 if (LHSDeclRef && RHSDeclRef) { 11753 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11754 return; 11755 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11756 RHSDeclRef->getDecl()->getCanonicalDecl()) 11757 return; 11758 11759 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11760 << LHSExpr->getSourceRange() 11761 << RHSExpr->getSourceRange(); 11762 return; 11763 } 11764 11765 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11766 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11767 << LHSExpr->getSourceRange() 11768 << RHSExpr->getSourceRange(); 11769 } 11770 11771 //===--- Layout compatibility ----------------------------------------------// 11772 11773 namespace { 11774 11775 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11776 11777 /// \brief Check if two enumeration types are layout-compatible. 11778 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11779 // C++11 [dcl.enum] p8: 11780 // Two enumeration types are layout-compatible if they have the same 11781 // underlying type. 11782 return ED1->isComplete() && ED2->isComplete() && 11783 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11784 } 11785 11786 /// \brief Check if two fields are layout-compatible. 11787 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11788 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11789 return false; 11790 11791 if (Field1->isBitField() != Field2->isBitField()) 11792 return false; 11793 11794 if (Field1->isBitField()) { 11795 // Make sure that the bit-fields are the same length. 11796 unsigned Bits1 = Field1->getBitWidthValue(C); 11797 unsigned Bits2 = Field2->getBitWidthValue(C); 11798 11799 if (Bits1 != Bits2) 11800 return false; 11801 } 11802 11803 return true; 11804 } 11805 11806 /// \brief Check if two standard-layout structs are layout-compatible. 11807 /// (C++11 [class.mem] p17) 11808 bool isLayoutCompatibleStruct(ASTContext &C, 11809 RecordDecl *RD1, 11810 RecordDecl *RD2) { 11811 // If both records are C++ classes, check that base classes match. 11812 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11813 // If one of records is a CXXRecordDecl we are in C++ mode, 11814 // thus the other one is a CXXRecordDecl, too. 11815 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11816 // Check number of base classes. 11817 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11818 return false; 11819 11820 // Check the base classes. 11821 for (CXXRecordDecl::base_class_const_iterator 11822 Base1 = D1CXX->bases_begin(), 11823 BaseEnd1 = D1CXX->bases_end(), 11824 Base2 = D2CXX->bases_begin(); 11825 Base1 != BaseEnd1; 11826 ++Base1, ++Base2) { 11827 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11828 return false; 11829 } 11830 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11831 // If only RD2 is a C++ class, it should have zero base classes. 11832 if (D2CXX->getNumBases() > 0) 11833 return false; 11834 } 11835 11836 // Check the fields. 11837 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11838 Field2End = RD2->field_end(), 11839 Field1 = RD1->field_begin(), 11840 Field1End = RD1->field_end(); 11841 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11842 if (!isLayoutCompatible(C, *Field1, *Field2)) 11843 return false; 11844 } 11845 if (Field1 != Field1End || Field2 != Field2End) 11846 return false; 11847 11848 return true; 11849 } 11850 11851 /// \brief Check if two standard-layout unions are layout-compatible. 11852 /// (C++11 [class.mem] p18) 11853 bool isLayoutCompatibleUnion(ASTContext &C, 11854 RecordDecl *RD1, 11855 RecordDecl *RD2) { 11856 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11857 for (auto *Field2 : RD2->fields()) 11858 UnmatchedFields.insert(Field2); 11859 11860 for (auto *Field1 : RD1->fields()) { 11861 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11862 I = UnmatchedFields.begin(), 11863 E = UnmatchedFields.end(); 11864 11865 for ( ; I != E; ++I) { 11866 if (isLayoutCompatible(C, Field1, *I)) { 11867 bool Result = UnmatchedFields.erase(*I); 11868 (void) Result; 11869 assert(Result); 11870 break; 11871 } 11872 } 11873 if (I == E) 11874 return false; 11875 } 11876 11877 return UnmatchedFields.empty(); 11878 } 11879 11880 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11881 if (RD1->isUnion() != RD2->isUnion()) 11882 return false; 11883 11884 if (RD1->isUnion()) 11885 return isLayoutCompatibleUnion(C, RD1, RD2); 11886 else 11887 return isLayoutCompatibleStruct(C, RD1, RD2); 11888 } 11889 11890 /// \brief Check if two types are layout-compatible in C++11 sense. 11891 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 11892 if (T1.isNull() || T2.isNull()) 11893 return false; 11894 11895 // C++11 [basic.types] p11: 11896 // If two types T1 and T2 are the same type, then T1 and T2 are 11897 // layout-compatible types. 11898 if (C.hasSameType(T1, T2)) 11899 return true; 11900 11901 T1 = T1.getCanonicalType().getUnqualifiedType(); 11902 T2 = T2.getCanonicalType().getUnqualifiedType(); 11903 11904 const Type::TypeClass TC1 = T1->getTypeClass(); 11905 const Type::TypeClass TC2 = T2->getTypeClass(); 11906 11907 if (TC1 != TC2) 11908 return false; 11909 11910 if (TC1 == Type::Enum) { 11911 return isLayoutCompatible(C, 11912 cast<EnumType>(T1)->getDecl(), 11913 cast<EnumType>(T2)->getDecl()); 11914 } else if (TC1 == Type::Record) { 11915 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 11916 return false; 11917 11918 return isLayoutCompatible(C, 11919 cast<RecordType>(T1)->getDecl(), 11920 cast<RecordType>(T2)->getDecl()); 11921 } 11922 11923 return false; 11924 } 11925 } // end anonymous namespace 11926 11927 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 11928 11929 namespace { 11930 /// \brief Given a type tag expression find the type tag itself. 11931 /// 11932 /// \param TypeExpr Type tag expression, as it appears in user's code. 11933 /// 11934 /// \param VD Declaration of an identifier that appears in a type tag. 11935 /// 11936 /// \param MagicValue Type tag magic value. 11937 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 11938 const ValueDecl **VD, uint64_t *MagicValue) { 11939 while(true) { 11940 if (!TypeExpr) 11941 return false; 11942 11943 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 11944 11945 switch (TypeExpr->getStmtClass()) { 11946 case Stmt::UnaryOperatorClass: { 11947 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 11948 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 11949 TypeExpr = UO->getSubExpr(); 11950 continue; 11951 } 11952 return false; 11953 } 11954 11955 case Stmt::DeclRefExprClass: { 11956 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 11957 *VD = DRE->getDecl(); 11958 return true; 11959 } 11960 11961 case Stmt::IntegerLiteralClass: { 11962 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 11963 llvm::APInt MagicValueAPInt = IL->getValue(); 11964 if (MagicValueAPInt.getActiveBits() <= 64) { 11965 *MagicValue = MagicValueAPInt.getZExtValue(); 11966 return true; 11967 } else 11968 return false; 11969 } 11970 11971 case Stmt::BinaryConditionalOperatorClass: 11972 case Stmt::ConditionalOperatorClass: { 11973 const AbstractConditionalOperator *ACO = 11974 cast<AbstractConditionalOperator>(TypeExpr); 11975 bool Result; 11976 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 11977 if (Result) 11978 TypeExpr = ACO->getTrueExpr(); 11979 else 11980 TypeExpr = ACO->getFalseExpr(); 11981 continue; 11982 } 11983 return false; 11984 } 11985 11986 case Stmt::BinaryOperatorClass: { 11987 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 11988 if (BO->getOpcode() == BO_Comma) { 11989 TypeExpr = BO->getRHS(); 11990 continue; 11991 } 11992 return false; 11993 } 11994 11995 default: 11996 return false; 11997 } 11998 } 11999 } 12000 12001 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 12002 /// 12003 /// \param TypeExpr Expression that specifies a type tag. 12004 /// 12005 /// \param MagicValues Registered magic values. 12006 /// 12007 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12008 /// kind. 12009 /// 12010 /// \param TypeInfo Information about the corresponding C type. 12011 /// 12012 /// \returns true if the corresponding C type was found. 12013 bool GetMatchingCType( 12014 const IdentifierInfo *ArgumentKind, 12015 const Expr *TypeExpr, const ASTContext &Ctx, 12016 const llvm::DenseMap<Sema::TypeTagMagicValue, 12017 Sema::TypeTagData> *MagicValues, 12018 bool &FoundWrongKind, 12019 Sema::TypeTagData &TypeInfo) { 12020 FoundWrongKind = false; 12021 12022 // Variable declaration that has type_tag_for_datatype attribute. 12023 const ValueDecl *VD = nullptr; 12024 12025 uint64_t MagicValue; 12026 12027 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12028 return false; 12029 12030 if (VD) { 12031 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12032 if (I->getArgumentKind() != ArgumentKind) { 12033 FoundWrongKind = true; 12034 return false; 12035 } 12036 TypeInfo.Type = I->getMatchingCType(); 12037 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12038 TypeInfo.MustBeNull = I->getMustBeNull(); 12039 return true; 12040 } 12041 return false; 12042 } 12043 12044 if (!MagicValues) 12045 return false; 12046 12047 llvm::DenseMap<Sema::TypeTagMagicValue, 12048 Sema::TypeTagData>::const_iterator I = 12049 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12050 if (I == MagicValues->end()) 12051 return false; 12052 12053 TypeInfo = I->second; 12054 return true; 12055 } 12056 } // end anonymous namespace 12057 12058 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12059 uint64_t MagicValue, QualType Type, 12060 bool LayoutCompatible, 12061 bool MustBeNull) { 12062 if (!TypeTagForDatatypeMagicValues) 12063 TypeTagForDatatypeMagicValues.reset( 12064 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12065 12066 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12067 (*TypeTagForDatatypeMagicValues)[Magic] = 12068 TypeTagData(Type, LayoutCompatible, MustBeNull); 12069 } 12070 12071 namespace { 12072 bool IsSameCharType(QualType T1, QualType T2) { 12073 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12074 if (!BT1) 12075 return false; 12076 12077 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12078 if (!BT2) 12079 return false; 12080 12081 BuiltinType::Kind T1Kind = BT1->getKind(); 12082 BuiltinType::Kind T2Kind = BT2->getKind(); 12083 12084 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12085 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12086 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12087 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12088 } 12089 } // end anonymous namespace 12090 12091 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12092 const Expr * const *ExprArgs) { 12093 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12094 bool IsPointerAttr = Attr->getIsPointer(); 12095 12096 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 12097 bool FoundWrongKind; 12098 TypeTagData TypeInfo; 12099 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12100 TypeTagForDatatypeMagicValues.get(), 12101 FoundWrongKind, TypeInfo)) { 12102 if (FoundWrongKind) 12103 Diag(TypeTagExpr->getExprLoc(), 12104 diag::warn_type_tag_for_datatype_wrong_kind) 12105 << TypeTagExpr->getSourceRange(); 12106 return; 12107 } 12108 12109 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 12110 if (IsPointerAttr) { 12111 // Skip implicit cast of pointer to `void *' (as a function argument). 12112 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12113 if (ICE->getType()->isVoidPointerType() && 12114 ICE->getCastKind() == CK_BitCast) 12115 ArgumentExpr = ICE->getSubExpr(); 12116 } 12117 QualType ArgumentType = ArgumentExpr->getType(); 12118 12119 // Passing a `void*' pointer shouldn't trigger a warning. 12120 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12121 return; 12122 12123 if (TypeInfo.MustBeNull) { 12124 // Type tag with matching void type requires a null pointer. 12125 if (!ArgumentExpr->isNullPointerConstant(Context, 12126 Expr::NPC_ValueDependentIsNotNull)) { 12127 Diag(ArgumentExpr->getExprLoc(), 12128 diag::warn_type_safety_null_pointer_required) 12129 << ArgumentKind->getName() 12130 << ArgumentExpr->getSourceRange() 12131 << TypeTagExpr->getSourceRange(); 12132 } 12133 return; 12134 } 12135 12136 QualType RequiredType = TypeInfo.Type; 12137 if (IsPointerAttr) 12138 RequiredType = Context.getPointerType(RequiredType); 12139 12140 bool mismatch = false; 12141 if (!TypeInfo.LayoutCompatible) { 12142 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12143 12144 // C++11 [basic.fundamental] p1: 12145 // Plain char, signed char, and unsigned char are three distinct types. 12146 // 12147 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12148 // char' depending on the current char signedness mode. 12149 if (mismatch) 12150 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12151 RequiredType->getPointeeType())) || 12152 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12153 mismatch = false; 12154 } else 12155 if (IsPointerAttr) 12156 mismatch = !isLayoutCompatible(Context, 12157 ArgumentType->getPointeeType(), 12158 RequiredType->getPointeeType()); 12159 else 12160 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12161 12162 if (mismatch) 12163 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12164 << ArgumentType << ArgumentKind 12165 << TypeInfo.LayoutCompatible << RequiredType 12166 << ArgumentExpr->getSourceRange() 12167 << TypeTagExpr->getSourceRange(); 12168 } 12169 12170 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12171 CharUnits Alignment) { 12172 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12173 } 12174 12175 void Sema::DiagnoseMisalignedMembers() { 12176 for (MisalignedMember &m : MisalignedMembers) { 12177 const NamedDecl *ND = m.RD; 12178 if (ND->getName().empty()) { 12179 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12180 ND = TD; 12181 } 12182 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12183 << m.MD << ND << m.E->getSourceRange(); 12184 } 12185 MisalignedMembers.clear(); 12186 } 12187 12188 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12189 E = E->IgnoreParens(); 12190 if (!T->isPointerType() && !T->isIntegerType()) 12191 return; 12192 if (isa<UnaryOperator>(E) && 12193 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 12194 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 12195 if (isa<MemberExpr>(Op)) { 12196 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 12197 MisalignedMember(Op)); 12198 if (MA != MisalignedMembers.end() && 12199 (T->isIntegerType() || 12200 (T->isPointerType() && 12201 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment))) 12202 MisalignedMembers.erase(MA); 12203 } 12204 } 12205 } 12206 12207 void Sema::RefersToMemberWithReducedAlignment( 12208 Expr *E, 12209 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12210 Action) { 12211 const auto *ME = dyn_cast<MemberExpr>(E); 12212 if (!ME) 12213 return; 12214 12215 // No need to check expressions with an __unaligned-qualified type. 12216 if (E->getType().getQualifiers().hasUnaligned()) 12217 return; 12218 12219 // For a chain of MemberExpr like "a.b.c.d" this list 12220 // will keep FieldDecl's like [d, c, b]. 12221 SmallVector<FieldDecl *, 4> ReverseMemberChain; 12222 const MemberExpr *TopME = nullptr; 12223 bool AnyIsPacked = false; 12224 do { 12225 QualType BaseType = ME->getBase()->getType(); 12226 if (ME->isArrow()) 12227 BaseType = BaseType->getPointeeType(); 12228 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 12229 if (RD->isInvalidDecl()) 12230 return; 12231 12232 ValueDecl *MD = ME->getMemberDecl(); 12233 auto *FD = dyn_cast<FieldDecl>(MD); 12234 // We do not care about non-data members. 12235 if (!FD || FD->isInvalidDecl()) 12236 return; 12237 12238 AnyIsPacked = 12239 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 12240 ReverseMemberChain.push_back(FD); 12241 12242 TopME = ME; 12243 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 12244 } while (ME); 12245 assert(TopME && "We did not compute a topmost MemberExpr!"); 12246 12247 // Not the scope of this diagnostic. 12248 if (!AnyIsPacked) 12249 return; 12250 12251 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 12252 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 12253 // TODO: The innermost base of the member expression may be too complicated. 12254 // For now, just disregard these cases. This is left for future 12255 // improvement. 12256 if (!DRE && !isa<CXXThisExpr>(TopBase)) 12257 return; 12258 12259 // Alignment expected by the whole expression. 12260 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 12261 12262 // No need to do anything else with this case. 12263 if (ExpectedAlignment.isOne()) 12264 return; 12265 12266 // Synthesize offset of the whole access. 12267 CharUnits Offset; 12268 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 12269 I++) { 12270 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 12271 } 12272 12273 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 12274 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 12275 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 12276 12277 // The base expression of the innermost MemberExpr may give 12278 // stronger guarantees than the class containing the member. 12279 if (DRE && !TopME->isArrow()) { 12280 const ValueDecl *VD = DRE->getDecl(); 12281 if (!VD->getType()->isReferenceType()) 12282 CompleteObjectAlignment = 12283 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 12284 } 12285 12286 // Check if the synthesized offset fulfills the alignment. 12287 if (Offset % ExpectedAlignment != 0 || 12288 // It may fulfill the offset it but the effective alignment may still be 12289 // lower than the expected expression alignment. 12290 CompleteObjectAlignment < ExpectedAlignment) { 12291 // If this happens, we want to determine a sensible culprit of this. 12292 // Intuitively, watching the chain of member expressions from right to 12293 // left, we start with the required alignment (as required by the field 12294 // type) but some packed attribute in that chain has reduced the alignment. 12295 // It may happen that another packed structure increases it again. But if 12296 // we are here such increase has not been enough. So pointing the first 12297 // FieldDecl that either is packed or else its RecordDecl is, 12298 // seems reasonable. 12299 FieldDecl *FD = nullptr; 12300 CharUnits Alignment; 12301 for (FieldDecl *FDI : ReverseMemberChain) { 12302 if (FDI->hasAttr<PackedAttr>() || 12303 FDI->getParent()->hasAttr<PackedAttr>()) { 12304 FD = FDI; 12305 Alignment = std::min( 12306 Context.getTypeAlignInChars(FD->getType()), 12307 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 12308 break; 12309 } 12310 } 12311 assert(FD && "We did not find a packed FieldDecl!"); 12312 Action(E, FD->getParent(), FD, Alignment); 12313 } 12314 } 12315 12316 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 12317 using namespace std::placeholders; 12318 RefersToMemberWithReducedAlignment( 12319 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 12320 _2, _3, _4)); 12321 } 12322 12323