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/TargetBuiltins.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/ScopeInfo.h" 34 #include "clang/Sema/Sema.h" 35 #include "clang/Sema/SemaInternal.h" 36 #include "llvm/ADT/STLExtras.h" 37 #include "llvm/ADT/SmallBitVector.h" 38 #include "llvm/ADT/SmallString.h" 39 #include "llvm/Support/ConvertUTF.h" 40 #include "llvm/Support/Format.h" 41 #include "llvm/Support/Locale.h" 42 #include "llvm/Support/raw_ostream.h" 43 44 using namespace clang; 45 using namespace sema; 46 47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 48 unsigned ByteNo) const { 49 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 50 Context.getTargetInfo()); 51 } 52 53 /// Checks that a call expression's argument count is the desired number. 54 /// This is useful when doing custom type-checking. Returns true on error. 55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 56 unsigned argCount = call->getNumArgs(); 57 if (argCount == desiredArgCount) return false; 58 59 if (argCount < desiredArgCount) 60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 61 << 0 /*function call*/ << desiredArgCount << argCount 62 << call->getSourceRange(); 63 64 // Highlight all the excess arguments. 65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 66 call->getArg(argCount - 1)->getLocEnd()); 67 68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 69 << 0 /*function call*/ << desiredArgCount << argCount 70 << call->getArg(1)->getSourceRange(); 71 } 72 73 /// Check that the first argument to __builtin_annotation is an integer 74 /// and the second argument is a non-wide string literal. 75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 76 if (checkArgCount(S, TheCall, 2)) 77 return true; 78 79 // First argument should be an integer. 80 Expr *ValArg = TheCall->getArg(0); 81 QualType Ty = ValArg->getType(); 82 if (!Ty->isIntegerType()) { 83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 84 << ValArg->getSourceRange(); 85 return true; 86 } 87 88 // Second argument should be a constant string. 89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 91 if (!Literal || !Literal->isAscii()) { 92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 93 << StrArg->getSourceRange(); 94 return true; 95 } 96 97 TheCall->setType(Ty); 98 return false; 99 } 100 101 /// Check that the argument to __builtin_addressof is a glvalue, and set the 102 /// result type to the corresponding pointer type. 103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 104 if (checkArgCount(S, TheCall, 1)) 105 return true; 106 107 ExprResult Arg(TheCall->getArg(0)); 108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 109 if (ResultType.isNull()) 110 return true; 111 112 TheCall->setArg(0, Arg.get()); 113 TheCall->setType(ResultType); 114 return false; 115 } 116 117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 118 if (checkArgCount(S, TheCall, 3)) 119 return true; 120 121 // First two arguments should be integers. 122 for (unsigned I = 0; I < 2; ++I) { 123 Expr *Arg = TheCall->getArg(I); 124 QualType Ty = Arg->getType(); 125 if (!Ty->isIntegerType()) { 126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 127 << Ty << Arg->getSourceRange(); 128 return true; 129 } 130 } 131 132 // Third argument should be a pointer to a non-const integer. 133 // IRGen correctly handles volatile, restrict, and address spaces, and 134 // the other qualifiers aren't possible. 135 { 136 Expr *Arg = TheCall->getArg(2); 137 QualType Ty = Arg->getType(); 138 const auto *PtrTy = Ty->getAs<PointerType>(); 139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 140 !PtrTy->getPointeeType().isConstQualified())) { 141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 142 << Ty << Arg->getSourceRange(); 143 return true; 144 } 145 } 146 147 return false; 148 } 149 150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 151 CallExpr *TheCall, unsigned SizeIdx, 152 unsigned DstSizeIdx) { 153 if (TheCall->getNumArgs() <= SizeIdx || 154 TheCall->getNumArgs() <= DstSizeIdx) 155 return; 156 157 const Expr *SizeArg = TheCall->getArg(SizeIdx); 158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 159 160 llvm::APSInt Size, DstSize; 161 162 // find out if both sizes are known at compile time 163 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 165 return; 166 167 if (Size.ule(DstSize)) 168 return; 169 170 // confirmed overflow so generate the diagnostic. 171 IdentifierInfo *FnName = FDecl->getIdentifier(); 172 SourceLocation SL = TheCall->getLocStart(); 173 SourceRange SR = TheCall->getSourceRange(); 174 175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 176 } 177 178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 179 if (checkArgCount(S, BuiltinCall, 2)) 180 return true; 181 182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 184 Expr *Call = BuiltinCall->getArg(0); 185 Expr *Chain = BuiltinCall->getArg(1); 186 187 if (Call->getStmtClass() != Stmt::CallExprClass) { 188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 189 << Call->getSourceRange(); 190 return true; 191 } 192 193 auto CE = cast<CallExpr>(Call); 194 if (CE->getCallee()->getType()->isBlockPointerType()) { 195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 196 << Call->getSourceRange(); 197 return true; 198 } 199 200 const Decl *TargetDecl = CE->getCalleeDecl(); 201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 202 if (FD->getBuiltinID()) { 203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 204 << Call->getSourceRange(); 205 return true; 206 } 207 208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 210 << Call->getSourceRange(); 211 return true; 212 } 213 214 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 215 if (ChainResult.isInvalid()) 216 return true; 217 if (!ChainResult.get()->getType()->isPointerType()) { 218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 219 << Chain->getSourceRange(); 220 return true; 221 } 222 223 QualType ReturnTy = CE->getCallReturnType(S.Context); 224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 225 QualType BuiltinTy = S.Context.getFunctionType( 226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 228 229 Builtin = 230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 231 232 BuiltinCall->setType(CE->getType()); 233 BuiltinCall->setValueKind(CE->getValueKind()); 234 BuiltinCall->setObjectKind(CE->getObjectKind()); 235 BuiltinCall->setCallee(Builtin); 236 BuiltinCall->setArg(1, ChainResult.get()); 237 238 return false; 239 } 240 241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 242 Scope::ScopeFlags NeededScopeFlags, 243 unsigned DiagID) { 244 // Scopes aren't available during instantiation. Fortunately, builtin 245 // functions cannot be template args so they cannot be formed through template 246 // instantiation. Therefore checking once during the parse is sufficient. 247 if (!SemaRef.ActiveTemplateInstantiations.empty()) 248 return false; 249 250 Scope *S = SemaRef.getCurScope(); 251 while (S && !S->isSEHExceptScope()) 252 S = S->getParent(); 253 if (!S || !(S->getFlags() & NeededScopeFlags)) { 254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 255 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 256 << DRE->getDecl()->getIdentifier(); 257 return true; 258 } 259 260 return false; 261 } 262 263 static inline bool isBlockPointer(Expr *Arg) { 264 return Arg->getType()->isBlockPointerType(); 265 } 266 267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 268 /// void*, which is a requirement of device side enqueue. 269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 270 const BlockPointerType *BPT = 271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 272 ArrayRef<QualType> Params = 273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 274 unsigned ArgCounter = 0; 275 bool IllegalParams = false; 276 // Iterate through the block parameters until either one is found that is not 277 // a local void*, or the block is valid. 278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 279 I != E; ++I, ++ArgCounter) { 280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 281 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 282 LangAS::opencl_local) { 283 // Get the location of the error. If a block literal has been passed 284 // (BlockExpr) then we can point straight to the offending argument, 285 // else we just point to the variable reference. 286 SourceLocation ErrorLoc; 287 if (isa<BlockExpr>(BlockArg)) { 288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 290 } else if (isa<DeclRefExpr>(BlockArg)) { 291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 292 } 293 S.Diag(ErrorLoc, 294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 295 IllegalParams = true; 296 } 297 } 298 299 return IllegalParams; 300 } 301 302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 303 /// get_kernel_work_group_size 304 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 306 if (checkArgCount(S, TheCall, 1)) 307 return true; 308 309 Expr *BlockArg = TheCall->getArg(0); 310 if (!isBlockPointer(BlockArg)) { 311 S.Diag(BlockArg->getLocStart(), 312 diag::err_opencl_enqueue_kernel_expected_type) << "block"; 313 return true; 314 } 315 return checkOpenCLBlockArgs(S, BlockArg); 316 } 317 318 /// Diagnose integer type and any valid implicit convertion to it. 319 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 320 const QualType &IntType); 321 322 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 323 unsigned Start, unsigned End) { 324 bool IllegalParams = false; 325 for (unsigned I = Start; I <= End; ++I) 326 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 327 S.Context.getSizeType()); 328 return IllegalParams; 329 } 330 331 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 332 /// 'local void*' parameter of passed block. 333 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 334 Expr *BlockArg, 335 unsigned NumNonVarArgs) { 336 const BlockPointerType *BPT = 337 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 338 unsigned NumBlockParams = 339 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 340 unsigned TotalNumArgs = TheCall->getNumArgs(); 341 342 // For each argument passed to the block, a corresponding uint needs to 343 // be passed to describe the size of the local memory. 344 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 345 S.Diag(TheCall->getLocStart(), 346 diag::err_opencl_enqueue_kernel_local_size_args); 347 return true; 348 } 349 350 // Check that the sizes of the local memory are specified by integers. 351 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 352 TotalNumArgs - 1); 353 } 354 355 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 356 /// overload formats specified in Table 6.13.17.1. 357 /// int enqueue_kernel(queue_t queue, 358 /// kernel_enqueue_flags_t flags, 359 /// const ndrange_t ndrange, 360 /// void (^block)(void)) 361 /// int enqueue_kernel(queue_t queue, 362 /// kernel_enqueue_flags_t flags, 363 /// const ndrange_t ndrange, 364 /// uint num_events_in_wait_list, 365 /// clk_event_t *event_wait_list, 366 /// clk_event_t *event_ret, 367 /// void (^block)(void)) 368 /// int enqueue_kernel(queue_t queue, 369 /// kernel_enqueue_flags_t flags, 370 /// const ndrange_t ndrange, 371 /// void (^block)(local void*, ...), 372 /// uint size0, ...) 373 /// int enqueue_kernel(queue_t queue, 374 /// kernel_enqueue_flags_t flags, 375 /// const ndrange_t ndrange, 376 /// uint num_events_in_wait_list, 377 /// clk_event_t *event_wait_list, 378 /// clk_event_t *event_ret, 379 /// void (^block)(local void*, ...), 380 /// uint size0, ...) 381 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 382 unsigned NumArgs = TheCall->getNumArgs(); 383 384 if (NumArgs < 4) { 385 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 386 return true; 387 } 388 389 Expr *Arg0 = TheCall->getArg(0); 390 Expr *Arg1 = TheCall->getArg(1); 391 Expr *Arg2 = TheCall->getArg(2); 392 Expr *Arg3 = TheCall->getArg(3); 393 394 // First argument always needs to be a queue_t type. 395 if (!Arg0->getType()->isQueueT()) { 396 S.Diag(TheCall->getArg(0)->getLocStart(), 397 diag::err_opencl_enqueue_kernel_expected_type) 398 << S.Context.OCLQueueTy; 399 return true; 400 } 401 402 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 403 if (!Arg1->getType()->isIntegerType()) { 404 S.Diag(TheCall->getArg(1)->getLocStart(), 405 diag::err_opencl_enqueue_kernel_expected_type) 406 << "'kernel_enqueue_flags_t' (i.e. uint)"; 407 return true; 408 } 409 410 // Third argument is always an ndrange_t type. 411 if (!Arg2->getType()->isNDRangeT()) { 412 S.Diag(TheCall->getArg(2)->getLocStart(), 413 diag::err_opencl_enqueue_kernel_expected_type) 414 << S.Context.OCLNDRangeTy; 415 return true; 416 } 417 418 // With four arguments, there is only one form that the function could be 419 // called in: no events and no variable arguments. 420 if (NumArgs == 4) { 421 // check that the last argument is the right block type. 422 if (!isBlockPointer(Arg3)) { 423 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 424 << "block"; 425 return true; 426 } 427 // we have a block type, check the prototype 428 const BlockPointerType *BPT = 429 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 430 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 431 S.Diag(Arg3->getLocStart(), 432 diag::err_opencl_enqueue_kernel_blocks_no_args); 433 return true; 434 } 435 return false; 436 } 437 // we can have block + varargs. 438 if (isBlockPointer(Arg3)) 439 return (checkOpenCLBlockArgs(S, Arg3) || 440 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 441 // last two cases with either exactly 7 args or 7 args and varargs. 442 if (NumArgs >= 7) { 443 // check common block argument. 444 Expr *Arg6 = TheCall->getArg(6); 445 if (!isBlockPointer(Arg6)) { 446 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 447 << "block"; 448 return true; 449 } 450 if (checkOpenCLBlockArgs(S, Arg6)) 451 return true; 452 453 // Forth argument has to be any integer type. 454 if (!Arg3->getType()->isIntegerType()) { 455 S.Diag(TheCall->getArg(3)->getLocStart(), 456 diag::err_opencl_enqueue_kernel_expected_type) 457 << "integer"; 458 return true; 459 } 460 // check remaining common arguments. 461 Expr *Arg4 = TheCall->getArg(4); 462 Expr *Arg5 = TheCall->getArg(5); 463 464 // Fifth argument is always passed as a pointer to clk_event_t. 465 if (!Arg4->isNullPointerConstant(S.Context, 466 Expr::NPC_ValueDependentIsNotNull) && 467 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 468 S.Diag(TheCall->getArg(4)->getLocStart(), 469 diag::err_opencl_enqueue_kernel_expected_type) 470 << S.Context.getPointerType(S.Context.OCLClkEventTy); 471 return true; 472 } 473 474 // Sixth argument is always passed as a pointer to clk_event_t. 475 if (!Arg5->isNullPointerConstant(S.Context, 476 Expr::NPC_ValueDependentIsNotNull) && 477 !(Arg5->getType()->isPointerType() && 478 Arg5->getType()->getPointeeType()->isClkEventT())) { 479 S.Diag(TheCall->getArg(5)->getLocStart(), 480 diag::err_opencl_enqueue_kernel_expected_type) 481 << S.Context.getPointerType(S.Context.OCLClkEventTy); 482 return true; 483 } 484 485 if (NumArgs == 7) 486 return false; 487 488 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 489 } 490 491 // None of the specific case has been detected, give generic error 492 S.Diag(TheCall->getLocStart(), 493 diag::err_opencl_enqueue_kernel_incorrect_args); 494 return true; 495 } 496 497 /// Returns OpenCL access qual. 498 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 499 return D->getAttr<OpenCLAccessAttr>(); 500 } 501 502 /// Returns true if pipe element type is different from the pointer. 503 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 504 const Expr *Arg0 = Call->getArg(0); 505 // First argument type should always be pipe. 506 if (!Arg0->getType()->isPipeType()) { 507 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 508 << Call->getDirectCallee() << Arg0->getSourceRange(); 509 return true; 510 } 511 OpenCLAccessAttr *AccessQual = 512 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 513 // Validates the access qualifier is compatible with the call. 514 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 515 // read_only and write_only, and assumed to be read_only if no qualifier is 516 // specified. 517 switch (Call->getDirectCallee()->getBuiltinID()) { 518 case Builtin::BIread_pipe: 519 case Builtin::BIreserve_read_pipe: 520 case Builtin::BIcommit_read_pipe: 521 case Builtin::BIwork_group_reserve_read_pipe: 522 case Builtin::BIsub_group_reserve_read_pipe: 523 case Builtin::BIwork_group_commit_read_pipe: 524 case Builtin::BIsub_group_commit_read_pipe: 525 if (!(!AccessQual || AccessQual->isReadOnly())) { 526 S.Diag(Arg0->getLocStart(), 527 diag::err_opencl_builtin_pipe_invalid_access_modifier) 528 << "read_only" << Arg0->getSourceRange(); 529 return true; 530 } 531 break; 532 case Builtin::BIwrite_pipe: 533 case Builtin::BIreserve_write_pipe: 534 case Builtin::BIcommit_write_pipe: 535 case Builtin::BIwork_group_reserve_write_pipe: 536 case Builtin::BIsub_group_reserve_write_pipe: 537 case Builtin::BIwork_group_commit_write_pipe: 538 case Builtin::BIsub_group_commit_write_pipe: 539 if (!(AccessQual && AccessQual->isWriteOnly())) { 540 S.Diag(Arg0->getLocStart(), 541 diag::err_opencl_builtin_pipe_invalid_access_modifier) 542 << "write_only" << Arg0->getSourceRange(); 543 return true; 544 } 545 break; 546 default: 547 break; 548 } 549 return false; 550 } 551 552 /// Returns true if pipe element type is different from the pointer. 553 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 554 const Expr *Arg0 = Call->getArg(0); 555 const Expr *ArgIdx = Call->getArg(Idx); 556 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 557 const QualType EltTy = PipeTy->getElementType(); 558 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 559 // The Idx argument should be a pointer and the type of the pointer and 560 // the type of pipe element should also be the same. 561 if (!ArgTy || 562 !S.Context.hasSameType( 563 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 564 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 565 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 566 << ArgIdx->getType() << ArgIdx->getSourceRange(); 567 return true; 568 } 569 return false; 570 } 571 572 // \brief Performs semantic analysis for the read/write_pipe call. 573 // \param S Reference to the semantic analyzer. 574 // \param Call A pointer to the builtin call. 575 // \return True if a semantic error has been found, false otherwise. 576 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 577 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 578 // functions have two forms. 579 switch (Call->getNumArgs()) { 580 case 2: { 581 if (checkOpenCLPipeArg(S, Call)) 582 return true; 583 // The call with 2 arguments should be 584 // read/write_pipe(pipe T, T*). 585 // Check packet type T. 586 if (checkOpenCLPipePacketType(S, Call, 1)) 587 return true; 588 } break; 589 590 case 4: { 591 if (checkOpenCLPipeArg(S, Call)) 592 return true; 593 // The call with 4 arguments should be 594 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 595 // Check reserve_id_t. 596 if (!Call->getArg(1)->getType()->isReserveIDT()) { 597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 598 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 599 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 600 return true; 601 } 602 603 // Check the index. 604 const Expr *Arg2 = Call->getArg(2); 605 if (!Arg2->getType()->isIntegerType() && 606 !Arg2->getType()->isUnsignedIntegerType()) { 607 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 608 << Call->getDirectCallee() << S.Context.UnsignedIntTy 609 << Arg2->getType() << Arg2->getSourceRange(); 610 return true; 611 } 612 613 // Check packet type T. 614 if (checkOpenCLPipePacketType(S, Call, 3)) 615 return true; 616 } break; 617 default: 618 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 619 << Call->getDirectCallee() << Call->getSourceRange(); 620 return true; 621 } 622 623 return false; 624 } 625 626 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 627 // /_}reserve_{read/write}_pipe 628 // \param S Reference to the semantic analyzer. 629 // \param Call The call to the builtin function to be analyzed. 630 // \return True if a semantic error was found, false otherwise. 631 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 632 if (checkArgCount(S, Call, 2)) 633 return true; 634 635 if (checkOpenCLPipeArg(S, Call)) 636 return true; 637 638 // Check the reserve size. 639 if (!Call->getArg(1)->getType()->isIntegerType() && 640 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 641 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 642 << Call->getDirectCallee() << S.Context.UnsignedIntTy 643 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 644 return true; 645 } 646 647 return false; 648 } 649 650 // \brief Performs a semantic analysis on {work_group_/sub_group_ 651 // /_}commit_{read/write}_pipe 652 // \param S Reference to the semantic analyzer. 653 // \param Call The call to the builtin function to be analyzed. 654 // \return True if a semantic error was found, false otherwise. 655 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 656 if (checkArgCount(S, Call, 2)) 657 return true; 658 659 if (checkOpenCLPipeArg(S, Call)) 660 return true; 661 662 // Check reserve_id_t. 663 if (!Call->getArg(1)->getType()->isReserveIDT()) { 664 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 665 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 666 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 667 return true; 668 } 669 670 return false; 671 } 672 673 // \brief Performs a semantic analysis on the call to built-in Pipe 674 // Query Functions. 675 // \param S Reference to the semantic analyzer. 676 // \param Call The call to the builtin function to be analyzed. 677 // \return True if a semantic error was found, false otherwise. 678 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 679 if (checkArgCount(S, Call, 1)) 680 return true; 681 682 if (!Call->getArg(0)->getType()->isPipeType()) { 683 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 684 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 685 return true; 686 } 687 688 return false; 689 } 690 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 691 // \brief Performs semantic analysis for the to_global/local/private call. 692 // \param S Reference to the semantic analyzer. 693 // \param BuiltinID ID of the builtin function. 694 // \param Call A pointer to the builtin call. 695 // \return True if a semantic error has been found, false otherwise. 696 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 697 CallExpr *Call) { 698 if (Call->getNumArgs() != 1) { 699 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 700 << Call->getDirectCallee() << Call->getSourceRange(); 701 return true; 702 } 703 704 auto RT = Call->getArg(0)->getType(); 705 if (!RT->isPointerType() || RT->getPointeeType() 706 .getAddressSpace() == LangAS::opencl_constant) { 707 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 708 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 709 return true; 710 } 711 712 RT = RT->getPointeeType(); 713 auto Qual = RT.getQualifiers(); 714 switch (BuiltinID) { 715 case Builtin::BIto_global: 716 Qual.setAddressSpace(LangAS::opencl_global); 717 break; 718 case Builtin::BIto_local: 719 Qual.setAddressSpace(LangAS::opencl_local); 720 break; 721 default: 722 Qual.removeAddressSpace(); 723 } 724 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 725 RT.getUnqualifiedType(), Qual))); 726 727 return false; 728 } 729 730 ExprResult 731 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 732 CallExpr *TheCall) { 733 ExprResult TheCallResult(TheCall); 734 735 // Find out if any arguments are required to be integer constant expressions. 736 unsigned ICEArguments = 0; 737 ASTContext::GetBuiltinTypeError Error; 738 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 739 if (Error != ASTContext::GE_None) 740 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 741 742 // If any arguments are required to be ICE's, check and diagnose. 743 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 744 // Skip arguments not required to be ICE's. 745 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 746 747 llvm::APSInt Result; 748 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 749 return true; 750 ICEArguments &= ~(1 << ArgNo); 751 } 752 753 switch (BuiltinID) { 754 case Builtin::BI__builtin___CFStringMakeConstantString: 755 assert(TheCall->getNumArgs() == 1 && 756 "Wrong # arguments to builtin CFStringMakeConstantString"); 757 if (CheckObjCString(TheCall->getArg(0))) 758 return ExprError(); 759 break; 760 case Builtin::BI__builtin_stdarg_start: 761 case Builtin::BI__builtin_va_start: 762 if (SemaBuiltinVAStart(TheCall)) 763 return ExprError(); 764 break; 765 case Builtin::BI__va_start: { 766 switch (Context.getTargetInfo().getTriple().getArch()) { 767 case llvm::Triple::arm: 768 case llvm::Triple::thumb: 769 if (SemaBuiltinVAStartARM(TheCall)) 770 return ExprError(); 771 break; 772 default: 773 if (SemaBuiltinVAStart(TheCall)) 774 return ExprError(); 775 break; 776 } 777 break; 778 } 779 case Builtin::BI__builtin_isgreater: 780 case Builtin::BI__builtin_isgreaterequal: 781 case Builtin::BI__builtin_isless: 782 case Builtin::BI__builtin_islessequal: 783 case Builtin::BI__builtin_islessgreater: 784 case Builtin::BI__builtin_isunordered: 785 if (SemaBuiltinUnorderedCompare(TheCall)) 786 return ExprError(); 787 break; 788 case Builtin::BI__builtin_fpclassify: 789 if (SemaBuiltinFPClassification(TheCall, 6)) 790 return ExprError(); 791 break; 792 case Builtin::BI__builtin_isfinite: 793 case Builtin::BI__builtin_isinf: 794 case Builtin::BI__builtin_isinf_sign: 795 case Builtin::BI__builtin_isnan: 796 case Builtin::BI__builtin_isnormal: 797 if (SemaBuiltinFPClassification(TheCall, 1)) 798 return ExprError(); 799 break; 800 case Builtin::BI__builtin_shufflevector: 801 return SemaBuiltinShuffleVector(TheCall); 802 // TheCall will be freed by the smart pointer here, but that's fine, since 803 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 804 case Builtin::BI__builtin_prefetch: 805 if (SemaBuiltinPrefetch(TheCall)) 806 return ExprError(); 807 break; 808 case Builtin::BI__builtin_alloca_with_align: 809 if (SemaBuiltinAllocaWithAlign(TheCall)) 810 return ExprError(); 811 break; 812 case Builtin::BI__assume: 813 case Builtin::BI__builtin_assume: 814 if (SemaBuiltinAssume(TheCall)) 815 return ExprError(); 816 break; 817 case Builtin::BI__builtin_assume_aligned: 818 if (SemaBuiltinAssumeAligned(TheCall)) 819 return ExprError(); 820 break; 821 case Builtin::BI__builtin_object_size: 822 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 823 return ExprError(); 824 break; 825 case Builtin::BI__builtin_longjmp: 826 if (SemaBuiltinLongjmp(TheCall)) 827 return ExprError(); 828 break; 829 case Builtin::BI__builtin_setjmp: 830 if (SemaBuiltinSetjmp(TheCall)) 831 return ExprError(); 832 break; 833 case Builtin::BI_setjmp: 834 case Builtin::BI_setjmpex: 835 if (checkArgCount(*this, TheCall, 1)) 836 return true; 837 break; 838 839 case Builtin::BI__builtin_classify_type: 840 if (checkArgCount(*this, TheCall, 1)) return true; 841 TheCall->setType(Context.IntTy); 842 break; 843 case Builtin::BI__builtin_constant_p: 844 if (checkArgCount(*this, TheCall, 1)) return true; 845 TheCall->setType(Context.IntTy); 846 break; 847 case Builtin::BI__sync_fetch_and_add: 848 case Builtin::BI__sync_fetch_and_add_1: 849 case Builtin::BI__sync_fetch_and_add_2: 850 case Builtin::BI__sync_fetch_and_add_4: 851 case Builtin::BI__sync_fetch_and_add_8: 852 case Builtin::BI__sync_fetch_and_add_16: 853 case Builtin::BI__sync_fetch_and_sub: 854 case Builtin::BI__sync_fetch_and_sub_1: 855 case Builtin::BI__sync_fetch_and_sub_2: 856 case Builtin::BI__sync_fetch_and_sub_4: 857 case Builtin::BI__sync_fetch_and_sub_8: 858 case Builtin::BI__sync_fetch_and_sub_16: 859 case Builtin::BI__sync_fetch_and_or: 860 case Builtin::BI__sync_fetch_and_or_1: 861 case Builtin::BI__sync_fetch_and_or_2: 862 case Builtin::BI__sync_fetch_and_or_4: 863 case Builtin::BI__sync_fetch_and_or_8: 864 case Builtin::BI__sync_fetch_and_or_16: 865 case Builtin::BI__sync_fetch_and_and: 866 case Builtin::BI__sync_fetch_and_and_1: 867 case Builtin::BI__sync_fetch_and_and_2: 868 case Builtin::BI__sync_fetch_and_and_4: 869 case Builtin::BI__sync_fetch_and_and_8: 870 case Builtin::BI__sync_fetch_and_and_16: 871 case Builtin::BI__sync_fetch_and_xor: 872 case Builtin::BI__sync_fetch_and_xor_1: 873 case Builtin::BI__sync_fetch_and_xor_2: 874 case Builtin::BI__sync_fetch_and_xor_4: 875 case Builtin::BI__sync_fetch_and_xor_8: 876 case Builtin::BI__sync_fetch_and_xor_16: 877 case Builtin::BI__sync_fetch_and_nand: 878 case Builtin::BI__sync_fetch_and_nand_1: 879 case Builtin::BI__sync_fetch_and_nand_2: 880 case Builtin::BI__sync_fetch_and_nand_4: 881 case Builtin::BI__sync_fetch_and_nand_8: 882 case Builtin::BI__sync_fetch_and_nand_16: 883 case Builtin::BI__sync_add_and_fetch: 884 case Builtin::BI__sync_add_and_fetch_1: 885 case Builtin::BI__sync_add_and_fetch_2: 886 case Builtin::BI__sync_add_and_fetch_4: 887 case Builtin::BI__sync_add_and_fetch_8: 888 case Builtin::BI__sync_add_and_fetch_16: 889 case Builtin::BI__sync_sub_and_fetch: 890 case Builtin::BI__sync_sub_and_fetch_1: 891 case Builtin::BI__sync_sub_and_fetch_2: 892 case Builtin::BI__sync_sub_and_fetch_4: 893 case Builtin::BI__sync_sub_and_fetch_8: 894 case Builtin::BI__sync_sub_and_fetch_16: 895 case Builtin::BI__sync_and_and_fetch: 896 case Builtin::BI__sync_and_and_fetch_1: 897 case Builtin::BI__sync_and_and_fetch_2: 898 case Builtin::BI__sync_and_and_fetch_4: 899 case Builtin::BI__sync_and_and_fetch_8: 900 case Builtin::BI__sync_and_and_fetch_16: 901 case Builtin::BI__sync_or_and_fetch: 902 case Builtin::BI__sync_or_and_fetch_1: 903 case Builtin::BI__sync_or_and_fetch_2: 904 case Builtin::BI__sync_or_and_fetch_4: 905 case Builtin::BI__sync_or_and_fetch_8: 906 case Builtin::BI__sync_or_and_fetch_16: 907 case Builtin::BI__sync_xor_and_fetch: 908 case Builtin::BI__sync_xor_and_fetch_1: 909 case Builtin::BI__sync_xor_and_fetch_2: 910 case Builtin::BI__sync_xor_and_fetch_4: 911 case Builtin::BI__sync_xor_and_fetch_8: 912 case Builtin::BI__sync_xor_and_fetch_16: 913 case Builtin::BI__sync_nand_and_fetch: 914 case Builtin::BI__sync_nand_and_fetch_1: 915 case Builtin::BI__sync_nand_and_fetch_2: 916 case Builtin::BI__sync_nand_and_fetch_4: 917 case Builtin::BI__sync_nand_and_fetch_8: 918 case Builtin::BI__sync_nand_and_fetch_16: 919 case Builtin::BI__sync_val_compare_and_swap: 920 case Builtin::BI__sync_val_compare_and_swap_1: 921 case Builtin::BI__sync_val_compare_and_swap_2: 922 case Builtin::BI__sync_val_compare_and_swap_4: 923 case Builtin::BI__sync_val_compare_and_swap_8: 924 case Builtin::BI__sync_val_compare_and_swap_16: 925 case Builtin::BI__sync_bool_compare_and_swap: 926 case Builtin::BI__sync_bool_compare_and_swap_1: 927 case Builtin::BI__sync_bool_compare_and_swap_2: 928 case Builtin::BI__sync_bool_compare_and_swap_4: 929 case Builtin::BI__sync_bool_compare_and_swap_8: 930 case Builtin::BI__sync_bool_compare_and_swap_16: 931 case Builtin::BI__sync_lock_test_and_set: 932 case Builtin::BI__sync_lock_test_and_set_1: 933 case Builtin::BI__sync_lock_test_and_set_2: 934 case Builtin::BI__sync_lock_test_and_set_4: 935 case Builtin::BI__sync_lock_test_and_set_8: 936 case Builtin::BI__sync_lock_test_and_set_16: 937 case Builtin::BI__sync_lock_release: 938 case Builtin::BI__sync_lock_release_1: 939 case Builtin::BI__sync_lock_release_2: 940 case Builtin::BI__sync_lock_release_4: 941 case Builtin::BI__sync_lock_release_8: 942 case Builtin::BI__sync_lock_release_16: 943 case Builtin::BI__sync_swap: 944 case Builtin::BI__sync_swap_1: 945 case Builtin::BI__sync_swap_2: 946 case Builtin::BI__sync_swap_4: 947 case Builtin::BI__sync_swap_8: 948 case Builtin::BI__sync_swap_16: 949 return SemaBuiltinAtomicOverloaded(TheCallResult); 950 case Builtin::BI__builtin_nontemporal_load: 951 case Builtin::BI__builtin_nontemporal_store: 952 return SemaBuiltinNontemporalOverloaded(TheCallResult); 953 #define BUILTIN(ID, TYPE, ATTRS) 954 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 955 case Builtin::BI##ID: \ 956 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 957 #include "clang/Basic/Builtins.def" 958 case Builtin::BI__builtin_annotation: 959 if (SemaBuiltinAnnotation(*this, TheCall)) 960 return ExprError(); 961 break; 962 case Builtin::BI__builtin_addressof: 963 if (SemaBuiltinAddressof(*this, TheCall)) 964 return ExprError(); 965 break; 966 case Builtin::BI__builtin_add_overflow: 967 case Builtin::BI__builtin_sub_overflow: 968 case Builtin::BI__builtin_mul_overflow: 969 if (SemaBuiltinOverflow(*this, TheCall)) 970 return ExprError(); 971 break; 972 case Builtin::BI__builtin_operator_new: 973 case Builtin::BI__builtin_operator_delete: 974 if (!getLangOpts().CPlusPlus) { 975 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 976 << (BuiltinID == Builtin::BI__builtin_operator_new 977 ? "__builtin_operator_new" 978 : "__builtin_operator_delete") 979 << "C++"; 980 return ExprError(); 981 } 982 // CodeGen assumes it can find the global new and delete to call, 983 // so ensure that they are declared. 984 DeclareGlobalNewDelete(); 985 break; 986 987 // check secure string manipulation functions where overflows 988 // are detectable at compile time 989 case Builtin::BI__builtin___memcpy_chk: 990 case Builtin::BI__builtin___memmove_chk: 991 case Builtin::BI__builtin___memset_chk: 992 case Builtin::BI__builtin___strlcat_chk: 993 case Builtin::BI__builtin___strlcpy_chk: 994 case Builtin::BI__builtin___strncat_chk: 995 case Builtin::BI__builtin___strncpy_chk: 996 case Builtin::BI__builtin___stpncpy_chk: 997 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 998 break; 999 case Builtin::BI__builtin___memccpy_chk: 1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1001 break; 1002 case Builtin::BI__builtin___snprintf_chk: 1003 case Builtin::BI__builtin___vsnprintf_chk: 1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1005 break; 1006 case Builtin::BI__builtin_call_with_static_chain: 1007 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1008 return ExprError(); 1009 break; 1010 case Builtin::BI__exception_code: 1011 case Builtin::BI_exception_code: 1012 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1013 diag::err_seh___except_block)) 1014 return ExprError(); 1015 break; 1016 case Builtin::BI__exception_info: 1017 case Builtin::BI_exception_info: 1018 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1019 diag::err_seh___except_filter)) 1020 return ExprError(); 1021 break; 1022 case Builtin::BI__GetExceptionInfo: 1023 if (checkArgCount(*this, TheCall, 1)) 1024 return ExprError(); 1025 1026 if (CheckCXXThrowOperand( 1027 TheCall->getLocStart(), 1028 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1029 TheCall)) 1030 return ExprError(); 1031 1032 TheCall->setType(Context.VoidPtrTy); 1033 break; 1034 // OpenCL v2.0, s6.13.16 - Pipe functions 1035 case Builtin::BIread_pipe: 1036 case Builtin::BIwrite_pipe: 1037 // Since those two functions are declared with var args, we need a semantic 1038 // check for the argument. 1039 if (SemaBuiltinRWPipe(*this, TheCall)) 1040 return ExprError(); 1041 TheCall->setType(Context.IntTy); 1042 break; 1043 case Builtin::BIreserve_read_pipe: 1044 case Builtin::BIreserve_write_pipe: 1045 case Builtin::BIwork_group_reserve_read_pipe: 1046 case Builtin::BIwork_group_reserve_write_pipe: 1047 case Builtin::BIsub_group_reserve_read_pipe: 1048 case Builtin::BIsub_group_reserve_write_pipe: 1049 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1050 return ExprError(); 1051 // Since return type of reserve_read/write_pipe built-in function is 1052 // reserve_id_t, which is not defined in the builtin def file , we used int 1053 // as return type and need to override the return type of these functions. 1054 TheCall->setType(Context.OCLReserveIDTy); 1055 break; 1056 case Builtin::BIcommit_read_pipe: 1057 case Builtin::BIcommit_write_pipe: 1058 case Builtin::BIwork_group_commit_read_pipe: 1059 case Builtin::BIwork_group_commit_write_pipe: 1060 case Builtin::BIsub_group_commit_read_pipe: 1061 case Builtin::BIsub_group_commit_write_pipe: 1062 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1063 return ExprError(); 1064 break; 1065 case Builtin::BIget_pipe_num_packets: 1066 case Builtin::BIget_pipe_max_packets: 1067 if (SemaBuiltinPipePackets(*this, TheCall)) 1068 return ExprError(); 1069 TheCall->setType(Context.UnsignedIntTy); 1070 break; 1071 case Builtin::BIto_global: 1072 case Builtin::BIto_local: 1073 case Builtin::BIto_private: 1074 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1075 return ExprError(); 1076 break; 1077 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1078 case Builtin::BIenqueue_kernel: 1079 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1080 return ExprError(); 1081 break; 1082 case Builtin::BIget_kernel_work_group_size: 1083 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1084 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1085 return ExprError(); 1086 break; 1087 case Builtin::BI__builtin_os_log_format: 1088 case Builtin::BI__builtin_os_log_format_buffer_size: 1089 if (SemaBuiltinOSLogFormat(TheCall)) { 1090 return ExprError(); 1091 } 1092 break; 1093 } 1094 1095 // Since the target specific builtins for each arch overlap, only check those 1096 // of the arch we are compiling for. 1097 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1098 switch (Context.getTargetInfo().getTriple().getArch()) { 1099 case llvm::Triple::arm: 1100 case llvm::Triple::armeb: 1101 case llvm::Triple::thumb: 1102 case llvm::Triple::thumbeb: 1103 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1104 return ExprError(); 1105 break; 1106 case llvm::Triple::aarch64: 1107 case llvm::Triple::aarch64_be: 1108 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1109 return ExprError(); 1110 break; 1111 case llvm::Triple::mips: 1112 case llvm::Triple::mipsel: 1113 case llvm::Triple::mips64: 1114 case llvm::Triple::mips64el: 1115 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1116 return ExprError(); 1117 break; 1118 case llvm::Triple::systemz: 1119 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1120 return ExprError(); 1121 break; 1122 case llvm::Triple::x86: 1123 case llvm::Triple::x86_64: 1124 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1125 return ExprError(); 1126 break; 1127 case llvm::Triple::ppc: 1128 case llvm::Triple::ppc64: 1129 case llvm::Triple::ppc64le: 1130 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1131 return ExprError(); 1132 break; 1133 default: 1134 break; 1135 } 1136 } 1137 1138 return TheCallResult; 1139 } 1140 1141 // Get the valid immediate range for the specified NEON type code. 1142 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1143 NeonTypeFlags Type(t); 1144 int IsQuad = ForceQuad ? true : Type.isQuad(); 1145 switch (Type.getEltType()) { 1146 case NeonTypeFlags::Int8: 1147 case NeonTypeFlags::Poly8: 1148 return shift ? 7 : (8 << IsQuad) - 1; 1149 case NeonTypeFlags::Int16: 1150 case NeonTypeFlags::Poly16: 1151 return shift ? 15 : (4 << IsQuad) - 1; 1152 case NeonTypeFlags::Int32: 1153 return shift ? 31 : (2 << IsQuad) - 1; 1154 case NeonTypeFlags::Int64: 1155 case NeonTypeFlags::Poly64: 1156 return shift ? 63 : (1 << IsQuad) - 1; 1157 case NeonTypeFlags::Poly128: 1158 return shift ? 127 : (1 << IsQuad) - 1; 1159 case NeonTypeFlags::Float16: 1160 assert(!shift && "cannot shift float types!"); 1161 return (4 << IsQuad) - 1; 1162 case NeonTypeFlags::Float32: 1163 assert(!shift && "cannot shift float types!"); 1164 return (2 << IsQuad) - 1; 1165 case NeonTypeFlags::Float64: 1166 assert(!shift && "cannot shift float types!"); 1167 return (1 << IsQuad) - 1; 1168 } 1169 llvm_unreachable("Invalid NeonTypeFlag!"); 1170 } 1171 1172 /// getNeonEltType - Return the QualType corresponding to the elements of 1173 /// the vector type specified by the NeonTypeFlags. This is used to check 1174 /// the pointer arguments for Neon load/store intrinsics. 1175 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1176 bool IsPolyUnsigned, bool IsInt64Long) { 1177 switch (Flags.getEltType()) { 1178 case NeonTypeFlags::Int8: 1179 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1180 case NeonTypeFlags::Int16: 1181 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1182 case NeonTypeFlags::Int32: 1183 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1184 case NeonTypeFlags::Int64: 1185 if (IsInt64Long) 1186 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1187 else 1188 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1189 : Context.LongLongTy; 1190 case NeonTypeFlags::Poly8: 1191 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1192 case NeonTypeFlags::Poly16: 1193 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1194 case NeonTypeFlags::Poly64: 1195 if (IsInt64Long) 1196 return Context.UnsignedLongTy; 1197 else 1198 return Context.UnsignedLongLongTy; 1199 case NeonTypeFlags::Poly128: 1200 break; 1201 case NeonTypeFlags::Float16: 1202 return Context.HalfTy; 1203 case NeonTypeFlags::Float32: 1204 return Context.FloatTy; 1205 case NeonTypeFlags::Float64: 1206 return Context.DoubleTy; 1207 } 1208 llvm_unreachable("Invalid NeonTypeFlag!"); 1209 } 1210 1211 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1212 llvm::APSInt Result; 1213 uint64_t mask = 0; 1214 unsigned TV = 0; 1215 int PtrArgNum = -1; 1216 bool HasConstPtr = false; 1217 switch (BuiltinID) { 1218 #define GET_NEON_OVERLOAD_CHECK 1219 #include "clang/Basic/arm_neon.inc" 1220 #undef GET_NEON_OVERLOAD_CHECK 1221 } 1222 1223 // For NEON intrinsics which are overloaded on vector element type, validate 1224 // the immediate which specifies which variant to emit. 1225 unsigned ImmArg = TheCall->getNumArgs()-1; 1226 if (mask) { 1227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1228 return true; 1229 1230 TV = Result.getLimitedValue(64); 1231 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1232 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1233 << TheCall->getArg(ImmArg)->getSourceRange(); 1234 } 1235 1236 if (PtrArgNum >= 0) { 1237 // Check that pointer arguments have the specified type. 1238 Expr *Arg = TheCall->getArg(PtrArgNum); 1239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1240 Arg = ICE->getSubExpr(); 1241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1242 QualType RHSTy = RHS.get()->getType(); 1243 1244 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64; 1246 bool IsInt64Long = 1247 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1248 QualType EltTy = 1249 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1250 if (HasConstPtr) 1251 EltTy = EltTy.withConst(); 1252 QualType LHSTy = Context.getPointerType(EltTy); 1253 AssignConvertType ConvTy; 1254 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1255 if (RHS.isInvalid()) 1256 return true; 1257 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1258 RHS.get(), AA_Assigning)) 1259 return true; 1260 } 1261 1262 // For NEON intrinsics which take an immediate value as part of the 1263 // instruction, range check them here. 1264 unsigned i = 0, l = 0, u = 0; 1265 switch (BuiltinID) { 1266 default: 1267 return false; 1268 #define GET_NEON_IMMEDIATE_CHECK 1269 #include "clang/Basic/arm_neon.inc" 1270 #undef GET_NEON_IMMEDIATE_CHECK 1271 } 1272 1273 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1274 } 1275 1276 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1277 unsigned MaxWidth) { 1278 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1279 BuiltinID == ARM::BI__builtin_arm_ldaex || 1280 BuiltinID == ARM::BI__builtin_arm_strex || 1281 BuiltinID == ARM::BI__builtin_arm_stlex || 1282 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1283 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1284 BuiltinID == AArch64::BI__builtin_arm_strex || 1285 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1286 "unexpected ARM builtin"); 1287 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1288 BuiltinID == ARM::BI__builtin_arm_ldaex || 1289 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1290 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1291 1292 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1293 1294 // Ensure that we have the proper number of arguments. 1295 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1296 return true; 1297 1298 // Inspect the pointer argument of the atomic builtin. This should always be 1299 // a pointer type, whose element is an integral scalar or pointer type. 1300 // Because it is a pointer type, we don't have to worry about any implicit 1301 // casts here. 1302 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1303 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1304 if (PointerArgRes.isInvalid()) 1305 return true; 1306 PointerArg = PointerArgRes.get(); 1307 1308 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1309 if (!pointerType) { 1310 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1311 << PointerArg->getType() << PointerArg->getSourceRange(); 1312 return true; 1313 } 1314 1315 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1316 // task is to insert the appropriate casts into the AST. First work out just 1317 // what the appropriate type is. 1318 QualType ValType = pointerType->getPointeeType(); 1319 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1320 if (IsLdrex) 1321 AddrType.addConst(); 1322 1323 // Issue a warning if the cast is dodgy. 1324 CastKind CastNeeded = CK_NoOp; 1325 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1326 CastNeeded = CK_BitCast; 1327 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1328 << PointerArg->getType() 1329 << Context.getPointerType(AddrType) 1330 << AA_Passing << PointerArg->getSourceRange(); 1331 } 1332 1333 // Finally, do the cast and replace the argument with the corrected version. 1334 AddrType = Context.getPointerType(AddrType); 1335 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1336 if (PointerArgRes.isInvalid()) 1337 return true; 1338 PointerArg = PointerArgRes.get(); 1339 1340 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1341 1342 // In general, we allow ints, floats and pointers to be loaded and stored. 1343 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1344 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1345 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1346 << PointerArg->getType() << PointerArg->getSourceRange(); 1347 return true; 1348 } 1349 1350 // But ARM doesn't have instructions to deal with 128-bit versions. 1351 if (Context.getTypeSize(ValType) > MaxWidth) { 1352 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1353 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1354 << PointerArg->getType() << PointerArg->getSourceRange(); 1355 return true; 1356 } 1357 1358 switch (ValType.getObjCLifetime()) { 1359 case Qualifiers::OCL_None: 1360 case Qualifiers::OCL_ExplicitNone: 1361 // okay 1362 break; 1363 1364 case Qualifiers::OCL_Weak: 1365 case Qualifiers::OCL_Strong: 1366 case Qualifiers::OCL_Autoreleasing: 1367 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1368 << ValType << PointerArg->getSourceRange(); 1369 return true; 1370 } 1371 1372 if (IsLdrex) { 1373 TheCall->setType(ValType); 1374 return false; 1375 } 1376 1377 // Initialize the argument to be stored. 1378 ExprResult ValArg = TheCall->getArg(0); 1379 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1380 Context, ValType, /*consume*/ false); 1381 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1382 if (ValArg.isInvalid()) 1383 return true; 1384 TheCall->setArg(0, ValArg.get()); 1385 1386 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1387 // but the custom checker bypasses all default analysis. 1388 TheCall->setType(Context.IntTy); 1389 return false; 1390 } 1391 1392 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1393 llvm::APSInt Result; 1394 1395 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1396 BuiltinID == ARM::BI__builtin_arm_ldaex || 1397 BuiltinID == ARM::BI__builtin_arm_strex || 1398 BuiltinID == ARM::BI__builtin_arm_stlex) { 1399 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1400 } 1401 1402 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1403 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1404 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1405 } 1406 1407 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1408 BuiltinID == ARM::BI__builtin_arm_wsr64) 1409 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1410 1411 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1412 BuiltinID == ARM::BI__builtin_arm_rsrp || 1413 BuiltinID == ARM::BI__builtin_arm_wsr || 1414 BuiltinID == ARM::BI__builtin_arm_wsrp) 1415 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1416 1417 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1418 return true; 1419 1420 // For intrinsics which take an immediate value as part of the instruction, 1421 // range check them here. 1422 unsigned i = 0, l = 0, u = 0; 1423 switch (BuiltinID) { 1424 default: return false; 1425 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1426 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1427 case ARM::BI__builtin_arm_vcvtr_f: 1428 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1429 case ARM::BI__builtin_arm_dmb: 1430 case ARM::BI__builtin_arm_dsb: 1431 case ARM::BI__builtin_arm_isb: 1432 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1433 } 1434 1435 // FIXME: VFP Intrinsics should error if VFP not present. 1436 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1437 } 1438 1439 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1440 CallExpr *TheCall) { 1441 llvm::APSInt Result; 1442 1443 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1444 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1445 BuiltinID == AArch64::BI__builtin_arm_strex || 1446 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1447 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1448 } 1449 1450 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1451 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1452 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1453 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1454 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1455 } 1456 1457 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1458 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1459 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1460 1461 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1462 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1463 BuiltinID == AArch64::BI__builtin_arm_wsr || 1464 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1465 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1466 1467 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1468 return true; 1469 1470 // For intrinsics which take an immediate value as part of the instruction, 1471 // range check them here. 1472 unsigned i = 0, l = 0, u = 0; 1473 switch (BuiltinID) { 1474 default: return false; 1475 case AArch64::BI__builtin_arm_dmb: 1476 case AArch64::BI__builtin_arm_dsb: 1477 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1478 } 1479 1480 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1481 } 1482 1483 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1484 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1485 // ordering for DSP is unspecified. MSA is ordered by the data format used 1486 // by the underlying instruction i.e., df/m, df/n and then by size. 1487 // 1488 // FIXME: The size tests here should instead be tablegen'd along with the 1489 // definitions from include/clang/Basic/BuiltinsMips.def. 1490 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1491 // be too. 1492 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1493 unsigned i = 0, l = 0, u = 0, m = 0; 1494 switch (BuiltinID) { 1495 default: return false; 1496 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1497 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1498 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1499 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1500 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1501 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1502 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1503 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1504 // df/m field. 1505 // These intrinsics take an unsigned 3 bit immediate. 1506 case Mips::BI__builtin_msa_bclri_b: 1507 case Mips::BI__builtin_msa_bnegi_b: 1508 case Mips::BI__builtin_msa_bseti_b: 1509 case Mips::BI__builtin_msa_sat_s_b: 1510 case Mips::BI__builtin_msa_sat_u_b: 1511 case Mips::BI__builtin_msa_slli_b: 1512 case Mips::BI__builtin_msa_srai_b: 1513 case Mips::BI__builtin_msa_srari_b: 1514 case Mips::BI__builtin_msa_srli_b: 1515 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1516 case Mips::BI__builtin_msa_binsli_b: 1517 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1518 // These intrinsics take an unsigned 4 bit immediate. 1519 case Mips::BI__builtin_msa_bclri_h: 1520 case Mips::BI__builtin_msa_bnegi_h: 1521 case Mips::BI__builtin_msa_bseti_h: 1522 case Mips::BI__builtin_msa_sat_s_h: 1523 case Mips::BI__builtin_msa_sat_u_h: 1524 case Mips::BI__builtin_msa_slli_h: 1525 case Mips::BI__builtin_msa_srai_h: 1526 case Mips::BI__builtin_msa_srari_h: 1527 case Mips::BI__builtin_msa_srli_h: 1528 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1529 case Mips::BI__builtin_msa_binsli_h: 1530 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1531 // These intrinsics take an unsigned 5 bit immedate. 1532 // The first block of intrinsics actually have an unsigned 5 bit field, 1533 // not a df/n field. 1534 case Mips::BI__builtin_msa_clei_u_b: 1535 case Mips::BI__builtin_msa_clei_u_h: 1536 case Mips::BI__builtin_msa_clei_u_w: 1537 case Mips::BI__builtin_msa_clei_u_d: 1538 case Mips::BI__builtin_msa_clti_u_b: 1539 case Mips::BI__builtin_msa_clti_u_h: 1540 case Mips::BI__builtin_msa_clti_u_w: 1541 case Mips::BI__builtin_msa_clti_u_d: 1542 case Mips::BI__builtin_msa_maxi_u_b: 1543 case Mips::BI__builtin_msa_maxi_u_h: 1544 case Mips::BI__builtin_msa_maxi_u_w: 1545 case Mips::BI__builtin_msa_maxi_u_d: 1546 case Mips::BI__builtin_msa_mini_u_b: 1547 case Mips::BI__builtin_msa_mini_u_h: 1548 case Mips::BI__builtin_msa_mini_u_w: 1549 case Mips::BI__builtin_msa_mini_u_d: 1550 case Mips::BI__builtin_msa_addvi_b: 1551 case Mips::BI__builtin_msa_addvi_h: 1552 case Mips::BI__builtin_msa_addvi_w: 1553 case Mips::BI__builtin_msa_addvi_d: 1554 case Mips::BI__builtin_msa_bclri_w: 1555 case Mips::BI__builtin_msa_bnegi_w: 1556 case Mips::BI__builtin_msa_bseti_w: 1557 case Mips::BI__builtin_msa_sat_s_w: 1558 case Mips::BI__builtin_msa_sat_u_w: 1559 case Mips::BI__builtin_msa_slli_w: 1560 case Mips::BI__builtin_msa_srai_w: 1561 case Mips::BI__builtin_msa_srari_w: 1562 case Mips::BI__builtin_msa_srli_w: 1563 case Mips::BI__builtin_msa_srlri_w: 1564 case Mips::BI__builtin_msa_subvi_b: 1565 case Mips::BI__builtin_msa_subvi_h: 1566 case Mips::BI__builtin_msa_subvi_w: 1567 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1568 case Mips::BI__builtin_msa_binsli_w: 1569 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1570 // These intrinsics take an unsigned 6 bit immediate. 1571 case Mips::BI__builtin_msa_bclri_d: 1572 case Mips::BI__builtin_msa_bnegi_d: 1573 case Mips::BI__builtin_msa_bseti_d: 1574 case Mips::BI__builtin_msa_sat_s_d: 1575 case Mips::BI__builtin_msa_sat_u_d: 1576 case Mips::BI__builtin_msa_slli_d: 1577 case Mips::BI__builtin_msa_srai_d: 1578 case Mips::BI__builtin_msa_srari_d: 1579 case Mips::BI__builtin_msa_srli_d: 1580 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1581 case Mips::BI__builtin_msa_binsli_d: 1582 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1583 // These intrinsics take a signed 5 bit immediate. 1584 case Mips::BI__builtin_msa_ceqi_b: 1585 case Mips::BI__builtin_msa_ceqi_h: 1586 case Mips::BI__builtin_msa_ceqi_w: 1587 case Mips::BI__builtin_msa_ceqi_d: 1588 case Mips::BI__builtin_msa_clti_s_b: 1589 case Mips::BI__builtin_msa_clti_s_h: 1590 case Mips::BI__builtin_msa_clti_s_w: 1591 case Mips::BI__builtin_msa_clti_s_d: 1592 case Mips::BI__builtin_msa_clei_s_b: 1593 case Mips::BI__builtin_msa_clei_s_h: 1594 case Mips::BI__builtin_msa_clei_s_w: 1595 case Mips::BI__builtin_msa_clei_s_d: 1596 case Mips::BI__builtin_msa_maxi_s_b: 1597 case Mips::BI__builtin_msa_maxi_s_h: 1598 case Mips::BI__builtin_msa_maxi_s_w: 1599 case Mips::BI__builtin_msa_maxi_s_d: 1600 case Mips::BI__builtin_msa_mini_s_b: 1601 case Mips::BI__builtin_msa_mini_s_h: 1602 case Mips::BI__builtin_msa_mini_s_w: 1603 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1604 // These intrinsics take an unsigned 8 bit immediate. 1605 case Mips::BI__builtin_msa_andi_b: 1606 case Mips::BI__builtin_msa_nori_b: 1607 case Mips::BI__builtin_msa_ori_b: 1608 case Mips::BI__builtin_msa_shf_b: 1609 case Mips::BI__builtin_msa_shf_h: 1610 case Mips::BI__builtin_msa_shf_w: 1611 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1612 case Mips::BI__builtin_msa_bseli_b: 1613 case Mips::BI__builtin_msa_bmnzi_b: 1614 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1615 // df/n format 1616 // These intrinsics take an unsigned 4 bit immediate. 1617 case Mips::BI__builtin_msa_copy_s_b: 1618 case Mips::BI__builtin_msa_copy_u_b: 1619 case Mips::BI__builtin_msa_insve_b: 1620 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1621 case Mips::BI__builtin_msa_sld_b: 1622 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1623 // These intrinsics take an unsigned 3 bit immediate. 1624 case Mips::BI__builtin_msa_copy_s_h: 1625 case Mips::BI__builtin_msa_copy_u_h: 1626 case Mips::BI__builtin_msa_insve_h: 1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1628 case Mips::BI__builtin_msa_sld_h: 1629 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1630 // These intrinsics take an unsigned 2 bit immediate. 1631 case Mips::BI__builtin_msa_copy_s_w: 1632 case Mips::BI__builtin_msa_copy_u_w: 1633 case Mips::BI__builtin_msa_insve_w: 1634 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1635 case Mips::BI__builtin_msa_sld_w: 1636 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1637 // These intrinsics take an unsigned 1 bit immediate. 1638 case Mips::BI__builtin_msa_copy_s_d: 1639 case Mips::BI__builtin_msa_copy_u_d: 1640 case Mips::BI__builtin_msa_insve_d: 1641 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1642 case Mips::BI__builtin_msa_sld_d: 1643 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1644 // Memory offsets and immediate loads. 1645 // These intrinsics take a signed 10 bit immediate. 1646 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break; 1647 case Mips::BI__builtin_msa_ldi_h: 1648 case Mips::BI__builtin_msa_ldi_w: 1649 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1650 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1651 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1652 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1653 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1654 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1655 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1656 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1657 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1658 } 1659 1660 if (!m) 1661 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1662 1663 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1664 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1665 } 1666 1667 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1668 unsigned i = 0, l = 0, u = 0; 1669 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1670 BuiltinID == PPC::BI__builtin_divdeu || 1671 BuiltinID == PPC::BI__builtin_bpermd; 1672 bool IsTarget64Bit = Context.getTargetInfo() 1673 .getTypeWidth(Context 1674 .getTargetInfo() 1675 .getIntPtrType()) == 64; 1676 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1677 BuiltinID == PPC::BI__builtin_divweu || 1678 BuiltinID == PPC::BI__builtin_divde || 1679 BuiltinID == PPC::BI__builtin_divdeu; 1680 1681 if (Is64BitBltin && !IsTarget64Bit) 1682 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1683 << TheCall->getSourceRange(); 1684 1685 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1686 (BuiltinID == PPC::BI__builtin_bpermd && 1687 !Context.getTargetInfo().hasFeature("bpermd"))) 1688 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1689 << TheCall->getSourceRange(); 1690 1691 switch (BuiltinID) { 1692 default: return false; 1693 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1694 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1695 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1696 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1697 case PPC::BI__builtin_tbegin: 1698 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1699 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1700 case PPC::BI__builtin_tabortwc: 1701 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1702 case PPC::BI__builtin_tabortwci: 1703 case PPC::BI__builtin_tabortdci: 1704 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1705 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1706 } 1707 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1708 } 1709 1710 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1711 CallExpr *TheCall) { 1712 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1713 Expr *Arg = TheCall->getArg(0); 1714 llvm::APSInt AbortCode(32); 1715 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1716 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1717 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1718 << Arg->getSourceRange(); 1719 } 1720 1721 // For intrinsics which take an immediate value as part of the instruction, 1722 // range check them here. 1723 unsigned i = 0, l = 0, u = 0; 1724 switch (BuiltinID) { 1725 default: return false; 1726 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1727 case SystemZ::BI__builtin_s390_verimb: 1728 case SystemZ::BI__builtin_s390_verimh: 1729 case SystemZ::BI__builtin_s390_verimf: 1730 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1731 case SystemZ::BI__builtin_s390_vfaeb: 1732 case SystemZ::BI__builtin_s390_vfaeh: 1733 case SystemZ::BI__builtin_s390_vfaef: 1734 case SystemZ::BI__builtin_s390_vfaebs: 1735 case SystemZ::BI__builtin_s390_vfaehs: 1736 case SystemZ::BI__builtin_s390_vfaefs: 1737 case SystemZ::BI__builtin_s390_vfaezb: 1738 case SystemZ::BI__builtin_s390_vfaezh: 1739 case SystemZ::BI__builtin_s390_vfaezf: 1740 case SystemZ::BI__builtin_s390_vfaezbs: 1741 case SystemZ::BI__builtin_s390_vfaezhs: 1742 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1743 case SystemZ::BI__builtin_s390_vfidb: 1744 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1745 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1746 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1747 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1748 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1749 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1750 case SystemZ::BI__builtin_s390_vstrcb: 1751 case SystemZ::BI__builtin_s390_vstrch: 1752 case SystemZ::BI__builtin_s390_vstrcf: 1753 case SystemZ::BI__builtin_s390_vstrczb: 1754 case SystemZ::BI__builtin_s390_vstrczh: 1755 case SystemZ::BI__builtin_s390_vstrczf: 1756 case SystemZ::BI__builtin_s390_vstrcbs: 1757 case SystemZ::BI__builtin_s390_vstrchs: 1758 case SystemZ::BI__builtin_s390_vstrcfs: 1759 case SystemZ::BI__builtin_s390_vstrczbs: 1760 case SystemZ::BI__builtin_s390_vstrczhs: 1761 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1762 } 1763 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1764 } 1765 1766 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1767 /// This checks that the target supports __builtin_cpu_supports and 1768 /// that the string argument is constant and valid. 1769 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1770 Expr *Arg = TheCall->getArg(0); 1771 1772 // Check if the argument is a string literal. 1773 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1774 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1775 << Arg->getSourceRange(); 1776 1777 // Check the contents of the string. 1778 StringRef Feature = 1779 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1780 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1781 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1782 << Arg->getSourceRange(); 1783 return false; 1784 } 1785 1786 // Check if the rounding mode is legal. 1787 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1788 // Indicates if this instruction has rounding control or just SAE. 1789 bool HasRC = false; 1790 1791 unsigned ArgNum = 0; 1792 switch (BuiltinID) { 1793 default: 1794 return false; 1795 case X86::BI__builtin_ia32_vcvttsd2si32: 1796 case X86::BI__builtin_ia32_vcvttsd2si64: 1797 case X86::BI__builtin_ia32_vcvttsd2usi32: 1798 case X86::BI__builtin_ia32_vcvttsd2usi64: 1799 case X86::BI__builtin_ia32_vcvttss2si32: 1800 case X86::BI__builtin_ia32_vcvttss2si64: 1801 case X86::BI__builtin_ia32_vcvttss2usi32: 1802 case X86::BI__builtin_ia32_vcvttss2usi64: 1803 ArgNum = 1; 1804 break; 1805 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1806 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1807 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1808 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1809 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1810 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1811 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1812 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1813 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1814 case X86::BI__builtin_ia32_exp2pd_mask: 1815 case X86::BI__builtin_ia32_exp2ps_mask: 1816 case X86::BI__builtin_ia32_getexppd512_mask: 1817 case X86::BI__builtin_ia32_getexpps512_mask: 1818 case X86::BI__builtin_ia32_rcp28pd_mask: 1819 case X86::BI__builtin_ia32_rcp28ps_mask: 1820 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1821 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1822 case X86::BI__builtin_ia32_vcomisd: 1823 case X86::BI__builtin_ia32_vcomiss: 1824 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1825 ArgNum = 3; 1826 break; 1827 case X86::BI__builtin_ia32_cmppd512_mask: 1828 case X86::BI__builtin_ia32_cmpps512_mask: 1829 case X86::BI__builtin_ia32_cmpsd_mask: 1830 case X86::BI__builtin_ia32_cmpss_mask: 1831 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1832 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1833 case X86::BI__builtin_ia32_getexpss128_round_mask: 1834 case X86::BI__builtin_ia32_maxpd512_mask: 1835 case X86::BI__builtin_ia32_maxps512_mask: 1836 case X86::BI__builtin_ia32_maxsd_round_mask: 1837 case X86::BI__builtin_ia32_maxss_round_mask: 1838 case X86::BI__builtin_ia32_minpd512_mask: 1839 case X86::BI__builtin_ia32_minps512_mask: 1840 case X86::BI__builtin_ia32_minsd_round_mask: 1841 case X86::BI__builtin_ia32_minss_round_mask: 1842 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1843 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1844 case X86::BI__builtin_ia32_reducepd512_mask: 1845 case X86::BI__builtin_ia32_reduceps512_mask: 1846 case X86::BI__builtin_ia32_rndscalepd_mask: 1847 case X86::BI__builtin_ia32_rndscaleps_mask: 1848 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1849 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1850 ArgNum = 4; 1851 break; 1852 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1853 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1854 case X86::BI__builtin_ia32_fixupimmps512_mask: 1855 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1856 case X86::BI__builtin_ia32_fixupimmsd_mask: 1857 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1858 case X86::BI__builtin_ia32_fixupimmss_mask: 1859 case X86::BI__builtin_ia32_fixupimmss_maskz: 1860 case X86::BI__builtin_ia32_rangepd512_mask: 1861 case X86::BI__builtin_ia32_rangeps512_mask: 1862 case X86::BI__builtin_ia32_rangesd128_round_mask: 1863 case X86::BI__builtin_ia32_rangess128_round_mask: 1864 case X86::BI__builtin_ia32_reducesd_mask: 1865 case X86::BI__builtin_ia32_reducess_mask: 1866 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1867 case X86::BI__builtin_ia32_rndscaless_round_mask: 1868 ArgNum = 5; 1869 break; 1870 case X86::BI__builtin_ia32_vcvtsd2si64: 1871 case X86::BI__builtin_ia32_vcvtsd2si32: 1872 case X86::BI__builtin_ia32_vcvtsd2usi32: 1873 case X86::BI__builtin_ia32_vcvtsd2usi64: 1874 case X86::BI__builtin_ia32_vcvtss2si32: 1875 case X86::BI__builtin_ia32_vcvtss2si64: 1876 case X86::BI__builtin_ia32_vcvtss2usi32: 1877 case X86::BI__builtin_ia32_vcvtss2usi64: 1878 ArgNum = 1; 1879 HasRC = true; 1880 break; 1881 case X86::BI__builtin_ia32_cvtsi2sd64: 1882 case X86::BI__builtin_ia32_cvtsi2ss32: 1883 case X86::BI__builtin_ia32_cvtsi2ss64: 1884 case X86::BI__builtin_ia32_cvtusi2sd64: 1885 case X86::BI__builtin_ia32_cvtusi2ss32: 1886 case X86::BI__builtin_ia32_cvtusi2ss64: 1887 ArgNum = 2; 1888 HasRC = true; 1889 break; 1890 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1891 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1892 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1893 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1894 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1895 case X86::BI__builtin_ia32_cvtps2qq512_mask: 1896 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 1897 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 1898 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 1899 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 1900 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 1901 case X86::BI__builtin_ia32_sqrtpd512_mask: 1902 case X86::BI__builtin_ia32_sqrtps512_mask: 1903 ArgNum = 3; 1904 HasRC = true; 1905 break; 1906 case X86::BI__builtin_ia32_addpd512_mask: 1907 case X86::BI__builtin_ia32_addps512_mask: 1908 case X86::BI__builtin_ia32_divpd512_mask: 1909 case X86::BI__builtin_ia32_divps512_mask: 1910 case X86::BI__builtin_ia32_mulpd512_mask: 1911 case X86::BI__builtin_ia32_mulps512_mask: 1912 case X86::BI__builtin_ia32_subpd512_mask: 1913 case X86::BI__builtin_ia32_subps512_mask: 1914 case X86::BI__builtin_ia32_addss_round_mask: 1915 case X86::BI__builtin_ia32_addsd_round_mask: 1916 case X86::BI__builtin_ia32_divss_round_mask: 1917 case X86::BI__builtin_ia32_divsd_round_mask: 1918 case X86::BI__builtin_ia32_mulss_round_mask: 1919 case X86::BI__builtin_ia32_mulsd_round_mask: 1920 case X86::BI__builtin_ia32_subss_round_mask: 1921 case X86::BI__builtin_ia32_subsd_round_mask: 1922 case X86::BI__builtin_ia32_scalefpd512_mask: 1923 case X86::BI__builtin_ia32_scalefps512_mask: 1924 case X86::BI__builtin_ia32_scalefsd_round_mask: 1925 case X86::BI__builtin_ia32_scalefss_round_mask: 1926 case X86::BI__builtin_ia32_getmantpd512_mask: 1927 case X86::BI__builtin_ia32_getmantps512_mask: 1928 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 1929 case X86::BI__builtin_ia32_sqrtsd_round_mask: 1930 case X86::BI__builtin_ia32_sqrtss_round_mask: 1931 case X86::BI__builtin_ia32_vfmaddpd512_mask: 1932 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 1933 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 1934 case X86::BI__builtin_ia32_vfmaddps512_mask: 1935 case X86::BI__builtin_ia32_vfmaddps512_mask3: 1936 case X86::BI__builtin_ia32_vfmaddps512_maskz: 1937 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 1938 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 1939 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 1940 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 1941 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 1942 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 1943 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 1944 case X86::BI__builtin_ia32_vfmsubps512_mask3: 1945 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 1946 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 1947 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 1948 case X86::BI__builtin_ia32_vfnmaddps512_mask: 1949 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 1950 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 1951 case X86::BI__builtin_ia32_vfnmsubps512_mask: 1952 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 1953 case X86::BI__builtin_ia32_vfmaddsd3_mask: 1954 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 1955 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 1956 case X86::BI__builtin_ia32_vfmaddss3_mask: 1957 case X86::BI__builtin_ia32_vfmaddss3_maskz: 1958 case X86::BI__builtin_ia32_vfmaddss3_mask3: 1959 ArgNum = 4; 1960 HasRC = true; 1961 break; 1962 case X86::BI__builtin_ia32_getmantsd_round_mask: 1963 case X86::BI__builtin_ia32_getmantss_round_mask: 1964 ArgNum = 5; 1965 HasRC = true; 1966 break; 1967 } 1968 1969 llvm::APSInt Result; 1970 1971 // We can't check the value of a dependent argument. 1972 Expr *Arg = TheCall->getArg(ArgNum); 1973 if (Arg->isTypeDependent() || Arg->isValueDependent()) 1974 return false; 1975 1976 // Check constant-ness first. 1977 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 1978 return true; 1979 1980 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 1981 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 1982 // combined with ROUND_NO_EXC. 1983 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 1984 Result == 8/*ROUND_NO_EXC*/ || 1985 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 1986 return false; 1987 1988 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 1989 << Arg->getSourceRange(); 1990 } 1991 1992 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1993 if (BuiltinID == X86::BI__builtin_cpu_supports) 1994 return SemaBuiltinCpuSupports(*this, TheCall); 1995 1996 if (BuiltinID == X86::BI__builtin_ms_va_start) 1997 return SemaBuiltinMSVAStart(TheCall); 1998 1999 // If the intrinsic has rounding or SAE make sure its valid. 2000 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2001 return true; 2002 2003 // For intrinsics which take an immediate value as part of the instruction, 2004 // range check them here. 2005 int i = 0, l = 0, u = 0; 2006 switch (BuiltinID) { 2007 default: 2008 return false; 2009 case X86::BI_mm_prefetch: 2010 i = 1; l = 0; u = 3; 2011 break; 2012 case X86::BI__builtin_ia32_sha1rnds4: 2013 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2014 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2015 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2016 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2017 i = 2; l = 0; u = 3; 2018 break; 2019 case X86::BI__builtin_ia32_vpermil2pd: 2020 case X86::BI__builtin_ia32_vpermil2pd256: 2021 case X86::BI__builtin_ia32_vpermil2ps: 2022 case X86::BI__builtin_ia32_vpermil2ps256: 2023 i = 3; l = 0; u = 3; 2024 break; 2025 case X86::BI__builtin_ia32_cmpb128_mask: 2026 case X86::BI__builtin_ia32_cmpw128_mask: 2027 case X86::BI__builtin_ia32_cmpd128_mask: 2028 case X86::BI__builtin_ia32_cmpq128_mask: 2029 case X86::BI__builtin_ia32_cmpb256_mask: 2030 case X86::BI__builtin_ia32_cmpw256_mask: 2031 case X86::BI__builtin_ia32_cmpd256_mask: 2032 case X86::BI__builtin_ia32_cmpq256_mask: 2033 case X86::BI__builtin_ia32_cmpb512_mask: 2034 case X86::BI__builtin_ia32_cmpw512_mask: 2035 case X86::BI__builtin_ia32_cmpd512_mask: 2036 case X86::BI__builtin_ia32_cmpq512_mask: 2037 case X86::BI__builtin_ia32_ucmpb128_mask: 2038 case X86::BI__builtin_ia32_ucmpw128_mask: 2039 case X86::BI__builtin_ia32_ucmpd128_mask: 2040 case X86::BI__builtin_ia32_ucmpq128_mask: 2041 case X86::BI__builtin_ia32_ucmpb256_mask: 2042 case X86::BI__builtin_ia32_ucmpw256_mask: 2043 case X86::BI__builtin_ia32_ucmpd256_mask: 2044 case X86::BI__builtin_ia32_ucmpq256_mask: 2045 case X86::BI__builtin_ia32_ucmpb512_mask: 2046 case X86::BI__builtin_ia32_ucmpw512_mask: 2047 case X86::BI__builtin_ia32_ucmpd512_mask: 2048 case X86::BI__builtin_ia32_ucmpq512_mask: 2049 case X86::BI__builtin_ia32_vpcomub: 2050 case X86::BI__builtin_ia32_vpcomuw: 2051 case X86::BI__builtin_ia32_vpcomud: 2052 case X86::BI__builtin_ia32_vpcomuq: 2053 case X86::BI__builtin_ia32_vpcomb: 2054 case X86::BI__builtin_ia32_vpcomw: 2055 case X86::BI__builtin_ia32_vpcomd: 2056 case X86::BI__builtin_ia32_vpcomq: 2057 i = 2; l = 0; u = 7; 2058 break; 2059 case X86::BI__builtin_ia32_roundps: 2060 case X86::BI__builtin_ia32_roundpd: 2061 case X86::BI__builtin_ia32_roundps256: 2062 case X86::BI__builtin_ia32_roundpd256: 2063 i = 1; l = 0; u = 15; 2064 break; 2065 case X86::BI__builtin_ia32_roundss: 2066 case X86::BI__builtin_ia32_roundsd: 2067 case X86::BI__builtin_ia32_rangepd128_mask: 2068 case X86::BI__builtin_ia32_rangepd256_mask: 2069 case X86::BI__builtin_ia32_rangepd512_mask: 2070 case X86::BI__builtin_ia32_rangeps128_mask: 2071 case X86::BI__builtin_ia32_rangeps256_mask: 2072 case X86::BI__builtin_ia32_rangeps512_mask: 2073 case X86::BI__builtin_ia32_getmantsd_round_mask: 2074 case X86::BI__builtin_ia32_getmantss_round_mask: 2075 i = 2; l = 0; u = 15; 2076 break; 2077 case X86::BI__builtin_ia32_cmpps: 2078 case X86::BI__builtin_ia32_cmpss: 2079 case X86::BI__builtin_ia32_cmppd: 2080 case X86::BI__builtin_ia32_cmpsd: 2081 case X86::BI__builtin_ia32_cmpps256: 2082 case X86::BI__builtin_ia32_cmppd256: 2083 case X86::BI__builtin_ia32_cmpps128_mask: 2084 case X86::BI__builtin_ia32_cmppd128_mask: 2085 case X86::BI__builtin_ia32_cmpps256_mask: 2086 case X86::BI__builtin_ia32_cmppd256_mask: 2087 case X86::BI__builtin_ia32_cmpps512_mask: 2088 case X86::BI__builtin_ia32_cmppd512_mask: 2089 case X86::BI__builtin_ia32_cmpsd_mask: 2090 case X86::BI__builtin_ia32_cmpss_mask: 2091 i = 2; l = 0; u = 31; 2092 break; 2093 case X86::BI__builtin_ia32_xabort: 2094 i = 0; l = -128; u = 255; 2095 break; 2096 case X86::BI__builtin_ia32_pshufw: 2097 case X86::BI__builtin_ia32_aeskeygenassist128: 2098 i = 1; l = -128; u = 255; 2099 break; 2100 case X86::BI__builtin_ia32_vcvtps2ph: 2101 case X86::BI__builtin_ia32_vcvtps2ph256: 2102 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2103 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2104 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2105 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2106 case X86::BI__builtin_ia32_rndscaleps_mask: 2107 case X86::BI__builtin_ia32_rndscalepd_mask: 2108 case X86::BI__builtin_ia32_reducepd128_mask: 2109 case X86::BI__builtin_ia32_reducepd256_mask: 2110 case X86::BI__builtin_ia32_reducepd512_mask: 2111 case X86::BI__builtin_ia32_reduceps128_mask: 2112 case X86::BI__builtin_ia32_reduceps256_mask: 2113 case X86::BI__builtin_ia32_reduceps512_mask: 2114 case X86::BI__builtin_ia32_prold512_mask: 2115 case X86::BI__builtin_ia32_prolq512_mask: 2116 case X86::BI__builtin_ia32_prold128_mask: 2117 case X86::BI__builtin_ia32_prold256_mask: 2118 case X86::BI__builtin_ia32_prolq128_mask: 2119 case X86::BI__builtin_ia32_prolq256_mask: 2120 case X86::BI__builtin_ia32_prord128_mask: 2121 case X86::BI__builtin_ia32_prord256_mask: 2122 case X86::BI__builtin_ia32_prorq128_mask: 2123 case X86::BI__builtin_ia32_prorq256_mask: 2124 case X86::BI__builtin_ia32_fpclasspd128_mask: 2125 case X86::BI__builtin_ia32_fpclasspd256_mask: 2126 case X86::BI__builtin_ia32_fpclassps128_mask: 2127 case X86::BI__builtin_ia32_fpclassps256_mask: 2128 case X86::BI__builtin_ia32_fpclassps512_mask: 2129 case X86::BI__builtin_ia32_fpclasspd512_mask: 2130 case X86::BI__builtin_ia32_fpclasssd_mask: 2131 case X86::BI__builtin_ia32_fpclassss_mask: 2132 i = 1; l = 0; u = 255; 2133 break; 2134 case X86::BI__builtin_ia32_palignr: 2135 case X86::BI__builtin_ia32_insertps128: 2136 case X86::BI__builtin_ia32_dpps: 2137 case X86::BI__builtin_ia32_dppd: 2138 case X86::BI__builtin_ia32_dpps256: 2139 case X86::BI__builtin_ia32_mpsadbw128: 2140 case X86::BI__builtin_ia32_mpsadbw256: 2141 case X86::BI__builtin_ia32_pcmpistrm128: 2142 case X86::BI__builtin_ia32_pcmpistri128: 2143 case X86::BI__builtin_ia32_pcmpistria128: 2144 case X86::BI__builtin_ia32_pcmpistric128: 2145 case X86::BI__builtin_ia32_pcmpistrio128: 2146 case X86::BI__builtin_ia32_pcmpistris128: 2147 case X86::BI__builtin_ia32_pcmpistriz128: 2148 case X86::BI__builtin_ia32_pclmulqdq128: 2149 case X86::BI__builtin_ia32_vperm2f128_pd256: 2150 case X86::BI__builtin_ia32_vperm2f128_ps256: 2151 case X86::BI__builtin_ia32_vperm2f128_si256: 2152 case X86::BI__builtin_ia32_permti256: 2153 i = 2; l = -128; u = 255; 2154 break; 2155 case X86::BI__builtin_ia32_palignr128: 2156 case X86::BI__builtin_ia32_palignr256: 2157 case X86::BI__builtin_ia32_palignr512_mask: 2158 case X86::BI__builtin_ia32_vcomisd: 2159 case X86::BI__builtin_ia32_vcomiss: 2160 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2161 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2162 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2163 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2164 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2165 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2166 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2167 i = 2; l = 0; u = 255; 2168 break; 2169 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2170 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2171 case X86::BI__builtin_ia32_fixupimmps512_mask: 2172 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2173 case X86::BI__builtin_ia32_fixupimmsd_mask: 2174 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2175 case X86::BI__builtin_ia32_fixupimmss_mask: 2176 case X86::BI__builtin_ia32_fixupimmss_maskz: 2177 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2178 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2179 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2180 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2181 case X86::BI__builtin_ia32_fixupimmps128_mask: 2182 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2183 case X86::BI__builtin_ia32_fixupimmps256_mask: 2184 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2185 case X86::BI__builtin_ia32_pternlogd512_mask: 2186 case X86::BI__builtin_ia32_pternlogd512_maskz: 2187 case X86::BI__builtin_ia32_pternlogq512_mask: 2188 case X86::BI__builtin_ia32_pternlogq512_maskz: 2189 case X86::BI__builtin_ia32_pternlogd128_mask: 2190 case X86::BI__builtin_ia32_pternlogd128_maskz: 2191 case X86::BI__builtin_ia32_pternlogd256_mask: 2192 case X86::BI__builtin_ia32_pternlogd256_maskz: 2193 case X86::BI__builtin_ia32_pternlogq128_mask: 2194 case X86::BI__builtin_ia32_pternlogq128_maskz: 2195 case X86::BI__builtin_ia32_pternlogq256_mask: 2196 case X86::BI__builtin_ia32_pternlogq256_maskz: 2197 i = 3; l = 0; u = 255; 2198 break; 2199 case X86::BI__builtin_ia32_pcmpestrm128: 2200 case X86::BI__builtin_ia32_pcmpestri128: 2201 case X86::BI__builtin_ia32_pcmpestria128: 2202 case X86::BI__builtin_ia32_pcmpestric128: 2203 case X86::BI__builtin_ia32_pcmpestrio128: 2204 case X86::BI__builtin_ia32_pcmpestris128: 2205 case X86::BI__builtin_ia32_pcmpestriz128: 2206 i = 4; l = -128; u = 255; 2207 break; 2208 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2209 case X86::BI__builtin_ia32_rndscaless_round_mask: 2210 i = 4; l = 0; u = 255; 2211 break; 2212 } 2213 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2214 } 2215 2216 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2217 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2218 /// Returns true when the format fits the function and the FormatStringInfo has 2219 /// been populated. 2220 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2221 FormatStringInfo *FSI) { 2222 FSI->HasVAListArg = Format->getFirstArg() == 0; 2223 FSI->FormatIdx = Format->getFormatIdx() - 1; 2224 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2225 2226 // The way the format attribute works in GCC, the implicit this argument 2227 // of member functions is counted. However, it doesn't appear in our own 2228 // lists, so decrement format_idx in that case. 2229 if (IsCXXMember) { 2230 if(FSI->FormatIdx == 0) 2231 return false; 2232 --FSI->FormatIdx; 2233 if (FSI->FirstDataArg != 0) 2234 --FSI->FirstDataArg; 2235 } 2236 return true; 2237 } 2238 2239 /// Checks if a the given expression evaluates to null. 2240 /// 2241 /// \brief Returns true if the value evaluates to null. 2242 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2243 // If the expression has non-null type, it doesn't evaluate to null. 2244 if (auto nullability 2245 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2246 if (*nullability == NullabilityKind::NonNull) 2247 return false; 2248 } 2249 2250 // As a special case, transparent unions initialized with zero are 2251 // considered null for the purposes of the nonnull attribute. 2252 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2253 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2254 if (const CompoundLiteralExpr *CLE = 2255 dyn_cast<CompoundLiteralExpr>(Expr)) 2256 if (const InitListExpr *ILE = 2257 dyn_cast<InitListExpr>(CLE->getInitializer())) 2258 Expr = ILE->getInit(0); 2259 } 2260 2261 bool Result; 2262 return (!Expr->isValueDependent() && 2263 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2264 !Result); 2265 } 2266 2267 static void CheckNonNullArgument(Sema &S, 2268 const Expr *ArgExpr, 2269 SourceLocation CallSiteLoc) { 2270 if (CheckNonNullExpr(S, ArgExpr)) 2271 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2272 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2273 } 2274 2275 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2276 FormatStringInfo FSI; 2277 if ((GetFormatStringType(Format) == FST_NSString) && 2278 getFormatStringInfo(Format, false, &FSI)) { 2279 Idx = FSI.FormatIdx; 2280 return true; 2281 } 2282 return false; 2283 } 2284 /// \brief Diagnose use of %s directive in an NSString which is being passed 2285 /// as formatting string to formatting method. 2286 static void 2287 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2288 const NamedDecl *FDecl, 2289 Expr **Args, 2290 unsigned NumArgs) { 2291 unsigned Idx = 0; 2292 bool Format = false; 2293 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2294 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2295 Idx = 2; 2296 Format = true; 2297 } 2298 else 2299 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2300 if (S.GetFormatNSStringIdx(I, Idx)) { 2301 Format = true; 2302 break; 2303 } 2304 } 2305 if (!Format || NumArgs <= Idx) 2306 return; 2307 const Expr *FormatExpr = Args[Idx]; 2308 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2309 FormatExpr = CSCE->getSubExpr(); 2310 const StringLiteral *FormatString; 2311 if (const ObjCStringLiteral *OSL = 2312 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2313 FormatString = OSL->getString(); 2314 else 2315 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2316 if (!FormatString) 2317 return; 2318 if (S.FormatStringHasSArg(FormatString)) { 2319 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2320 << "%s" << 1 << 1; 2321 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2322 << FDecl->getDeclName(); 2323 } 2324 } 2325 2326 /// Determine whether the given type has a non-null nullability annotation. 2327 static bool isNonNullType(ASTContext &ctx, QualType type) { 2328 if (auto nullability = type->getNullability(ctx)) 2329 return *nullability == NullabilityKind::NonNull; 2330 2331 return false; 2332 } 2333 2334 static void CheckNonNullArguments(Sema &S, 2335 const NamedDecl *FDecl, 2336 const FunctionProtoType *Proto, 2337 ArrayRef<const Expr *> Args, 2338 SourceLocation CallSiteLoc) { 2339 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2340 2341 // Check the attributes attached to the method/function itself. 2342 llvm::SmallBitVector NonNullArgs; 2343 if (FDecl) { 2344 // Handle the nonnull attribute on the function/method declaration itself. 2345 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2346 if (!NonNull->args_size()) { 2347 // Easy case: all pointer arguments are nonnull. 2348 for (const auto *Arg : Args) 2349 if (S.isValidPointerAttrType(Arg->getType())) 2350 CheckNonNullArgument(S, Arg, CallSiteLoc); 2351 return; 2352 } 2353 2354 for (unsigned Val : NonNull->args()) { 2355 if (Val >= Args.size()) 2356 continue; 2357 if (NonNullArgs.empty()) 2358 NonNullArgs.resize(Args.size()); 2359 NonNullArgs.set(Val); 2360 } 2361 } 2362 } 2363 2364 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2365 // Handle the nonnull attribute on the parameters of the 2366 // function/method. 2367 ArrayRef<ParmVarDecl*> parms; 2368 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2369 parms = FD->parameters(); 2370 else 2371 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2372 2373 unsigned ParamIndex = 0; 2374 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2375 I != E; ++I, ++ParamIndex) { 2376 const ParmVarDecl *PVD = *I; 2377 if (PVD->hasAttr<NonNullAttr>() || 2378 isNonNullType(S.Context, PVD->getType())) { 2379 if (NonNullArgs.empty()) 2380 NonNullArgs.resize(Args.size()); 2381 2382 NonNullArgs.set(ParamIndex); 2383 } 2384 } 2385 } else { 2386 // If we have a non-function, non-method declaration but no 2387 // function prototype, try to dig out the function prototype. 2388 if (!Proto) { 2389 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2390 QualType type = VD->getType().getNonReferenceType(); 2391 if (auto pointerType = type->getAs<PointerType>()) 2392 type = pointerType->getPointeeType(); 2393 else if (auto blockType = type->getAs<BlockPointerType>()) 2394 type = blockType->getPointeeType(); 2395 // FIXME: data member pointers? 2396 2397 // Dig out the function prototype, if there is one. 2398 Proto = type->getAs<FunctionProtoType>(); 2399 } 2400 } 2401 2402 // Fill in non-null argument information from the nullability 2403 // information on the parameter types (if we have them). 2404 if (Proto) { 2405 unsigned Index = 0; 2406 for (auto paramType : Proto->getParamTypes()) { 2407 if (isNonNullType(S.Context, paramType)) { 2408 if (NonNullArgs.empty()) 2409 NonNullArgs.resize(Args.size()); 2410 2411 NonNullArgs.set(Index); 2412 } 2413 2414 ++Index; 2415 } 2416 } 2417 } 2418 2419 // Check for non-null arguments. 2420 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2421 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2422 if (NonNullArgs[ArgIndex]) 2423 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2424 } 2425 } 2426 2427 /// Handles the checks for format strings, non-POD arguments to vararg 2428 /// functions, and NULL arguments passed to non-NULL parameters. 2429 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2430 ArrayRef<const Expr *> Args, bool IsMemberFunction, 2431 SourceLocation Loc, SourceRange Range, 2432 VariadicCallType CallType) { 2433 // FIXME: We should check as much as we can in the template definition. 2434 if (CurContext->isDependentContext()) 2435 return; 2436 2437 // Printf and scanf checking. 2438 llvm::SmallBitVector CheckedVarArgs; 2439 if (FDecl) { 2440 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2441 // Only create vector if there are format attributes. 2442 CheckedVarArgs.resize(Args.size()); 2443 2444 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2445 CheckedVarArgs); 2446 } 2447 } 2448 2449 // Refuse POD arguments that weren't caught by the format string 2450 // checks above. 2451 if (CallType != VariadicDoesNotApply) { 2452 unsigned NumParams = Proto ? Proto->getNumParams() 2453 : FDecl && isa<FunctionDecl>(FDecl) 2454 ? cast<FunctionDecl>(FDecl)->getNumParams() 2455 : FDecl && isa<ObjCMethodDecl>(FDecl) 2456 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2457 : 0; 2458 2459 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2460 // Args[ArgIdx] can be null in malformed code. 2461 if (const Expr *Arg = Args[ArgIdx]) { 2462 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2463 checkVariadicArgument(Arg, CallType); 2464 } 2465 } 2466 } 2467 2468 if (FDecl || Proto) { 2469 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2470 2471 // Type safety checking. 2472 if (FDecl) { 2473 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2474 CheckArgumentWithTypeTag(I, Args.data()); 2475 } 2476 } 2477 } 2478 2479 /// CheckConstructorCall - Check a constructor call for correctness and safety 2480 /// properties not enforced by the C type system. 2481 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2482 ArrayRef<const Expr *> Args, 2483 const FunctionProtoType *Proto, 2484 SourceLocation Loc) { 2485 VariadicCallType CallType = 2486 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2487 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(), 2488 CallType); 2489 } 2490 2491 /// CheckFunctionCall - Check a direct function call for various correctness 2492 /// and safety properties not strictly enforced by the C type system. 2493 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2494 const FunctionProtoType *Proto) { 2495 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2496 isa<CXXMethodDecl>(FDecl); 2497 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2498 IsMemberOperatorCall; 2499 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2500 TheCall->getCallee()); 2501 Expr** Args = TheCall->getArgs(); 2502 unsigned NumArgs = TheCall->getNumArgs(); 2503 if (IsMemberOperatorCall) { 2504 // If this is a call to a member operator, hide the first argument 2505 // from checkCall. 2506 // FIXME: Our choice of AST representation here is less than ideal. 2507 ++Args; 2508 --NumArgs; 2509 } 2510 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs), 2511 IsMemberFunction, TheCall->getRParenLoc(), 2512 TheCall->getCallee()->getSourceRange(), CallType); 2513 2514 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2515 // None of the checks below are needed for functions that don't have 2516 // simple names (e.g., C++ conversion functions). 2517 if (!FnInfo) 2518 return false; 2519 2520 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo); 2521 if (getLangOpts().ObjC1) 2522 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2523 2524 unsigned CMId = FDecl->getMemoryFunctionKind(); 2525 if (CMId == 0) 2526 return false; 2527 2528 // Handle memory setting and copying functions. 2529 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2530 CheckStrlcpycatArguments(TheCall, FnInfo); 2531 else if (CMId == Builtin::BIstrncat) 2532 CheckStrncatArguments(TheCall, FnInfo); 2533 else 2534 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2535 2536 return false; 2537 } 2538 2539 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2540 ArrayRef<const Expr *> Args) { 2541 VariadicCallType CallType = 2542 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2543 2544 checkCall(Method, nullptr, Args, 2545 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2546 CallType); 2547 2548 return false; 2549 } 2550 2551 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2552 const FunctionProtoType *Proto) { 2553 QualType Ty; 2554 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2555 Ty = V->getType().getNonReferenceType(); 2556 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2557 Ty = F->getType().getNonReferenceType(); 2558 else 2559 return false; 2560 2561 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2562 !Ty->isFunctionProtoType()) 2563 return false; 2564 2565 VariadicCallType CallType; 2566 if (!Proto || !Proto->isVariadic()) { 2567 CallType = VariadicDoesNotApply; 2568 } else if (Ty->isBlockPointerType()) { 2569 CallType = VariadicBlock; 2570 } else { // Ty->isFunctionPointerType() 2571 CallType = VariadicFunction; 2572 } 2573 2574 checkCall(NDecl, Proto, 2575 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2576 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2577 TheCall->getCallee()->getSourceRange(), CallType); 2578 2579 return false; 2580 } 2581 2582 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2583 /// such as function pointers returned from functions. 2584 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2585 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2586 TheCall->getCallee()); 2587 checkCall(/*FDecl=*/nullptr, Proto, 2588 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2589 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2590 TheCall->getCallee()->getSourceRange(), CallType); 2591 2592 return false; 2593 } 2594 2595 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2596 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2597 return false; 2598 2599 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2600 switch (Op) { 2601 case AtomicExpr::AO__c11_atomic_init: 2602 llvm_unreachable("There is no ordering argument for an init"); 2603 2604 case AtomicExpr::AO__c11_atomic_load: 2605 case AtomicExpr::AO__atomic_load_n: 2606 case AtomicExpr::AO__atomic_load: 2607 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2608 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2609 2610 case AtomicExpr::AO__c11_atomic_store: 2611 case AtomicExpr::AO__atomic_store: 2612 case AtomicExpr::AO__atomic_store_n: 2613 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2614 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2615 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2616 2617 default: 2618 return true; 2619 } 2620 } 2621 2622 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2623 AtomicExpr::AtomicOp Op) { 2624 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2625 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2626 2627 // All these operations take one of the following forms: 2628 enum { 2629 // C __c11_atomic_init(A *, C) 2630 Init, 2631 // C __c11_atomic_load(A *, int) 2632 Load, 2633 // void __atomic_load(A *, CP, int) 2634 LoadCopy, 2635 // void __atomic_store(A *, CP, int) 2636 Copy, 2637 // C __c11_atomic_add(A *, M, int) 2638 Arithmetic, 2639 // C __atomic_exchange_n(A *, CP, int) 2640 Xchg, 2641 // void __atomic_exchange(A *, C *, CP, int) 2642 GNUXchg, 2643 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2644 C11CmpXchg, 2645 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2646 GNUCmpXchg 2647 } Form = Init; 2648 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2649 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2650 // where: 2651 // C is an appropriate type, 2652 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2653 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2654 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2655 // the int parameters are for orderings. 2656 2657 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2658 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2659 AtomicExpr::AO__atomic_load, 2660 "need to update code for modified C11 atomics"); 2661 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 2662 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 2663 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2664 Op == AtomicExpr::AO__atomic_store_n || 2665 Op == AtomicExpr::AO__atomic_exchange_n || 2666 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2667 bool IsAddSub = false; 2668 2669 switch (Op) { 2670 case AtomicExpr::AO__c11_atomic_init: 2671 Form = Init; 2672 break; 2673 2674 case AtomicExpr::AO__c11_atomic_load: 2675 case AtomicExpr::AO__atomic_load_n: 2676 Form = Load; 2677 break; 2678 2679 case AtomicExpr::AO__atomic_load: 2680 Form = LoadCopy; 2681 break; 2682 2683 case AtomicExpr::AO__c11_atomic_store: 2684 case AtomicExpr::AO__atomic_store: 2685 case AtomicExpr::AO__atomic_store_n: 2686 Form = Copy; 2687 break; 2688 2689 case AtomicExpr::AO__c11_atomic_fetch_add: 2690 case AtomicExpr::AO__c11_atomic_fetch_sub: 2691 case AtomicExpr::AO__atomic_fetch_add: 2692 case AtomicExpr::AO__atomic_fetch_sub: 2693 case AtomicExpr::AO__atomic_add_fetch: 2694 case AtomicExpr::AO__atomic_sub_fetch: 2695 IsAddSub = true; 2696 // Fall through. 2697 case AtomicExpr::AO__c11_atomic_fetch_and: 2698 case AtomicExpr::AO__c11_atomic_fetch_or: 2699 case AtomicExpr::AO__c11_atomic_fetch_xor: 2700 case AtomicExpr::AO__atomic_fetch_and: 2701 case AtomicExpr::AO__atomic_fetch_or: 2702 case AtomicExpr::AO__atomic_fetch_xor: 2703 case AtomicExpr::AO__atomic_fetch_nand: 2704 case AtomicExpr::AO__atomic_and_fetch: 2705 case AtomicExpr::AO__atomic_or_fetch: 2706 case AtomicExpr::AO__atomic_xor_fetch: 2707 case AtomicExpr::AO__atomic_nand_fetch: 2708 Form = Arithmetic; 2709 break; 2710 2711 case AtomicExpr::AO__c11_atomic_exchange: 2712 case AtomicExpr::AO__atomic_exchange_n: 2713 Form = Xchg; 2714 break; 2715 2716 case AtomicExpr::AO__atomic_exchange: 2717 Form = GNUXchg; 2718 break; 2719 2720 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2721 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2722 Form = C11CmpXchg; 2723 break; 2724 2725 case AtomicExpr::AO__atomic_compare_exchange: 2726 case AtomicExpr::AO__atomic_compare_exchange_n: 2727 Form = GNUCmpXchg; 2728 break; 2729 } 2730 2731 // Check we have the right number of arguments. 2732 if (TheCall->getNumArgs() < NumArgs[Form]) { 2733 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2734 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2735 << TheCall->getCallee()->getSourceRange(); 2736 return ExprError(); 2737 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 2738 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 2739 diag::err_typecheck_call_too_many_args) 2740 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2741 << TheCall->getCallee()->getSourceRange(); 2742 return ExprError(); 2743 } 2744 2745 // Inspect the first argument of the atomic operation. 2746 Expr *Ptr = TheCall->getArg(0); 2747 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2748 if (ConvertedPtr.isInvalid()) 2749 return ExprError(); 2750 2751 Ptr = ConvertedPtr.get(); 2752 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2753 if (!pointerType) { 2754 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2755 << Ptr->getType() << Ptr->getSourceRange(); 2756 return ExprError(); 2757 } 2758 2759 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2760 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2761 QualType ValType = AtomTy; // 'C' 2762 if (IsC11) { 2763 if (!AtomTy->isAtomicType()) { 2764 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 2765 << Ptr->getType() << Ptr->getSourceRange(); 2766 return ExprError(); 2767 } 2768 if (AtomTy.isConstQualified()) { 2769 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 2770 << Ptr->getType() << Ptr->getSourceRange(); 2771 return ExprError(); 2772 } 2773 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 2774 } else if (Form != Load && Form != LoadCopy) { 2775 if (ValType.isConstQualified()) { 2776 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 2777 << Ptr->getType() << Ptr->getSourceRange(); 2778 return ExprError(); 2779 } 2780 } 2781 2782 // For an arithmetic operation, the implied arithmetic must be well-formed. 2783 if (Form == Arithmetic) { 2784 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 2785 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 2786 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2787 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2788 return ExprError(); 2789 } 2790 if (!IsAddSub && !ValType->isIntegerType()) { 2791 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 2792 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2793 return ExprError(); 2794 } 2795 if (IsC11 && ValType->isPointerType() && 2796 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 2797 diag::err_incomplete_type)) { 2798 return ExprError(); 2799 } 2800 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 2801 // For __atomic_*_n operations, the value type must be a scalar integral or 2802 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 2803 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2804 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2805 return ExprError(); 2806 } 2807 2808 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 2809 !AtomTy->isScalarType()) { 2810 // For GNU atomics, require a trivially-copyable type. This is not part of 2811 // the GNU atomics specification, but we enforce it for sanity. 2812 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 2813 << Ptr->getType() << Ptr->getSourceRange(); 2814 return ExprError(); 2815 } 2816 2817 switch (ValType.getObjCLifetime()) { 2818 case Qualifiers::OCL_None: 2819 case Qualifiers::OCL_ExplicitNone: 2820 // okay 2821 break; 2822 2823 case Qualifiers::OCL_Weak: 2824 case Qualifiers::OCL_Strong: 2825 case Qualifiers::OCL_Autoreleasing: 2826 // FIXME: Can this happen? By this point, ValType should be known 2827 // to be trivially copyable. 2828 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 2829 << ValType << Ptr->getSourceRange(); 2830 return ExprError(); 2831 } 2832 2833 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 2834 // volatile-ness of the pointee-type inject itself into the result or the 2835 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 2836 ValType.removeLocalVolatile(); 2837 ValType.removeLocalConst(); 2838 QualType ResultType = ValType; 2839 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init) 2840 ResultType = Context.VoidTy; 2841 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 2842 ResultType = Context.BoolTy; 2843 2844 // The type of a parameter passed 'by value'. In the GNU atomics, such 2845 // arguments are actually passed as pointers. 2846 QualType ByValType = ValType; // 'CP' 2847 if (!IsC11 && !IsN) 2848 ByValType = Ptr->getType(); 2849 2850 // The first argument --- the pointer --- has a fixed type; we 2851 // deduce the types of the rest of the arguments accordingly. Walk 2852 // the remaining arguments, converting them to the deduced value type. 2853 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 2854 QualType Ty; 2855 if (i < NumVals[Form] + 1) { 2856 switch (i) { 2857 case 1: 2858 // The second argument is the non-atomic operand. For arithmetic, this 2859 // is always passed by value, and for a compare_exchange it is always 2860 // passed by address. For the rest, GNU uses by-address and C11 uses 2861 // by-value. 2862 assert(Form != Load); 2863 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 2864 Ty = ValType; 2865 else if (Form == Copy || Form == Xchg) 2866 Ty = ByValType; 2867 else if (Form == Arithmetic) 2868 Ty = Context.getPointerDiffType(); 2869 else { 2870 Expr *ValArg = TheCall->getArg(i); 2871 // Treat this argument as _Nonnull as we want to show a warning if 2872 // NULL is passed into it. 2873 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 2874 unsigned AS = 0; 2875 // Keep address space of non-atomic pointer type. 2876 if (const PointerType *PtrTy = 2877 ValArg->getType()->getAs<PointerType>()) { 2878 AS = PtrTy->getPointeeType().getAddressSpace(); 2879 } 2880 Ty = Context.getPointerType( 2881 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 2882 } 2883 break; 2884 case 2: 2885 // The third argument to compare_exchange / GNU exchange is a 2886 // (pointer to a) desired value. 2887 Ty = ByValType; 2888 break; 2889 case 3: 2890 // The fourth argument to GNU compare_exchange is a 'weak' flag. 2891 Ty = Context.BoolTy; 2892 break; 2893 } 2894 } else { 2895 // The order(s) are always converted to int. 2896 Ty = Context.IntTy; 2897 } 2898 2899 InitializedEntity Entity = 2900 InitializedEntity::InitializeParameter(Context, Ty, false); 2901 ExprResult Arg = TheCall->getArg(i); 2902 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 2903 if (Arg.isInvalid()) 2904 return true; 2905 TheCall->setArg(i, Arg.get()); 2906 } 2907 2908 // Permute the arguments into a 'consistent' order. 2909 SmallVector<Expr*, 5> SubExprs; 2910 SubExprs.push_back(Ptr); 2911 switch (Form) { 2912 case Init: 2913 // Note, AtomicExpr::getVal1() has a special case for this atomic. 2914 SubExprs.push_back(TheCall->getArg(1)); // Val1 2915 break; 2916 case Load: 2917 SubExprs.push_back(TheCall->getArg(1)); // Order 2918 break; 2919 case LoadCopy: 2920 case Copy: 2921 case Arithmetic: 2922 case Xchg: 2923 SubExprs.push_back(TheCall->getArg(2)); // Order 2924 SubExprs.push_back(TheCall->getArg(1)); // Val1 2925 break; 2926 case GNUXchg: 2927 // Note, AtomicExpr::getVal2() has a special case for this atomic. 2928 SubExprs.push_back(TheCall->getArg(3)); // Order 2929 SubExprs.push_back(TheCall->getArg(1)); // Val1 2930 SubExprs.push_back(TheCall->getArg(2)); // Val2 2931 break; 2932 case C11CmpXchg: 2933 SubExprs.push_back(TheCall->getArg(3)); // Order 2934 SubExprs.push_back(TheCall->getArg(1)); // Val1 2935 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 2936 SubExprs.push_back(TheCall->getArg(2)); // Val2 2937 break; 2938 case GNUCmpXchg: 2939 SubExprs.push_back(TheCall->getArg(4)); // Order 2940 SubExprs.push_back(TheCall->getArg(1)); // Val1 2941 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 2942 SubExprs.push_back(TheCall->getArg(2)); // Val2 2943 SubExprs.push_back(TheCall->getArg(3)); // Weak 2944 break; 2945 } 2946 2947 if (SubExprs.size() >= 2 && Form != Init) { 2948 llvm::APSInt Result(32); 2949 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 2950 !isValidOrderingForOp(Result.getSExtValue(), Op)) 2951 Diag(SubExprs[1]->getLocStart(), 2952 diag::warn_atomic_op_has_invalid_memory_order) 2953 << SubExprs[1]->getSourceRange(); 2954 } 2955 2956 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 2957 SubExprs, ResultType, Op, 2958 TheCall->getRParenLoc()); 2959 2960 if ((Op == AtomicExpr::AO__c11_atomic_load || 2961 (Op == AtomicExpr::AO__c11_atomic_store)) && 2962 Context.AtomicUsesUnsupportedLibcall(AE)) 2963 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 2964 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 2965 2966 return AE; 2967 } 2968 2969 /// checkBuiltinArgument - Given a call to a builtin function, perform 2970 /// normal type-checking on the given argument, updating the call in 2971 /// place. This is useful when a builtin function requires custom 2972 /// type-checking for some of its arguments but not necessarily all of 2973 /// them. 2974 /// 2975 /// Returns true on error. 2976 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 2977 FunctionDecl *Fn = E->getDirectCallee(); 2978 assert(Fn && "builtin call without direct callee!"); 2979 2980 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 2981 InitializedEntity Entity = 2982 InitializedEntity::InitializeParameter(S.Context, Param); 2983 2984 ExprResult Arg = E->getArg(0); 2985 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 2986 if (Arg.isInvalid()) 2987 return true; 2988 2989 E->setArg(ArgIndex, Arg.get()); 2990 return false; 2991 } 2992 2993 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 2994 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 2995 /// type of its first argument. The main ActOnCallExpr routines have already 2996 /// promoted the types of arguments because all of these calls are prototyped as 2997 /// void(...). 2998 /// 2999 /// This function goes through and does final semantic checking for these 3000 /// builtins, 3001 ExprResult 3002 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3003 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3004 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3005 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3006 3007 // Ensure that we have at least one argument to do type inference from. 3008 if (TheCall->getNumArgs() < 1) { 3009 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3010 << 0 << 1 << TheCall->getNumArgs() 3011 << TheCall->getCallee()->getSourceRange(); 3012 return ExprError(); 3013 } 3014 3015 // Inspect the first argument of the atomic builtin. This should always be 3016 // a pointer type, whose element is an integral scalar or pointer type. 3017 // Because it is a pointer type, we don't have to worry about any implicit 3018 // casts here. 3019 // FIXME: We don't allow floating point scalars as input. 3020 Expr *FirstArg = TheCall->getArg(0); 3021 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3022 if (FirstArgResult.isInvalid()) 3023 return ExprError(); 3024 FirstArg = FirstArgResult.get(); 3025 TheCall->setArg(0, FirstArg); 3026 3027 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3028 if (!pointerType) { 3029 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3030 << FirstArg->getType() << FirstArg->getSourceRange(); 3031 return ExprError(); 3032 } 3033 3034 QualType ValType = pointerType->getPointeeType(); 3035 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3036 !ValType->isBlockPointerType()) { 3037 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3038 << FirstArg->getType() << FirstArg->getSourceRange(); 3039 return ExprError(); 3040 } 3041 3042 switch (ValType.getObjCLifetime()) { 3043 case Qualifiers::OCL_None: 3044 case Qualifiers::OCL_ExplicitNone: 3045 // okay 3046 break; 3047 3048 case Qualifiers::OCL_Weak: 3049 case Qualifiers::OCL_Strong: 3050 case Qualifiers::OCL_Autoreleasing: 3051 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3052 << ValType << FirstArg->getSourceRange(); 3053 return ExprError(); 3054 } 3055 3056 // Strip any qualifiers off ValType. 3057 ValType = ValType.getUnqualifiedType(); 3058 3059 // The majority of builtins return a value, but a few have special return 3060 // types, so allow them to override appropriately below. 3061 QualType ResultType = ValType; 3062 3063 // We need to figure out which concrete builtin this maps onto. For example, 3064 // __sync_fetch_and_add with a 2 byte object turns into 3065 // __sync_fetch_and_add_2. 3066 #define BUILTIN_ROW(x) \ 3067 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3068 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3069 3070 static const unsigned BuiltinIndices[][5] = { 3071 BUILTIN_ROW(__sync_fetch_and_add), 3072 BUILTIN_ROW(__sync_fetch_and_sub), 3073 BUILTIN_ROW(__sync_fetch_and_or), 3074 BUILTIN_ROW(__sync_fetch_and_and), 3075 BUILTIN_ROW(__sync_fetch_and_xor), 3076 BUILTIN_ROW(__sync_fetch_and_nand), 3077 3078 BUILTIN_ROW(__sync_add_and_fetch), 3079 BUILTIN_ROW(__sync_sub_and_fetch), 3080 BUILTIN_ROW(__sync_and_and_fetch), 3081 BUILTIN_ROW(__sync_or_and_fetch), 3082 BUILTIN_ROW(__sync_xor_and_fetch), 3083 BUILTIN_ROW(__sync_nand_and_fetch), 3084 3085 BUILTIN_ROW(__sync_val_compare_and_swap), 3086 BUILTIN_ROW(__sync_bool_compare_and_swap), 3087 BUILTIN_ROW(__sync_lock_test_and_set), 3088 BUILTIN_ROW(__sync_lock_release), 3089 BUILTIN_ROW(__sync_swap) 3090 }; 3091 #undef BUILTIN_ROW 3092 3093 // Determine the index of the size. 3094 unsigned SizeIndex; 3095 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3096 case 1: SizeIndex = 0; break; 3097 case 2: SizeIndex = 1; break; 3098 case 4: SizeIndex = 2; break; 3099 case 8: SizeIndex = 3; break; 3100 case 16: SizeIndex = 4; break; 3101 default: 3102 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3103 << FirstArg->getType() << FirstArg->getSourceRange(); 3104 return ExprError(); 3105 } 3106 3107 // Each of these builtins has one pointer argument, followed by some number of 3108 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3109 // that we ignore. Find out which row of BuiltinIndices to read from as well 3110 // as the number of fixed args. 3111 unsigned BuiltinID = FDecl->getBuiltinID(); 3112 unsigned BuiltinIndex, NumFixed = 1; 3113 bool WarnAboutSemanticsChange = false; 3114 switch (BuiltinID) { 3115 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3116 case Builtin::BI__sync_fetch_and_add: 3117 case Builtin::BI__sync_fetch_and_add_1: 3118 case Builtin::BI__sync_fetch_and_add_2: 3119 case Builtin::BI__sync_fetch_and_add_4: 3120 case Builtin::BI__sync_fetch_and_add_8: 3121 case Builtin::BI__sync_fetch_and_add_16: 3122 BuiltinIndex = 0; 3123 break; 3124 3125 case Builtin::BI__sync_fetch_and_sub: 3126 case Builtin::BI__sync_fetch_and_sub_1: 3127 case Builtin::BI__sync_fetch_and_sub_2: 3128 case Builtin::BI__sync_fetch_and_sub_4: 3129 case Builtin::BI__sync_fetch_and_sub_8: 3130 case Builtin::BI__sync_fetch_and_sub_16: 3131 BuiltinIndex = 1; 3132 break; 3133 3134 case Builtin::BI__sync_fetch_and_or: 3135 case Builtin::BI__sync_fetch_and_or_1: 3136 case Builtin::BI__sync_fetch_and_or_2: 3137 case Builtin::BI__sync_fetch_and_or_4: 3138 case Builtin::BI__sync_fetch_and_or_8: 3139 case Builtin::BI__sync_fetch_and_or_16: 3140 BuiltinIndex = 2; 3141 break; 3142 3143 case Builtin::BI__sync_fetch_and_and: 3144 case Builtin::BI__sync_fetch_and_and_1: 3145 case Builtin::BI__sync_fetch_and_and_2: 3146 case Builtin::BI__sync_fetch_and_and_4: 3147 case Builtin::BI__sync_fetch_and_and_8: 3148 case Builtin::BI__sync_fetch_and_and_16: 3149 BuiltinIndex = 3; 3150 break; 3151 3152 case Builtin::BI__sync_fetch_and_xor: 3153 case Builtin::BI__sync_fetch_and_xor_1: 3154 case Builtin::BI__sync_fetch_and_xor_2: 3155 case Builtin::BI__sync_fetch_and_xor_4: 3156 case Builtin::BI__sync_fetch_and_xor_8: 3157 case Builtin::BI__sync_fetch_and_xor_16: 3158 BuiltinIndex = 4; 3159 break; 3160 3161 case Builtin::BI__sync_fetch_and_nand: 3162 case Builtin::BI__sync_fetch_and_nand_1: 3163 case Builtin::BI__sync_fetch_and_nand_2: 3164 case Builtin::BI__sync_fetch_and_nand_4: 3165 case Builtin::BI__sync_fetch_and_nand_8: 3166 case Builtin::BI__sync_fetch_and_nand_16: 3167 BuiltinIndex = 5; 3168 WarnAboutSemanticsChange = true; 3169 break; 3170 3171 case Builtin::BI__sync_add_and_fetch: 3172 case Builtin::BI__sync_add_and_fetch_1: 3173 case Builtin::BI__sync_add_and_fetch_2: 3174 case Builtin::BI__sync_add_and_fetch_4: 3175 case Builtin::BI__sync_add_and_fetch_8: 3176 case Builtin::BI__sync_add_and_fetch_16: 3177 BuiltinIndex = 6; 3178 break; 3179 3180 case Builtin::BI__sync_sub_and_fetch: 3181 case Builtin::BI__sync_sub_and_fetch_1: 3182 case Builtin::BI__sync_sub_and_fetch_2: 3183 case Builtin::BI__sync_sub_and_fetch_4: 3184 case Builtin::BI__sync_sub_and_fetch_8: 3185 case Builtin::BI__sync_sub_and_fetch_16: 3186 BuiltinIndex = 7; 3187 break; 3188 3189 case Builtin::BI__sync_and_and_fetch: 3190 case Builtin::BI__sync_and_and_fetch_1: 3191 case Builtin::BI__sync_and_and_fetch_2: 3192 case Builtin::BI__sync_and_and_fetch_4: 3193 case Builtin::BI__sync_and_and_fetch_8: 3194 case Builtin::BI__sync_and_and_fetch_16: 3195 BuiltinIndex = 8; 3196 break; 3197 3198 case Builtin::BI__sync_or_and_fetch: 3199 case Builtin::BI__sync_or_and_fetch_1: 3200 case Builtin::BI__sync_or_and_fetch_2: 3201 case Builtin::BI__sync_or_and_fetch_4: 3202 case Builtin::BI__sync_or_and_fetch_8: 3203 case Builtin::BI__sync_or_and_fetch_16: 3204 BuiltinIndex = 9; 3205 break; 3206 3207 case Builtin::BI__sync_xor_and_fetch: 3208 case Builtin::BI__sync_xor_and_fetch_1: 3209 case Builtin::BI__sync_xor_and_fetch_2: 3210 case Builtin::BI__sync_xor_and_fetch_4: 3211 case Builtin::BI__sync_xor_and_fetch_8: 3212 case Builtin::BI__sync_xor_and_fetch_16: 3213 BuiltinIndex = 10; 3214 break; 3215 3216 case Builtin::BI__sync_nand_and_fetch: 3217 case Builtin::BI__sync_nand_and_fetch_1: 3218 case Builtin::BI__sync_nand_and_fetch_2: 3219 case Builtin::BI__sync_nand_and_fetch_4: 3220 case Builtin::BI__sync_nand_and_fetch_8: 3221 case Builtin::BI__sync_nand_and_fetch_16: 3222 BuiltinIndex = 11; 3223 WarnAboutSemanticsChange = true; 3224 break; 3225 3226 case Builtin::BI__sync_val_compare_and_swap: 3227 case Builtin::BI__sync_val_compare_and_swap_1: 3228 case Builtin::BI__sync_val_compare_and_swap_2: 3229 case Builtin::BI__sync_val_compare_and_swap_4: 3230 case Builtin::BI__sync_val_compare_and_swap_8: 3231 case Builtin::BI__sync_val_compare_and_swap_16: 3232 BuiltinIndex = 12; 3233 NumFixed = 2; 3234 break; 3235 3236 case Builtin::BI__sync_bool_compare_and_swap: 3237 case Builtin::BI__sync_bool_compare_and_swap_1: 3238 case Builtin::BI__sync_bool_compare_and_swap_2: 3239 case Builtin::BI__sync_bool_compare_and_swap_4: 3240 case Builtin::BI__sync_bool_compare_and_swap_8: 3241 case Builtin::BI__sync_bool_compare_and_swap_16: 3242 BuiltinIndex = 13; 3243 NumFixed = 2; 3244 ResultType = Context.BoolTy; 3245 break; 3246 3247 case Builtin::BI__sync_lock_test_and_set: 3248 case Builtin::BI__sync_lock_test_and_set_1: 3249 case Builtin::BI__sync_lock_test_and_set_2: 3250 case Builtin::BI__sync_lock_test_and_set_4: 3251 case Builtin::BI__sync_lock_test_and_set_8: 3252 case Builtin::BI__sync_lock_test_and_set_16: 3253 BuiltinIndex = 14; 3254 break; 3255 3256 case Builtin::BI__sync_lock_release: 3257 case Builtin::BI__sync_lock_release_1: 3258 case Builtin::BI__sync_lock_release_2: 3259 case Builtin::BI__sync_lock_release_4: 3260 case Builtin::BI__sync_lock_release_8: 3261 case Builtin::BI__sync_lock_release_16: 3262 BuiltinIndex = 15; 3263 NumFixed = 0; 3264 ResultType = Context.VoidTy; 3265 break; 3266 3267 case Builtin::BI__sync_swap: 3268 case Builtin::BI__sync_swap_1: 3269 case Builtin::BI__sync_swap_2: 3270 case Builtin::BI__sync_swap_4: 3271 case Builtin::BI__sync_swap_8: 3272 case Builtin::BI__sync_swap_16: 3273 BuiltinIndex = 16; 3274 break; 3275 } 3276 3277 // Now that we know how many fixed arguments we expect, first check that we 3278 // have at least that many. 3279 if (TheCall->getNumArgs() < 1+NumFixed) { 3280 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3281 << 0 << 1+NumFixed << TheCall->getNumArgs() 3282 << TheCall->getCallee()->getSourceRange(); 3283 return ExprError(); 3284 } 3285 3286 if (WarnAboutSemanticsChange) { 3287 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3288 << TheCall->getCallee()->getSourceRange(); 3289 } 3290 3291 // Get the decl for the concrete builtin from this, we can tell what the 3292 // concrete integer type we should convert to is. 3293 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3294 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3295 FunctionDecl *NewBuiltinDecl; 3296 if (NewBuiltinID == BuiltinID) 3297 NewBuiltinDecl = FDecl; 3298 else { 3299 // Perform builtin lookup to avoid redeclaring it. 3300 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3301 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3302 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3303 assert(Res.getFoundDecl()); 3304 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3305 if (!NewBuiltinDecl) 3306 return ExprError(); 3307 } 3308 3309 // The first argument --- the pointer --- has a fixed type; we 3310 // deduce the types of the rest of the arguments accordingly. Walk 3311 // the remaining arguments, converting them to the deduced value type. 3312 for (unsigned i = 0; i != NumFixed; ++i) { 3313 ExprResult Arg = TheCall->getArg(i+1); 3314 3315 // GCC does an implicit conversion to the pointer or integer ValType. This 3316 // can fail in some cases (1i -> int**), check for this error case now. 3317 // Initialize the argument. 3318 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3319 ValType, /*consume*/ false); 3320 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3321 if (Arg.isInvalid()) 3322 return ExprError(); 3323 3324 // Okay, we have something that *can* be converted to the right type. Check 3325 // to see if there is a potentially weird extension going on here. This can 3326 // happen when you do an atomic operation on something like an char* and 3327 // pass in 42. The 42 gets converted to char. This is even more strange 3328 // for things like 45.123 -> char, etc. 3329 // FIXME: Do this check. 3330 TheCall->setArg(i+1, Arg.get()); 3331 } 3332 3333 ASTContext& Context = this->getASTContext(); 3334 3335 // Create a new DeclRefExpr to refer to the new decl. 3336 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3337 Context, 3338 DRE->getQualifierLoc(), 3339 SourceLocation(), 3340 NewBuiltinDecl, 3341 /*enclosing*/ false, 3342 DRE->getLocation(), 3343 Context.BuiltinFnTy, 3344 DRE->getValueKind()); 3345 3346 // Set the callee in the CallExpr. 3347 // FIXME: This loses syntactic information. 3348 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3349 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3350 CK_BuiltinFnToFnPtr); 3351 TheCall->setCallee(PromotedCall.get()); 3352 3353 // Change the result type of the call to match the original value type. This 3354 // is arbitrary, but the codegen for these builtins ins design to handle it 3355 // gracefully. 3356 TheCall->setType(ResultType); 3357 3358 return TheCallResult; 3359 } 3360 3361 /// SemaBuiltinNontemporalOverloaded - We have a call to 3362 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3363 /// overloaded function based on the pointer type of its last argument. 3364 /// 3365 /// This function goes through and does final semantic checking for these 3366 /// builtins. 3367 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3368 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3369 DeclRefExpr *DRE = 3370 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3371 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3372 unsigned BuiltinID = FDecl->getBuiltinID(); 3373 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3374 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3375 "Unexpected nontemporal load/store builtin!"); 3376 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3377 unsigned numArgs = isStore ? 2 : 1; 3378 3379 // Ensure that we have the proper number of arguments. 3380 if (checkArgCount(*this, TheCall, numArgs)) 3381 return ExprError(); 3382 3383 // Inspect the last argument of the nontemporal builtin. This should always 3384 // be a pointer type, from which we imply the type of the memory access. 3385 // Because it is a pointer type, we don't have to worry about any implicit 3386 // casts here. 3387 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3388 ExprResult PointerArgResult = 3389 DefaultFunctionArrayLvalueConversion(PointerArg); 3390 3391 if (PointerArgResult.isInvalid()) 3392 return ExprError(); 3393 PointerArg = PointerArgResult.get(); 3394 TheCall->setArg(numArgs - 1, PointerArg); 3395 3396 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3397 if (!pointerType) { 3398 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3399 << PointerArg->getType() << PointerArg->getSourceRange(); 3400 return ExprError(); 3401 } 3402 3403 QualType ValType = pointerType->getPointeeType(); 3404 3405 // Strip any qualifiers off ValType. 3406 ValType = ValType.getUnqualifiedType(); 3407 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3408 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3409 !ValType->isVectorType()) { 3410 Diag(DRE->getLocStart(), 3411 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3412 << PointerArg->getType() << PointerArg->getSourceRange(); 3413 return ExprError(); 3414 } 3415 3416 if (!isStore) { 3417 TheCall->setType(ValType); 3418 return TheCallResult; 3419 } 3420 3421 ExprResult ValArg = TheCall->getArg(0); 3422 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3423 Context, ValType, /*consume*/ false); 3424 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3425 if (ValArg.isInvalid()) 3426 return ExprError(); 3427 3428 TheCall->setArg(0, ValArg.get()); 3429 TheCall->setType(Context.VoidTy); 3430 return TheCallResult; 3431 } 3432 3433 /// CheckObjCString - Checks that the argument to the builtin 3434 /// CFString constructor is correct 3435 /// Note: It might also make sense to do the UTF-16 conversion here (would 3436 /// simplify the backend). 3437 bool Sema::CheckObjCString(Expr *Arg) { 3438 Arg = Arg->IgnoreParenCasts(); 3439 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3440 3441 if (!Literal || !Literal->isAscii()) { 3442 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3443 << Arg->getSourceRange(); 3444 return true; 3445 } 3446 3447 if (Literal->containsNonAsciiOrNull()) { 3448 StringRef String = Literal->getString(); 3449 unsigned NumBytes = String.size(); 3450 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3451 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3452 llvm::UTF16 *ToPtr = &ToBuf[0]; 3453 3454 llvm::ConversionResult Result = 3455 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3456 ToPtr + NumBytes, llvm::strictConversion); 3457 // Check for conversion failure. 3458 if (Result != llvm::conversionOK) 3459 Diag(Arg->getLocStart(), 3460 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3461 } 3462 return false; 3463 } 3464 3465 /// CheckObjCString - Checks that the format string argument to the os_log() 3466 /// and os_trace() functions is correct, and converts it to const char *. 3467 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3468 Arg = Arg->IgnoreParenCasts(); 3469 auto *Literal = dyn_cast<StringLiteral>(Arg); 3470 if (!Literal) { 3471 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3472 Literal = ObjcLiteral->getString(); 3473 } 3474 } 3475 3476 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3477 return ExprError( 3478 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3479 << Arg->getSourceRange()); 3480 } 3481 3482 ExprResult Result(Literal); 3483 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3484 InitializedEntity Entity = 3485 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3486 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3487 return Result; 3488 } 3489 3490 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3491 /// for validity. Emit an error and return true on failure; return false 3492 /// on success. 3493 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) { 3494 Expr *Fn = TheCall->getCallee(); 3495 if (TheCall->getNumArgs() > 2) { 3496 Diag(TheCall->getArg(2)->getLocStart(), 3497 diag::err_typecheck_call_too_many_args) 3498 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3499 << Fn->getSourceRange() 3500 << SourceRange(TheCall->getArg(2)->getLocStart(), 3501 (*(TheCall->arg_end()-1))->getLocEnd()); 3502 return true; 3503 } 3504 3505 if (TheCall->getNumArgs() < 2) { 3506 return Diag(TheCall->getLocEnd(), 3507 diag::err_typecheck_call_too_few_args_at_least) 3508 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3509 } 3510 3511 // Type-check the first argument normally. 3512 if (checkBuiltinArgument(*this, TheCall, 0)) 3513 return true; 3514 3515 // Determine whether the current function is variadic or not. 3516 BlockScopeInfo *CurBlock = getCurBlock(); 3517 bool isVariadic; 3518 if (CurBlock) 3519 isVariadic = CurBlock->TheDecl->isVariadic(); 3520 else if (FunctionDecl *FD = getCurFunctionDecl()) 3521 isVariadic = FD->isVariadic(); 3522 else 3523 isVariadic = getCurMethodDecl()->isVariadic(); 3524 3525 if (!isVariadic) { 3526 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3527 return true; 3528 } 3529 3530 // Verify that the second argument to the builtin is the last argument of the 3531 // current function or method. 3532 bool SecondArgIsLastNamedArgument = false; 3533 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3534 3535 // These are valid if SecondArgIsLastNamedArgument is false after the next 3536 // block. 3537 QualType Type; 3538 SourceLocation ParamLoc; 3539 bool IsCRegister = false; 3540 3541 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3542 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3543 // FIXME: This isn't correct for methods (results in bogus warning). 3544 // Get the last formal in the current function. 3545 const ParmVarDecl *LastArg; 3546 if (CurBlock) 3547 LastArg = CurBlock->TheDecl->parameters().back(); 3548 else if (FunctionDecl *FD = getCurFunctionDecl()) 3549 LastArg = FD->parameters().back(); 3550 else 3551 LastArg = getCurMethodDecl()->parameters().back(); 3552 SecondArgIsLastNamedArgument = PV == LastArg; 3553 3554 Type = PV->getType(); 3555 ParamLoc = PV->getLocation(); 3556 IsCRegister = 3557 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3558 } 3559 } 3560 3561 if (!SecondArgIsLastNamedArgument) 3562 Diag(TheCall->getArg(1)->getLocStart(), 3563 diag::warn_second_arg_of_va_start_not_last_named_param); 3564 else if (IsCRegister || Type->isReferenceType() || 3565 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3566 // Promotable integers are UB, but enumerations need a bit of 3567 // extra checking to see what their promotable type actually is. 3568 if (!Type->isPromotableIntegerType()) 3569 return false; 3570 if (!Type->isEnumeralType()) 3571 return true; 3572 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3573 return !(ED && 3574 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3575 }()) { 3576 unsigned Reason = 0; 3577 if (Type->isReferenceType()) Reason = 1; 3578 else if (IsCRegister) Reason = 2; 3579 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3580 Diag(ParamLoc, diag::note_parameter_type) << Type; 3581 } 3582 3583 TheCall->setType(Context.VoidTy); 3584 return false; 3585 } 3586 3587 /// Check the arguments to '__builtin_va_start' for validity, and that 3588 /// it was called from a function of the native ABI. 3589 /// Emit an error and return true on failure; return false on success. 3590 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 3591 // On x86-64 Unix, don't allow this in Win64 ABI functions. 3592 // On x64 Windows, don't allow this in System V ABI functions. 3593 // (Yes, that means there's no corresponding way to support variadic 3594 // System V ABI functions on Windows.) 3595 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) { 3596 unsigned OS = Context.getTargetInfo().getTriple().getOS(); 3597 clang::CallingConv CC = CC_C; 3598 if (const FunctionDecl *FD = getCurFunctionDecl()) 3599 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3600 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) || 3601 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64)) 3602 return Diag(TheCall->getCallee()->getLocStart(), 3603 diag::err_va_start_used_in_wrong_abi_function) 3604 << (OS != llvm::Triple::Win32); 3605 } 3606 return SemaBuiltinVAStartImpl(TheCall); 3607 } 3608 3609 /// Check the arguments to '__builtin_ms_va_start' for validity, and that 3610 /// it was called from a Win64 ABI function. 3611 /// Emit an error and return true on failure; return false on success. 3612 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) { 3613 // This only makes sense for x86-64. 3614 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3615 Expr *Callee = TheCall->getCallee(); 3616 if (TT.getArch() != llvm::Triple::x86_64) 3617 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt); 3618 // Don't allow this in System V ABI functions. 3619 clang::CallingConv CC = CC_C; 3620 if (const FunctionDecl *FD = getCurFunctionDecl()) 3621 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3622 if (CC == CC_X86_64SysV || 3623 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64)) 3624 return Diag(Callee->getLocStart(), 3625 diag::err_ms_va_start_used_in_sysv_function); 3626 return SemaBuiltinVAStartImpl(TheCall); 3627 } 3628 3629 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3630 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3631 // const char *named_addr); 3632 3633 Expr *Func = Call->getCallee(); 3634 3635 if (Call->getNumArgs() < 3) 3636 return Diag(Call->getLocEnd(), 3637 diag::err_typecheck_call_too_few_args_at_least) 3638 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3639 3640 // Determine whether the current function is variadic or not. 3641 bool IsVariadic; 3642 if (BlockScopeInfo *CurBlock = getCurBlock()) 3643 IsVariadic = CurBlock->TheDecl->isVariadic(); 3644 else if (FunctionDecl *FD = getCurFunctionDecl()) 3645 IsVariadic = FD->isVariadic(); 3646 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 3647 IsVariadic = MD->isVariadic(); 3648 else 3649 llvm_unreachable("unexpected statement type"); 3650 3651 if (!IsVariadic) { 3652 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3653 return true; 3654 } 3655 3656 // Type-check the first argument normally. 3657 if (checkBuiltinArgument(*this, Call, 0)) 3658 return true; 3659 3660 const struct { 3661 unsigned ArgNo; 3662 QualType Type; 3663 } ArgumentTypes[] = { 3664 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3665 { 2, Context.getSizeType() }, 3666 }; 3667 3668 for (const auto &AT : ArgumentTypes) { 3669 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3670 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3671 continue; 3672 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3673 << Arg->getType() << AT.Type << 1 /* different class */ 3674 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3675 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3676 } 3677 3678 return false; 3679 } 3680 3681 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3682 /// friends. This is declared to take (...), so we have to check everything. 3683 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3684 if (TheCall->getNumArgs() < 2) 3685 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3686 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3687 if (TheCall->getNumArgs() > 2) 3688 return Diag(TheCall->getArg(2)->getLocStart(), 3689 diag::err_typecheck_call_too_many_args) 3690 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3691 << SourceRange(TheCall->getArg(2)->getLocStart(), 3692 (*(TheCall->arg_end()-1))->getLocEnd()); 3693 3694 ExprResult OrigArg0 = TheCall->getArg(0); 3695 ExprResult OrigArg1 = TheCall->getArg(1); 3696 3697 // Do standard promotions between the two arguments, returning their common 3698 // type. 3699 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3700 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3701 return true; 3702 3703 // Make sure any conversions are pushed back into the call; this is 3704 // type safe since unordered compare builtins are declared as "_Bool 3705 // foo(...)". 3706 TheCall->setArg(0, OrigArg0.get()); 3707 TheCall->setArg(1, OrigArg1.get()); 3708 3709 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3710 return false; 3711 3712 // If the common type isn't a real floating type, then the arguments were 3713 // invalid for this operation. 3714 if (Res.isNull() || !Res->isRealFloatingType()) 3715 return Diag(OrigArg0.get()->getLocStart(), 3716 diag::err_typecheck_call_invalid_ordered_compare) 3717 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3718 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3719 3720 return false; 3721 } 3722 3723 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3724 /// __builtin_isnan and friends. This is declared to take (...), so we have 3725 /// to check everything. We expect the last argument to be a floating point 3726 /// value. 3727 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3728 if (TheCall->getNumArgs() < NumArgs) 3729 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3730 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3731 if (TheCall->getNumArgs() > NumArgs) 3732 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3733 diag::err_typecheck_call_too_many_args) 3734 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3735 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3736 (*(TheCall->arg_end()-1))->getLocEnd()); 3737 3738 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3739 3740 if (OrigArg->isTypeDependent()) 3741 return false; 3742 3743 // This operation requires a non-_Complex floating-point number. 3744 if (!OrigArg->getType()->isRealFloatingType()) 3745 return Diag(OrigArg->getLocStart(), 3746 diag::err_typecheck_call_invalid_unary_fp) 3747 << OrigArg->getType() << OrigArg->getSourceRange(); 3748 3749 // If this is an implicit conversion from float -> double, remove it. 3750 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 3751 Expr *CastArg = Cast->getSubExpr(); 3752 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 3753 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 3754 "promotion from float to double is the only expected cast here"); 3755 Cast->setSubExpr(nullptr); 3756 TheCall->setArg(NumArgs-1, CastArg); 3757 } 3758 } 3759 3760 return false; 3761 } 3762 3763 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 3764 // This is declared to take (...), so we have to check everything. 3765 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 3766 if (TheCall->getNumArgs() < 2) 3767 return ExprError(Diag(TheCall->getLocEnd(), 3768 diag::err_typecheck_call_too_few_args_at_least) 3769 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3770 << TheCall->getSourceRange()); 3771 3772 // Determine which of the following types of shufflevector we're checking: 3773 // 1) unary, vector mask: (lhs, mask) 3774 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 3775 QualType resType = TheCall->getArg(0)->getType(); 3776 unsigned numElements = 0; 3777 3778 if (!TheCall->getArg(0)->isTypeDependent() && 3779 !TheCall->getArg(1)->isTypeDependent()) { 3780 QualType LHSType = TheCall->getArg(0)->getType(); 3781 QualType RHSType = TheCall->getArg(1)->getType(); 3782 3783 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 3784 return ExprError(Diag(TheCall->getLocStart(), 3785 diag::err_shufflevector_non_vector) 3786 << SourceRange(TheCall->getArg(0)->getLocStart(), 3787 TheCall->getArg(1)->getLocEnd())); 3788 3789 numElements = LHSType->getAs<VectorType>()->getNumElements(); 3790 unsigned numResElements = TheCall->getNumArgs() - 2; 3791 3792 // Check to see if we have a call with 2 vector arguments, the unary shuffle 3793 // with mask. If so, verify that RHS is an integer vector type with the 3794 // same number of elts as lhs. 3795 if (TheCall->getNumArgs() == 2) { 3796 if (!RHSType->hasIntegerRepresentation() || 3797 RHSType->getAs<VectorType>()->getNumElements() != numElements) 3798 return ExprError(Diag(TheCall->getLocStart(), 3799 diag::err_shufflevector_incompatible_vector) 3800 << SourceRange(TheCall->getArg(1)->getLocStart(), 3801 TheCall->getArg(1)->getLocEnd())); 3802 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 3803 return ExprError(Diag(TheCall->getLocStart(), 3804 diag::err_shufflevector_incompatible_vector) 3805 << SourceRange(TheCall->getArg(0)->getLocStart(), 3806 TheCall->getArg(1)->getLocEnd())); 3807 } else if (numElements != numResElements) { 3808 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 3809 resType = Context.getVectorType(eltType, numResElements, 3810 VectorType::GenericVector); 3811 } 3812 } 3813 3814 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 3815 if (TheCall->getArg(i)->isTypeDependent() || 3816 TheCall->getArg(i)->isValueDependent()) 3817 continue; 3818 3819 llvm::APSInt Result(32); 3820 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 3821 return ExprError(Diag(TheCall->getLocStart(), 3822 diag::err_shufflevector_nonconstant_argument) 3823 << TheCall->getArg(i)->getSourceRange()); 3824 3825 // Allow -1 which will be translated to undef in the IR. 3826 if (Result.isSigned() && Result.isAllOnesValue()) 3827 continue; 3828 3829 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 3830 return ExprError(Diag(TheCall->getLocStart(), 3831 diag::err_shufflevector_argument_too_large) 3832 << TheCall->getArg(i)->getSourceRange()); 3833 } 3834 3835 SmallVector<Expr*, 32> exprs; 3836 3837 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 3838 exprs.push_back(TheCall->getArg(i)); 3839 TheCall->setArg(i, nullptr); 3840 } 3841 3842 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 3843 TheCall->getCallee()->getLocStart(), 3844 TheCall->getRParenLoc()); 3845 } 3846 3847 /// SemaConvertVectorExpr - Handle __builtin_convertvector 3848 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 3849 SourceLocation BuiltinLoc, 3850 SourceLocation RParenLoc) { 3851 ExprValueKind VK = VK_RValue; 3852 ExprObjectKind OK = OK_Ordinary; 3853 QualType DstTy = TInfo->getType(); 3854 QualType SrcTy = E->getType(); 3855 3856 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 3857 return ExprError(Diag(BuiltinLoc, 3858 diag::err_convertvector_non_vector) 3859 << E->getSourceRange()); 3860 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 3861 return ExprError(Diag(BuiltinLoc, 3862 diag::err_convertvector_non_vector_type)); 3863 3864 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 3865 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 3866 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 3867 if (SrcElts != DstElts) 3868 return ExprError(Diag(BuiltinLoc, 3869 diag::err_convertvector_incompatible_vector) 3870 << E->getSourceRange()); 3871 } 3872 3873 return new (Context) 3874 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 3875 } 3876 3877 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 3878 // This is declared to take (const void*, ...) and can take two 3879 // optional constant int args. 3880 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 3881 unsigned NumArgs = TheCall->getNumArgs(); 3882 3883 if (NumArgs > 3) 3884 return Diag(TheCall->getLocEnd(), 3885 diag::err_typecheck_call_too_many_args_at_most) 3886 << 0 /*function call*/ << 3 << NumArgs 3887 << TheCall->getSourceRange(); 3888 3889 // Argument 0 is checked for us and the remaining arguments must be 3890 // constant integers. 3891 for (unsigned i = 1; i != NumArgs; ++i) 3892 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 3893 return true; 3894 3895 return false; 3896 } 3897 3898 /// SemaBuiltinAssume - Handle __assume (MS Extension). 3899 // __assume does not evaluate its arguments, and should warn if its argument 3900 // has side effects. 3901 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 3902 Expr *Arg = TheCall->getArg(0); 3903 if (Arg->isInstantiationDependent()) return false; 3904 3905 if (Arg->HasSideEffects(Context)) 3906 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 3907 << Arg->getSourceRange() 3908 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 3909 3910 return false; 3911 } 3912 3913 /// Handle __builtin_alloca_with_align. This is declared 3914 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 3915 /// than 8. 3916 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 3917 // The alignment must be a constant integer. 3918 Expr *Arg = TheCall->getArg(1); 3919 3920 // We can't check the value of a dependent argument. 3921 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 3922 if (const auto *UE = 3923 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 3924 if (UE->getKind() == UETT_AlignOf) 3925 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 3926 << Arg->getSourceRange(); 3927 3928 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 3929 3930 if (!Result.isPowerOf2()) 3931 return Diag(TheCall->getLocStart(), 3932 diag::err_alignment_not_power_of_two) 3933 << Arg->getSourceRange(); 3934 3935 if (Result < Context.getCharWidth()) 3936 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 3937 << (unsigned)Context.getCharWidth() 3938 << Arg->getSourceRange(); 3939 3940 if (Result > INT32_MAX) 3941 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 3942 << INT32_MAX 3943 << Arg->getSourceRange(); 3944 } 3945 3946 return false; 3947 } 3948 3949 /// Handle __builtin_assume_aligned. This is declared 3950 /// as (const void*, size_t, ...) and can take one optional constant int arg. 3951 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 3952 unsigned NumArgs = TheCall->getNumArgs(); 3953 3954 if (NumArgs > 3) 3955 return Diag(TheCall->getLocEnd(), 3956 diag::err_typecheck_call_too_many_args_at_most) 3957 << 0 /*function call*/ << 3 << NumArgs 3958 << TheCall->getSourceRange(); 3959 3960 // The alignment must be a constant integer. 3961 Expr *Arg = TheCall->getArg(1); 3962 3963 // We can't check the value of a dependent argument. 3964 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 3965 llvm::APSInt Result; 3966 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 3967 return true; 3968 3969 if (!Result.isPowerOf2()) 3970 return Diag(TheCall->getLocStart(), 3971 diag::err_alignment_not_power_of_two) 3972 << Arg->getSourceRange(); 3973 } 3974 3975 if (NumArgs > 2) { 3976 ExprResult Arg(TheCall->getArg(2)); 3977 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3978 Context.getSizeType(), false); 3979 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3980 if (Arg.isInvalid()) return true; 3981 TheCall->setArg(2, Arg.get()); 3982 } 3983 3984 return false; 3985 } 3986 3987 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 3988 unsigned BuiltinID = 3989 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 3990 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 3991 3992 unsigned NumArgs = TheCall->getNumArgs(); 3993 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 3994 if (NumArgs < NumRequiredArgs) { 3995 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3996 << 0 /* function call */ << NumRequiredArgs << NumArgs 3997 << TheCall->getSourceRange(); 3998 } 3999 if (NumArgs >= NumRequiredArgs + 0x100) { 4000 return Diag(TheCall->getLocEnd(), 4001 diag::err_typecheck_call_too_many_args_at_most) 4002 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4003 << TheCall->getSourceRange(); 4004 } 4005 unsigned i = 0; 4006 4007 // For formatting call, check buffer arg. 4008 if (!IsSizeCall) { 4009 ExprResult Arg(TheCall->getArg(i)); 4010 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4011 Context, Context.VoidPtrTy, false); 4012 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4013 if (Arg.isInvalid()) 4014 return true; 4015 TheCall->setArg(i, Arg.get()); 4016 i++; 4017 } 4018 4019 // Check string literal arg. 4020 unsigned FormatIdx = i; 4021 { 4022 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4023 if (Arg.isInvalid()) 4024 return true; 4025 TheCall->setArg(i, Arg.get()); 4026 i++; 4027 } 4028 4029 // Make sure variadic args are scalar. 4030 unsigned FirstDataArg = i; 4031 while (i < NumArgs) { 4032 ExprResult Arg = DefaultVariadicArgumentPromotion( 4033 TheCall->getArg(i), VariadicFunction, nullptr); 4034 if (Arg.isInvalid()) 4035 return true; 4036 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4037 if (ArgSize.getQuantity() >= 0x100) { 4038 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4039 << i << (int)ArgSize.getQuantity() << 0xff 4040 << TheCall->getSourceRange(); 4041 } 4042 TheCall->setArg(i, Arg.get()); 4043 i++; 4044 } 4045 4046 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4047 // call to avoid duplicate diagnostics. 4048 if (!IsSizeCall) { 4049 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4050 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4051 bool Success = CheckFormatArguments( 4052 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4053 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4054 CheckedVarArgs); 4055 if (!Success) 4056 return true; 4057 } 4058 4059 if (IsSizeCall) { 4060 TheCall->setType(Context.getSizeType()); 4061 } else { 4062 TheCall->setType(Context.VoidPtrTy); 4063 } 4064 return false; 4065 } 4066 4067 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4068 /// TheCall is a constant expression. 4069 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4070 llvm::APSInt &Result) { 4071 Expr *Arg = TheCall->getArg(ArgNum); 4072 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4073 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4074 4075 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4076 4077 if (!Arg->isIntegerConstantExpr(Result, Context)) 4078 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4079 << FDecl->getDeclName() << Arg->getSourceRange(); 4080 4081 return false; 4082 } 4083 4084 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4085 /// TheCall is a constant expression in the range [Low, High]. 4086 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4087 int Low, int High) { 4088 llvm::APSInt Result; 4089 4090 // We can't check the value of a dependent argument. 4091 Expr *Arg = TheCall->getArg(ArgNum); 4092 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4093 return false; 4094 4095 // Check constant-ness first. 4096 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4097 return true; 4098 4099 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4100 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4101 << Low << High << Arg->getSourceRange(); 4102 4103 return false; 4104 } 4105 4106 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4107 /// TheCall is a constant expression is a multiple of Num.. 4108 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4109 unsigned Num) { 4110 llvm::APSInt Result; 4111 4112 // We can't check the value of a dependent argument. 4113 Expr *Arg = TheCall->getArg(ArgNum); 4114 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4115 return false; 4116 4117 // Check constant-ness first. 4118 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4119 return true; 4120 4121 if (Result.getSExtValue() % Num != 0) 4122 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4123 << Num << Arg->getSourceRange(); 4124 4125 return false; 4126 } 4127 4128 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4129 /// TheCall is an ARM/AArch64 special register string literal. 4130 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4131 int ArgNum, unsigned ExpectedFieldNum, 4132 bool AllowName) { 4133 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4134 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4135 BuiltinID == ARM::BI__builtin_arm_rsr || 4136 BuiltinID == ARM::BI__builtin_arm_rsrp || 4137 BuiltinID == ARM::BI__builtin_arm_wsr || 4138 BuiltinID == ARM::BI__builtin_arm_wsrp; 4139 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4140 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4141 BuiltinID == AArch64::BI__builtin_arm_rsr || 4142 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4143 BuiltinID == AArch64::BI__builtin_arm_wsr || 4144 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4145 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4146 4147 // We can't check the value of a dependent argument. 4148 Expr *Arg = TheCall->getArg(ArgNum); 4149 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4150 return false; 4151 4152 // Check if the argument is a string literal. 4153 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4154 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4155 << Arg->getSourceRange(); 4156 4157 // Check the type of special register given. 4158 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4159 SmallVector<StringRef, 6> Fields; 4160 Reg.split(Fields, ":"); 4161 4162 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4163 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4164 << Arg->getSourceRange(); 4165 4166 // If the string is the name of a register then we cannot check that it is 4167 // valid here but if the string is of one the forms described in ACLE then we 4168 // can check that the supplied fields are integers and within the valid 4169 // ranges. 4170 if (Fields.size() > 1) { 4171 bool FiveFields = Fields.size() == 5; 4172 4173 bool ValidString = true; 4174 if (IsARMBuiltin) { 4175 ValidString &= Fields[0].startswith_lower("cp") || 4176 Fields[0].startswith_lower("p"); 4177 if (ValidString) 4178 Fields[0] = 4179 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4180 4181 ValidString &= Fields[2].startswith_lower("c"); 4182 if (ValidString) 4183 Fields[2] = Fields[2].drop_front(1); 4184 4185 if (FiveFields) { 4186 ValidString &= Fields[3].startswith_lower("c"); 4187 if (ValidString) 4188 Fields[3] = Fields[3].drop_front(1); 4189 } 4190 } 4191 4192 SmallVector<int, 5> Ranges; 4193 if (FiveFields) 4194 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4195 else 4196 Ranges.append({15, 7, 15}); 4197 4198 for (unsigned i=0; i<Fields.size(); ++i) { 4199 int IntField; 4200 ValidString &= !Fields[i].getAsInteger(10, IntField); 4201 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4202 } 4203 4204 if (!ValidString) 4205 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4206 << Arg->getSourceRange(); 4207 4208 } else if (IsAArch64Builtin && Fields.size() == 1) { 4209 // If the register name is one of those that appear in the condition below 4210 // and the special register builtin being used is one of the write builtins, 4211 // then we require that the argument provided for writing to the register 4212 // is an integer constant expression. This is because it will be lowered to 4213 // an MSR (immediate) instruction, so we need to know the immediate at 4214 // compile time. 4215 if (TheCall->getNumArgs() != 2) 4216 return false; 4217 4218 std::string RegLower = Reg.lower(); 4219 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4220 RegLower != "pan" && RegLower != "uao") 4221 return false; 4222 4223 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4224 } 4225 4226 return false; 4227 } 4228 4229 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4230 /// This checks that the target supports __builtin_longjmp and 4231 /// that val is a constant 1. 4232 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4233 if (!Context.getTargetInfo().hasSjLjLowering()) 4234 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4235 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4236 4237 Expr *Arg = TheCall->getArg(1); 4238 llvm::APSInt Result; 4239 4240 // TODO: This is less than ideal. Overload this to take a value. 4241 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4242 return true; 4243 4244 if (Result != 1) 4245 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4246 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4247 4248 return false; 4249 } 4250 4251 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4252 /// This checks that the target supports __builtin_setjmp. 4253 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4254 if (!Context.getTargetInfo().hasSjLjLowering()) 4255 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4256 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4257 return false; 4258 } 4259 4260 namespace { 4261 class UncoveredArgHandler { 4262 enum { Unknown = -1, AllCovered = -2 }; 4263 signed FirstUncoveredArg; 4264 SmallVector<const Expr *, 4> DiagnosticExprs; 4265 4266 public: 4267 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4268 4269 bool hasUncoveredArg() const { 4270 return (FirstUncoveredArg >= 0); 4271 } 4272 4273 unsigned getUncoveredArg() const { 4274 assert(hasUncoveredArg() && "no uncovered argument"); 4275 return FirstUncoveredArg; 4276 } 4277 4278 void setAllCovered() { 4279 // A string has been found with all arguments covered, so clear out 4280 // the diagnostics. 4281 DiagnosticExprs.clear(); 4282 FirstUncoveredArg = AllCovered; 4283 } 4284 4285 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4286 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4287 4288 // Don't update if a previous string covers all arguments. 4289 if (FirstUncoveredArg == AllCovered) 4290 return; 4291 4292 // UncoveredArgHandler tracks the highest uncovered argument index 4293 // and with it all the strings that match this index. 4294 if (NewFirstUncoveredArg == FirstUncoveredArg) 4295 DiagnosticExprs.push_back(StrExpr); 4296 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4297 DiagnosticExprs.clear(); 4298 DiagnosticExprs.push_back(StrExpr); 4299 FirstUncoveredArg = NewFirstUncoveredArg; 4300 } 4301 } 4302 4303 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4304 }; 4305 4306 enum StringLiteralCheckType { 4307 SLCT_NotALiteral, 4308 SLCT_UncheckedLiteral, 4309 SLCT_CheckedLiteral 4310 }; 4311 } // end anonymous namespace 4312 4313 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4314 BinaryOperatorKind BinOpKind, 4315 bool AddendIsRight) { 4316 unsigned BitWidth = Offset.getBitWidth(); 4317 unsigned AddendBitWidth = Addend.getBitWidth(); 4318 // There might be negative interim results. 4319 if (Addend.isUnsigned()) { 4320 Addend = Addend.zext(++AddendBitWidth); 4321 Addend.setIsSigned(true); 4322 } 4323 // Adjust the bit width of the APSInts. 4324 if (AddendBitWidth > BitWidth) { 4325 Offset = Offset.sext(AddendBitWidth); 4326 BitWidth = AddendBitWidth; 4327 } else if (BitWidth > AddendBitWidth) { 4328 Addend = Addend.sext(BitWidth); 4329 } 4330 4331 bool Ov = false; 4332 llvm::APSInt ResOffset = Offset; 4333 if (BinOpKind == BO_Add) 4334 ResOffset = Offset.sadd_ov(Addend, Ov); 4335 else { 4336 assert(AddendIsRight && BinOpKind == BO_Sub && 4337 "operator must be add or sub with addend on the right"); 4338 ResOffset = Offset.ssub_ov(Addend, Ov); 4339 } 4340 4341 // We add an offset to a pointer here so we should support an offset as big as 4342 // possible. 4343 if (Ov) { 4344 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4345 Offset = Offset.sext(2 * BitWidth); 4346 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4347 return; 4348 } 4349 4350 Offset = ResOffset; 4351 } 4352 4353 namespace { 4354 // This is a wrapper class around StringLiteral to support offsetted string 4355 // literals as format strings. It takes the offset into account when returning 4356 // the string and its length or the source locations to display notes correctly. 4357 class FormatStringLiteral { 4358 const StringLiteral *FExpr; 4359 int64_t Offset; 4360 4361 public: 4362 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4363 : FExpr(fexpr), Offset(Offset) {} 4364 4365 StringRef getString() const { 4366 return FExpr->getString().drop_front(Offset); 4367 } 4368 4369 unsigned getByteLength() const { 4370 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4371 } 4372 unsigned getLength() const { return FExpr->getLength() - Offset; } 4373 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4374 4375 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4376 4377 QualType getType() const { return FExpr->getType(); } 4378 4379 bool isAscii() const { return FExpr->isAscii(); } 4380 bool isWide() const { return FExpr->isWide(); } 4381 bool isUTF8() const { return FExpr->isUTF8(); } 4382 bool isUTF16() const { return FExpr->isUTF16(); } 4383 bool isUTF32() const { return FExpr->isUTF32(); } 4384 bool isPascal() const { return FExpr->isPascal(); } 4385 4386 SourceLocation getLocationOfByte( 4387 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4388 const TargetInfo &Target, unsigned *StartToken = nullptr, 4389 unsigned *StartTokenByteOffset = nullptr) const { 4390 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4391 StartToken, StartTokenByteOffset); 4392 } 4393 4394 SourceLocation getLocStart() const LLVM_READONLY { 4395 return FExpr->getLocStart().getLocWithOffset(Offset); 4396 } 4397 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4398 }; 4399 } // end anonymous namespace 4400 4401 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4402 const Expr *OrigFormatExpr, 4403 ArrayRef<const Expr *> Args, 4404 bool HasVAListArg, unsigned format_idx, 4405 unsigned firstDataArg, 4406 Sema::FormatStringType Type, 4407 bool inFunctionCall, 4408 Sema::VariadicCallType CallType, 4409 llvm::SmallBitVector &CheckedVarArgs, 4410 UncoveredArgHandler &UncoveredArg); 4411 4412 // Determine if an expression is a string literal or constant string. 4413 // If this function returns false on the arguments to a function expecting a 4414 // format string, we will usually need to emit a warning. 4415 // True string literals are then checked by CheckFormatString. 4416 static StringLiteralCheckType 4417 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4418 bool HasVAListArg, unsigned format_idx, 4419 unsigned firstDataArg, Sema::FormatStringType Type, 4420 Sema::VariadicCallType CallType, bool InFunctionCall, 4421 llvm::SmallBitVector &CheckedVarArgs, 4422 UncoveredArgHandler &UncoveredArg, 4423 llvm::APSInt Offset) { 4424 tryAgain: 4425 assert(Offset.isSigned() && "invalid offset"); 4426 4427 if (E->isTypeDependent() || E->isValueDependent()) 4428 return SLCT_NotALiteral; 4429 4430 E = E->IgnoreParenCasts(); 4431 4432 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4433 // Technically -Wformat-nonliteral does not warn about this case. 4434 // The behavior of printf and friends in this case is implementation 4435 // dependent. Ideally if the format string cannot be null then 4436 // it should have a 'nonnull' attribute in the function prototype. 4437 return SLCT_UncheckedLiteral; 4438 4439 switch (E->getStmtClass()) { 4440 case Stmt::BinaryConditionalOperatorClass: 4441 case Stmt::ConditionalOperatorClass: { 4442 // The expression is a literal if both sub-expressions were, and it was 4443 // completely checked only if both sub-expressions were checked. 4444 const AbstractConditionalOperator *C = 4445 cast<AbstractConditionalOperator>(E); 4446 4447 // Determine whether it is necessary to check both sub-expressions, for 4448 // example, because the condition expression is a constant that can be 4449 // evaluated at compile time. 4450 bool CheckLeft = true, CheckRight = true; 4451 4452 bool Cond; 4453 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4454 if (Cond) 4455 CheckRight = false; 4456 else 4457 CheckLeft = false; 4458 } 4459 4460 // We need to maintain the offsets for the right and the left hand side 4461 // separately to check if every possible indexed expression is a valid 4462 // string literal. They might have different offsets for different string 4463 // literals in the end. 4464 StringLiteralCheckType Left; 4465 if (!CheckLeft) 4466 Left = SLCT_UncheckedLiteral; 4467 else { 4468 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4469 HasVAListArg, format_idx, firstDataArg, 4470 Type, CallType, InFunctionCall, 4471 CheckedVarArgs, UncoveredArg, Offset); 4472 if (Left == SLCT_NotALiteral || !CheckRight) { 4473 return Left; 4474 } 4475 } 4476 4477 StringLiteralCheckType Right = 4478 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4479 HasVAListArg, format_idx, firstDataArg, 4480 Type, CallType, InFunctionCall, CheckedVarArgs, 4481 UncoveredArg, Offset); 4482 4483 return (CheckLeft && Left < Right) ? Left : Right; 4484 } 4485 4486 case Stmt::ImplicitCastExprClass: { 4487 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4488 goto tryAgain; 4489 } 4490 4491 case Stmt::OpaqueValueExprClass: 4492 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4493 E = src; 4494 goto tryAgain; 4495 } 4496 return SLCT_NotALiteral; 4497 4498 case Stmt::PredefinedExprClass: 4499 // While __func__, etc., are technically not string literals, they 4500 // cannot contain format specifiers and thus are not a security 4501 // liability. 4502 return SLCT_UncheckedLiteral; 4503 4504 case Stmt::DeclRefExprClass: { 4505 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4506 4507 // As an exception, do not flag errors for variables binding to 4508 // const string literals. 4509 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4510 bool isConstant = false; 4511 QualType T = DR->getType(); 4512 4513 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4514 isConstant = AT->getElementType().isConstant(S.Context); 4515 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4516 isConstant = T.isConstant(S.Context) && 4517 PT->getPointeeType().isConstant(S.Context); 4518 } else if (T->isObjCObjectPointerType()) { 4519 // In ObjC, there is usually no "const ObjectPointer" type, 4520 // so don't check if the pointee type is constant. 4521 isConstant = T.isConstant(S.Context); 4522 } 4523 4524 if (isConstant) { 4525 if (const Expr *Init = VD->getAnyInitializer()) { 4526 // Look through initializers like const char c[] = { "foo" } 4527 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4528 if (InitList->isStringLiteralInit()) 4529 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4530 } 4531 return checkFormatStringExpr(S, Init, Args, 4532 HasVAListArg, format_idx, 4533 firstDataArg, Type, CallType, 4534 /*InFunctionCall*/ false, CheckedVarArgs, 4535 UncoveredArg, Offset); 4536 } 4537 } 4538 4539 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4540 // special check to see if the format string is a function parameter 4541 // of the function calling the printf function. If the function 4542 // has an attribute indicating it is a printf-like function, then we 4543 // should suppress warnings concerning non-literals being used in a call 4544 // to a vprintf function. For example: 4545 // 4546 // void 4547 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4548 // va_list ap; 4549 // va_start(ap, fmt); 4550 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4551 // ... 4552 // } 4553 if (HasVAListArg) { 4554 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4555 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4556 int PVIndex = PV->getFunctionScopeIndex() + 1; 4557 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4558 // adjust for implicit parameter 4559 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4560 if (MD->isInstance()) 4561 ++PVIndex; 4562 // We also check if the formats are compatible. 4563 // We can't pass a 'scanf' string to a 'printf' function. 4564 if (PVIndex == PVFormat->getFormatIdx() && 4565 Type == S.GetFormatStringType(PVFormat)) 4566 return SLCT_UncheckedLiteral; 4567 } 4568 } 4569 } 4570 } 4571 } 4572 4573 return SLCT_NotALiteral; 4574 } 4575 4576 case Stmt::CallExprClass: 4577 case Stmt::CXXMemberCallExprClass: { 4578 const CallExpr *CE = cast<CallExpr>(E); 4579 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4580 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4581 unsigned ArgIndex = FA->getFormatIdx(); 4582 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4583 if (MD->isInstance()) 4584 --ArgIndex; 4585 const Expr *Arg = CE->getArg(ArgIndex - 1); 4586 4587 return checkFormatStringExpr(S, Arg, Args, 4588 HasVAListArg, format_idx, firstDataArg, 4589 Type, CallType, InFunctionCall, 4590 CheckedVarArgs, UncoveredArg, Offset); 4591 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4592 unsigned BuiltinID = FD->getBuiltinID(); 4593 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4594 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4595 const Expr *Arg = CE->getArg(0); 4596 return checkFormatStringExpr(S, Arg, Args, 4597 HasVAListArg, format_idx, 4598 firstDataArg, Type, CallType, 4599 InFunctionCall, CheckedVarArgs, 4600 UncoveredArg, Offset); 4601 } 4602 } 4603 } 4604 4605 return SLCT_NotALiteral; 4606 } 4607 case Stmt::ObjCMessageExprClass: { 4608 const auto *ME = cast<ObjCMessageExpr>(E); 4609 if (const auto *ND = ME->getMethodDecl()) { 4610 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4611 unsigned ArgIndex = FA->getFormatIdx(); 4612 const Expr *Arg = ME->getArg(ArgIndex - 1); 4613 return checkFormatStringExpr( 4614 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4615 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4616 } 4617 } 4618 4619 return SLCT_NotALiteral; 4620 } 4621 case Stmt::ObjCStringLiteralClass: 4622 case Stmt::StringLiteralClass: { 4623 const StringLiteral *StrE = nullptr; 4624 4625 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4626 StrE = ObjCFExpr->getString(); 4627 else 4628 StrE = cast<StringLiteral>(E); 4629 4630 if (StrE) { 4631 if (Offset.isNegative() || Offset > StrE->getLength()) { 4632 // TODO: It would be better to have an explicit warning for out of 4633 // bounds literals. 4634 return SLCT_NotALiteral; 4635 } 4636 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4637 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4638 firstDataArg, Type, InFunctionCall, CallType, 4639 CheckedVarArgs, UncoveredArg); 4640 return SLCT_CheckedLiteral; 4641 } 4642 4643 return SLCT_NotALiteral; 4644 } 4645 case Stmt::BinaryOperatorClass: { 4646 llvm::APSInt LResult; 4647 llvm::APSInt RResult; 4648 4649 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 4650 4651 // A string literal + an int offset is still a string literal. 4652 if (BinOp->isAdditiveOp()) { 4653 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 4654 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 4655 4656 if (LIsInt != RIsInt) { 4657 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 4658 4659 if (LIsInt) { 4660 if (BinOpKind == BO_Add) { 4661 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 4662 E = BinOp->getRHS(); 4663 goto tryAgain; 4664 } 4665 } else { 4666 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 4667 E = BinOp->getLHS(); 4668 goto tryAgain; 4669 } 4670 } 4671 } 4672 4673 return SLCT_NotALiteral; 4674 } 4675 case Stmt::UnaryOperatorClass: { 4676 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 4677 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 4678 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 4679 llvm::APSInt IndexResult; 4680 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 4681 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 4682 E = ASE->getBase(); 4683 goto tryAgain; 4684 } 4685 } 4686 4687 return SLCT_NotALiteral; 4688 } 4689 4690 default: 4691 return SLCT_NotALiteral; 4692 } 4693 } 4694 4695 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 4696 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 4697 .Case("scanf", FST_Scanf) 4698 .Cases("printf", "printf0", FST_Printf) 4699 .Cases("NSString", "CFString", FST_NSString) 4700 .Case("strftime", FST_Strftime) 4701 .Case("strfmon", FST_Strfmon) 4702 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 4703 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 4704 .Case("os_trace", FST_OSLog) 4705 .Case("os_log", FST_OSLog) 4706 .Default(FST_Unknown); 4707 } 4708 4709 /// CheckFormatArguments - Check calls to printf and scanf (and similar 4710 /// functions) for correct use of format strings. 4711 /// Returns true if a format string has been fully checked. 4712 bool Sema::CheckFormatArguments(const FormatAttr *Format, 4713 ArrayRef<const Expr *> Args, 4714 bool IsCXXMember, 4715 VariadicCallType CallType, 4716 SourceLocation Loc, SourceRange Range, 4717 llvm::SmallBitVector &CheckedVarArgs) { 4718 FormatStringInfo FSI; 4719 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 4720 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 4721 FSI.FirstDataArg, GetFormatStringType(Format), 4722 CallType, Loc, Range, CheckedVarArgs); 4723 return false; 4724 } 4725 4726 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 4727 bool HasVAListArg, unsigned format_idx, 4728 unsigned firstDataArg, FormatStringType Type, 4729 VariadicCallType CallType, 4730 SourceLocation Loc, SourceRange Range, 4731 llvm::SmallBitVector &CheckedVarArgs) { 4732 // CHECK: printf/scanf-like function is called with no format string. 4733 if (format_idx >= Args.size()) { 4734 Diag(Loc, diag::warn_missing_format_string) << Range; 4735 return false; 4736 } 4737 4738 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 4739 4740 // CHECK: format string is not a string literal. 4741 // 4742 // Dynamically generated format strings are difficult to 4743 // automatically vet at compile time. Requiring that format strings 4744 // are string literals: (1) permits the checking of format strings by 4745 // the compiler and thereby (2) can practically remove the source of 4746 // many format string exploits. 4747 4748 // Format string can be either ObjC string (e.g. @"%d") or 4749 // C string (e.g. "%d") 4750 // ObjC string uses the same format specifiers as C string, so we can use 4751 // the same format string checking logic for both ObjC and C strings. 4752 UncoveredArgHandler UncoveredArg; 4753 StringLiteralCheckType CT = 4754 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 4755 format_idx, firstDataArg, Type, CallType, 4756 /*IsFunctionCall*/ true, CheckedVarArgs, 4757 UncoveredArg, 4758 /*no string offset*/ llvm::APSInt(64, false) = 0); 4759 4760 // Generate a diagnostic where an uncovered argument is detected. 4761 if (UncoveredArg.hasUncoveredArg()) { 4762 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 4763 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 4764 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 4765 } 4766 4767 if (CT != SLCT_NotALiteral) 4768 // Literal format string found, check done! 4769 return CT == SLCT_CheckedLiteral; 4770 4771 // Strftime is particular as it always uses a single 'time' argument, 4772 // so it is safe to pass a non-literal string. 4773 if (Type == FST_Strftime) 4774 return false; 4775 4776 // Do not emit diag when the string param is a macro expansion and the 4777 // format is either NSString or CFString. This is a hack to prevent 4778 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 4779 // which are usually used in place of NS and CF string literals. 4780 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 4781 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 4782 return false; 4783 4784 // If there are no arguments specified, warn with -Wformat-security, otherwise 4785 // warn only with -Wformat-nonliteral. 4786 if (Args.size() == firstDataArg) { 4787 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 4788 << OrigFormatExpr->getSourceRange(); 4789 switch (Type) { 4790 default: 4791 break; 4792 case FST_Kprintf: 4793 case FST_FreeBSDKPrintf: 4794 case FST_Printf: 4795 Diag(FormatLoc, diag::note_format_security_fixit) 4796 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 4797 break; 4798 case FST_NSString: 4799 Diag(FormatLoc, diag::note_format_security_fixit) 4800 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 4801 break; 4802 } 4803 } else { 4804 Diag(FormatLoc, diag::warn_format_nonliteral) 4805 << OrigFormatExpr->getSourceRange(); 4806 } 4807 return false; 4808 } 4809 4810 namespace { 4811 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 4812 protected: 4813 Sema &S; 4814 const FormatStringLiteral *FExpr; 4815 const Expr *OrigFormatExpr; 4816 const Sema::FormatStringType FSType; 4817 const unsigned FirstDataArg; 4818 const unsigned NumDataArgs; 4819 const char *Beg; // Start of format string. 4820 const bool HasVAListArg; 4821 ArrayRef<const Expr *> Args; 4822 unsigned FormatIdx; 4823 llvm::SmallBitVector CoveredArgs; 4824 bool usesPositionalArgs; 4825 bool atFirstArg; 4826 bool inFunctionCall; 4827 Sema::VariadicCallType CallType; 4828 llvm::SmallBitVector &CheckedVarArgs; 4829 UncoveredArgHandler &UncoveredArg; 4830 4831 public: 4832 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 4833 const Expr *origFormatExpr, 4834 const Sema::FormatStringType type, unsigned firstDataArg, 4835 unsigned numDataArgs, const char *beg, bool hasVAListArg, 4836 ArrayRef<const Expr *> Args, unsigned formatIdx, 4837 bool inFunctionCall, Sema::VariadicCallType callType, 4838 llvm::SmallBitVector &CheckedVarArgs, 4839 UncoveredArgHandler &UncoveredArg) 4840 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 4841 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 4842 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 4843 usesPositionalArgs(false), atFirstArg(true), 4844 inFunctionCall(inFunctionCall), CallType(callType), 4845 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 4846 CoveredArgs.resize(numDataArgs); 4847 CoveredArgs.reset(); 4848 } 4849 4850 void DoneProcessing(); 4851 4852 void HandleIncompleteSpecifier(const char *startSpecifier, 4853 unsigned specifierLen) override; 4854 4855 void HandleInvalidLengthModifier( 4856 const analyze_format_string::FormatSpecifier &FS, 4857 const analyze_format_string::ConversionSpecifier &CS, 4858 const char *startSpecifier, unsigned specifierLen, 4859 unsigned DiagID); 4860 4861 void HandleNonStandardLengthModifier( 4862 const analyze_format_string::FormatSpecifier &FS, 4863 const char *startSpecifier, unsigned specifierLen); 4864 4865 void HandleNonStandardConversionSpecifier( 4866 const analyze_format_string::ConversionSpecifier &CS, 4867 const char *startSpecifier, unsigned specifierLen); 4868 4869 void HandlePosition(const char *startPos, unsigned posLen) override; 4870 4871 void HandleInvalidPosition(const char *startSpecifier, 4872 unsigned specifierLen, 4873 analyze_format_string::PositionContext p) override; 4874 4875 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 4876 4877 void HandleNullChar(const char *nullCharacter) override; 4878 4879 template <typename Range> 4880 static void 4881 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 4882 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 4883 bool IsStringLocation, Range StringRange, 4884 ArrayRef<FixItHint> Fixit = None); 4885 4886 protected: 4887 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 4888 const char *startSpec, 4889 unsigned specifierLen, 4890 const char *csStart, unsigned csLen); 4891 4892 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 4893 const char *startSpec, 4894 unsigned specifierLen); 4895 4896 SourceRange getFormatStringRange(); 4897 CharSourceRange getSpecifierRange(const char *startSpecifier, 4898 unsigned specifierLen); 4899 SourceLocation getLocationOfByte(const char *x); 4900 4901 const Expr *getDataArg(unsigned i) const; 4902 4903 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 4904 const analyze_format_string::ConversionSpecifier &CS, 4905 const char *startSpecifier, unsigned specifierLen, 4906 unsigned argIndex); 4907 4908 template <typename Range> 4909 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 4910 bool IsStringLocation, Range StringRange, 4911 ArrayRef<FixItHint> Fixit = None); 4912 }; 4913 } // end anonymous namespace 4914 4915 SourceRange CheckFormatHandler::getFormatStringRange() { 4916 return OrigFormatExpr->getSourceRange(); 4917 } 4918 4919 CharSourceRange CheckFormatHandler:: 4920 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 4921 SourceLocation Start = getLocationOfByte(startSpecifier); 4922 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 4923 4924 // Advance the end SourceLocation by one due to half-open ranges. 4925 End = End.getLocWithOffset(1); 4926 4927 return CharSourceRange::getCharRange(Start, End); 4928 } 4929 4930 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 4931 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 4932 S.getLangOpts(), S.Context.getTargetInfo()); 4933 } 4934 4935 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 4936 unsigned specifierLen){ 4937 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 4938 getLocationOfByte(startSpecifier), 4939 /*IsStringLocation*/true, 4940 getSpecifierRange(startSpecifier, specifierLen)); 4941 } 4942 4943 void CheckFormatHandler::HandleInvalidLengthModifier( 4944 const analyze_format_string::FormatSpecifier &FS, 4945 const analyze_format_string::ConversionSpecifier &CS, 4946 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 4947 using namespace analyze_format_string; 4948 4949 const LengthModifier &LM = FS.getLengthModifier(); 4950 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4951 4952 // See if we know how to fix this length modifier. 4953 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4954 if (FixedLM) { 4955 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4956 getLocationOfByte(LM.getStart()), 4957 /*IsStringLocation*/true, 4958 getSpecifierRange(startSpecifier, specifierLen)); 4959 4960 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4961 << FixedLM->toString() 4962 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4963 4964 } else { 4965 FixItHint Hint; 4966 if (DiagID == diag::warn_format_nonsensical_length) 4967 Hint = FixItHint::CreateRemoval(LMRange); 4968 4969 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4970 getLocationOfByte(LM.getStart()), 4971 /*IsStringLocation*/true, 4972 getSpecifierRange(startSpecifier, specifierLen), 4973 Hint); 4974 } 4975 } 4976 4977 void CheckFormatHandler::HandleNonStandardLengthModifier( 4978 const analyze_format_string::FormatSpecifier &FS, 4979 const char *startSpecifier, unsigned specifierLen) { 4980 using namespace analyze_format_string; 4981 4982 const LengthModifier &LM = FS.getLengthModifier(); 4983 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4984 4985 // See if we know how to fix this length modifier. 4986 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4987 if (FixedLM) { 4988 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4989 << LM.toString() << 0, 4990 getLocationOfByte(LM.getStart()), 4991 /*IsStringLocation*/true, 4992 getSpecifierRange(startSpecifier, specifierLen)); 4993 4994 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4995 << FixedLM->toString() 4996 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4997 4998 } else { 4999 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5000 << LM.toString() << 0, 5001 getLocationOfByte(LM.getStart()), 5002 /*IsStringLocation*/true, 5003 getSpecifierRange(startSpecifier, specifierLen)); 5004 } 5005 } 5006 5007 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5008 const analyze_format_string::ConversionSpecifier &CS, 5009 const char *startSpecifier, unsigned specifierLen) { 5010 using namespace analyze_format_string; 5011 5012 // See if we know how to fix this conversion specifier. 5013 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5014 if (FixedCS) { 5015 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5016 << CS.toString() << /*conversion specifier*/1, 5017 getLocationOfByte(CS.getStart()), 5018 /*IsStringLocation*/true, 5019 getSpecifierRange(startSpecifier, specifierLen)); 5020 5021 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5022 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5023 << FixedCS->toString() 5024 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5025 } else { 5026 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5027 << CS.toString() << /*conversion specifier*/1, 5028 getLocationOfByte(CS.getStart()), 5029 /*IsStringLocation*/true, 5030 getSpecifierRange(startSpecifier, specifierLen)); 5031 } 5032 } 5033 5034 void CheckFormatHandler::HandlePosition(const char *startPos, 5035 unsigned posLen) { 5036 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5037 getLocationOfByte(startPos), 5038 /*IsStringLocation*/true, 5039 getSpecifierRange(startPos, posLen)); 5040 } 5041 5042 void 5043 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5044 analyze_format_string::PositionContext p) { 5045 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5046 << (unsigned) p, 5047 getLocationOfByte(startPos), /*IsStringLocation*/true, 5048 getSpecifierRange(startPos, posLen)); 5049 } 5050 5051 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5052 unsigned posLen) { 5053 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5054 getLocationOfByte(startPos), 5055 /*IsStringLocation*/true, 5056 getSpecifierRange(startPos, posLen)); 5057 } 5058 5059 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5060 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5061 // The presence of a null character is likely an error. 5062 EmitFormatDiagnostic( 5063 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5064 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5065 getFormatStringRange()); 5066 } 5067 } 5068 5069 // Note that this may return NULL if there was an error parsing or building 5070 // one of the argument expressions. 5071 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5072 return Args[FirstDataArg + i]; 5073 } 5074 5075 void CheckFormatHandler::DoneProcessing() { 5076 // Does the number of data arguments exceed the number of 5077 // format conversions in the format string? 5078 if (!HasVAListArg) { 5079 // Find any arguments that weren't covered. 5080 CoveredArgs.flip(); 5081 signed notCoveredArg = CoveredArgs.find_first(); 5082 if (notCoveredArg >= 0) { 5083 assert((unsigned)notCoveredArg < NumDataArgs); 5084 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5085 } else { 5086 UncoveredArg.setAllCovered(); 5087 } 5088 } 5089 } 5090 5091 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5092 const Expr *ArgExpr) { 5093 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5094 "Invalid state"); 5095 5096 if (!ArgExpr) 5097 return; 5098 5099 SourceLocation Loc = ArgExpr->getLocStart(); 5100 5101 if (S.getSourceManager().isInSystemMacro(Loc)) 5102 return; 5103 5104 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5105 for (auto E : DiagnosticExprs) 5106 PDiag << E->getSourceRange(); 5107 5108 CheckFormatHandler::EmitFormatDiagnostic( 5109 S, IsFunctionCall, DiagnosticExprs[0], 5110 PDiag, Loc, /*IsStringLocation*/false, 5111 DiagnosticExprs[0]->getSourceRange()); 5112 } 5113 5114 bool 5115 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5116 SourceLocation Loc, 5117 const char *startSpec, 5118 unsigned specifierLen, 5119 const char *csStart, 5120 unsigned csLen) { 5121 bool keepGoing = true; 5122 if (argIndex < NumDataArgs) { 5123 // Consider the argument coverered, even though the specifier doesn't 5124 // make sense. 5125 CoveredArgs.set(argIndex); 5126 } 5127 else { 5128 // If argIndex exceeds the number of data arguments we 5129 // don't issue a warning because that is just a cascade of warnings (and 5130 // they may have intended '%%' anyway). We don't want to continue processing 5131 // the format string after this point, however, as we will like just get 5132 // gibberish when trying to match arguments. 5133 keepGoing = false; 5134 } 5135 5136 StringRef Specifier(csStart, csLen); 5137 5138 // If the specifier in non-printable, it could be the first byte of a UTF-8 5139 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5140 // hex value. 5141 std::string CodePointStr; 5142 if (!llvm::sys::locale::isPrint(*csStart)) { 5143 llvm::UTF32 CodePoint; 5144 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5145 const llvm::UTF8 *E = 5146 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5147 llvm::ConversionResult Result = 5148 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5149 5150 if (Result != llvm::conversionOK) { 5151 unsigned char FirstChar = *csStart; 5152 CodePoint = (llvm::UTF32)FirstChar; 5153 } 5154 5155 llvm::raw_string_ostream OS(CodePointStr); 5156 if (CodePoint < 256) 5157 OS << "\\x" << llvm::format("%02x", CodePoint); 5158 else if (CodePoint <= 0xFFFF) 5159 OS << "\\u" << llvm::format("%04x", CodePoint); 5160 else 5161 OS << "\\U" << llvm::format("%08x", CodePoint); 5162 OS.flush(); 5163 Specifier = CodePointStr; 5164 } 5165 5166 EmitFormatDiagnostic( 5167 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5168 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5169 5170 return keepGoing; 5171 } 5172 5173 void 5174 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5175 const char *startSpec, 5176 unsigned specifierLen) { 5177 EmitFormatDiagnostic( 5178 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5179 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5180 } 5181 5182 bool 5183 CheckFormatHandler::CheckNumArgs( 5184 const analyze_format_string::FormatSpecifier &FS, 5185 const analyze_format_string::ConversionSpecifier &CS, 5186 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5187 5188 if (argIndex >= NumDataArgs) { 5189 PartialDiagnostic PDiag = FS.usesPositionalArg() 5190 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5191 << (argIndex+1) << NumDataArgs) 5192 : S.PDiag(diag::warn_printf_insufficient_data_args); 5193 EmitFormatDiagnostic( 5194 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5195 getSpecifierRange(startSpecifier, specifierLen)); 5196 5197 // Since more arguments than conversion tokens are given, by extension 5198 // all arguments are covered, so mark this as so. 5199 UncoveredArg.setAllCovered(); 5200 return false; 5201 } 5202 return true; 5203 } 5204 5205 template<typename Range> 5206 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5207 SourceLocation Loc, 5208 bool IsStringLocation, 5209 Range StringRange, 5210 ArrayRef<FixItHint> FixIt) { 5211 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5212 Loc, IsStringLocation, StringRange, FixIt); 5213 } 5214 5215 /// \brief If the format string is not within the funcion call, emit a note 5216 /// so that the function call and string are in diagnostic messages. 5217 /// 5218 /// \param InFunctionCall if true, the format string is within the function 5219 /// call and only one diagnostic message will be produced. Otherwise, an 5220 /// extra note will be emitted pointing to location of the format string. 5221 /// 5222 /// \param ArgumentExpr the expression that is passed as the format string 5223 /// argument in the function call. Used for getting locations when two 5224 /// diagnostics are emitted. 5225 /// 5226 /// \param PDiag the callee should already have provided any strings for the 5227 /// diagnostic message. This function only adds locations and fixits 5228 /// to diagnostics. 5229 /// 5230 /// \param Loc primary location for diagnostic. If two diagnostics are 5231 /// required, one will be at Loc and a new SourceLocation will be created for 5232 /// the other one. 5233 /// 5234 /// \param IsStringLocation if true, Loc points to the format string should be 5235 /// used for the note. Otherwise, Loc points to the argument list and will 5236 /// be used with PDiag. 5237 /// 5238 /// \param StringRange some or all of the string to highlight. This is 5239 /// templated so it can accept either a CharSourceRange or a SourceRange. 5240 /// 5241 /// \param FixIt optional fix it hint for the format string. 5242 template <typename Range> 5243 void CheckFormatHandler::EmitFormatDiagnostic( 5244 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5245 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5246 Range StringRange, ArrayRef<FixItHint> FixIt) { 5247 if (InFunctionCall) { 5248 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5249 D << StringRange; 5250 D << FixIt; 5251 } else { 5252 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5253 << ArgumentExpr->getSourceRange(); 5254 5255 const Sema::SemaDiagnosticBuilder &Note = 5256 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5257 diag::note_format_string_defined); 5258 5259 Note << StringRange; 5260 Note << FixIt; 5261 } 5262 } 5263 5264 //===--- CHECK: Printf format string checking ------------------------------===// 5265 5266 namespace { 5267 class CheckPrintfHandler : public CheckFormatHandler { 5268 public: 5269 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5270 const Expr *origFormatExpr, 5271 const Sema::FormatStringType type, unsigned firstDataArg, 5272 unsigned numDataArgs, bool isObjC, const char *beg, 5273 bool hasVAListArg, ArrayRef<const Expr *> Args, 5274 unsigned formatIdx, bool inFunctionCall, 5275 Sema::VariadicCallType CallType, 5276 llvm::SmallBitVector &CheckedVarArgs, 5277 UncoveredArgHandler &UncoveredArg) 5278 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5279 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5280 inFunctionCall, CallType, CheckedVarArgs, 5281 UncoveredArg) {} 5282 5283 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5284 5285 /// Returns true if '%@' specifiers are allowed in the format string. 5286 bool allowsObjCArg() const { 5287 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5288 FSType == Sema::FST_OSTrace; 5289 } 5290 5291 bool HandleInvalidPrintfConversionSpecifier( 5292 const analyze_printf::PrintfSpecifier &FS, 5293 const char *startSpecifier, 5294 unsigned specifierLen) override; 5295 5296 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5297 const char *startSpecifier, 5298 unsigned specifierLen) override; 5299 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5300 const char *StartSpecifier, 5301 unsigned SpecifierLen, 5302 const Expr *E); 5303 5304 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5305 const char *startSpecifier, unsigned specifierLen); 5306 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5307 const analyze_printf::OptionalAmount &Amt, 5308 unsigned type, 5309 const char *startSpecifier, unsigned specifierLen); 5310 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5311 const analyze_printf::OptionalFlag &flag, 5312 const char *startSpecifier, unsigned specifierLen); 5313 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5314 const analyze_printf::OptionalFlag &ignoredFlag, 5315 const analyze_printf::OptionalFlag &flag, 5316 const char *startSpecifier, unsigned specifierLen); 5317 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5318 const Expr *E); 5319 5320 void HandleEmptyObjCModifierFlag(const char *startFlag, 5321 unsigned flagLen) override; 5322 5323 void HandleInvalidObjCModifierFlag(const char *startFlag, 5324 unsigned flagLen) override; 5325 5326 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5327 const char *flagsEnd, 5328 const char *conversionPosition) 5329 override; 5330 }; 5331 } // end anonymous namespace 5332 5333 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5334 const analyze_printf::PrintfSpecifier &FS, 5335 const char *startSpecifier, 5336 unsigned specifierLen) { 5337 const analyze_printf::PrintfConversionSpecifier &CS = 5338 FS.getConversionSpecifier(); 5339 5340 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5341 getLocationOfByte(CS.getStart()), 5342 startSpecifier, specifierLen, 5343 CS.getStart(), CS.getLength()); 5344 } 5345 5346 bool CheckPrintfHandler::HandleAmount( 5347 const analyze_format_string::OptionalAmount &Amt, 5348 unsigned k, const char *startSpecifier, 5349 unsigned specifierLen) { 5350 if (Amt.hasDataArgument()) { 5351 if (!HasVAListArg) { 5352 unsigned argIndex = Amt.getArgIndex(); 5353 if (argIndex >= NumDataArgs) { 5354 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5355 << k, 5356 getLocationOfByte(Amt.getStart()), 5357 /*IsStringLocation*/true, 5358 getSpecifierRange(startSpecifier, specifierLen)); 5359 // Don't do any more checking. We will just emit 5360 // spurious errors. 5361 return false; 5362 } 5363 5364 // Type check the data argument. It should be an 'int'. 5365 // Although not in conformance with C99, we also allow the argument to be 5366 // an 'unsigned int' as that is a reasonably safe case. GCC also 5367 // doesn't emit a warning for that case. 5368 CoveredArgs.set(argIndex); 5369 const Expr *Arg = getDataArg(argIndex); 5370 if (!Arg) 5371 return false; 5372 5373 QualType T = Arg->getType(); 5374 5375 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5376 assert(AT.isValid()); 5377 5378 if (!AT.matchesType(S.Context, T)) { 5379 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5380 << k << AT.getRepresentativeTypeName(S.Context) 5381 << T << Arg->getSourceRange(), 5382 getLocationOfByte(Amt.getStart()), 5383 /*IsStringLocation*/true, 5384 getSpecifierRange(startSpecifier, specifierLen)); 5385 // Don't do any more checking. We will just emit 5386 // spurious errors. 5387 return false; 5388 } 5389 } 5390 } 5391 return true; 5392 } 5393 5394 void CheckPrintfHandler::HandleInvalidAmount( 5395 const analyze_printf::PrintfSpecifier &FS, 5396 const analyze_printf::OptionalAmount &Amt, 5397 unsigned type, 5398 const char *startSpecifier, 5399 unsigned specifierLen) { 5400 const analyze_printf::PrintfConversionSpecifier &CS = 5401 FS.getConversionSpecifier(); 5402 5403 FixItHint fixit = 5404 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5405 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5406 Amt.getConstantLength())) 5407 : FixItHint(); 5408 5409 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5410 << type << CS.toString(), 5411 getLocationOfByte(Amt.getStart()), 5412 /*IsStringLocation*/true, 5413 getSpecifierRange(startSpecifier, specifierLen), 5414 fixit); 5415 } 5416 5417 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5418 const analyze_printf::OptionalFlag &flag, 5419 const char *startSpecifier, 5420 unsigned specifierLen) { 5421 // Warn about pointless flag with a fixit removal. 5422 const analyze_printf::PrintfConversionSpecifier &CS = 5423 FS.getConversionSpecifier(); 5424 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5425 << flag.toString() << CS.toString(), 5426 getLocationOfByte(flag.getPosition()), 5427 /*IsStringLocation*/true, 5428 getSpecifierRange(startSpecifier, specifierLen), 5429 FixItHint::CreateRemoval( 5430 getSpecifierRange(flag.getPosition(), 1))); 5431 } 5432 5433 void CheckPrintfHandler::HandleIgnoredFlag( 5434 const analyze_printf::PrintfSpecifier &FS, 5435 const analyze_printf::OptionalFlag &ignoredFlag, 5436 const analyze_printf::OptionalFlag &flag, 5437 const char *startSpecifier, 5438 unsigned specifierLen) { 5439 // Warn about ignored flag with a fixit removal. 5440 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5441 << ignoredFlag.toString() << flag.toString(), 5442 getLocationOfByte(ignoredFlag.getPosition()), 5443 /*IsStringLocation*/true, 5444 getSpecifierRange(startSpecifier, specifierLen), 5445 FixItHint::CreateRemoval( 5446 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5447 } 5448 5449 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5450 // bool IsStringLocation, Range StringRange, 5451 // ArrayRef<FixItHint> Fixit = None); 5452 5453 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5454 unsigned flagLen) { 5455 // Warn about an empty flag. 5456 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5457 getLocationOfByte(startFlag), 5458 /*IsStringLocation*/true, 5459 getSpecifierRange(startFlag, flagLen)); 5460 } 5461 5462 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5463 unsigned flagLen) { 5464 // Warn about an invalid flag. 5465 auto Range = getSpecifierRange(startFlag, flagLen); 5466 StringRef flag(startFlag, flagLen); 5467 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5468 getLocationOfByte(startFlag), 5469 /*IsStringLocation*/true, 5470 Range, FixItHint::CreateRemoval(Range)); 5471 } 5472 5473 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5474 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5475 // Warn about using '[...]' without a '@' conversion. 5476 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5477 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5478 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5479 getLocationOfByte(conversionPosition), 5480 /*IsStringLocation*/true, 5481 Range, FixItHint::CreateRemoval(Range)); 5482 } 5483 5484 // Determines if the specified is a C++ class or struct containing 5485 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5486 // "c_str()"). 5487 template<typename MemberKind> 5488 static llvm::SmallPtrSet<MemberKind*, 1> 5489 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5490 const RecordType *RT = Ty->getAs<RecordType>(); 5491 llvm::SmallPtrSet<MemberKind*, 1> Results; 5492 5493 if (!RT) 5494 return Results; 5495 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5496 if (!RD || !RD->getDefinition()) 5497 return Results; 5498 5499 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5500 Sema::LookupMemberName); 5501 R.suppressDiagnostics(); 5502 5503 // We just need to include all members of the right kind turned up by the 5504 // filter, at this point. 5505 if (S.LookupQualifiedName(R, RT->getDecl())) 5506 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5507 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5508 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5509 Results.insert(FK); 5510 } 5511 return Results; 5512 } 5513 5514 /// Check if we could call '.c_str()' on an object. 5515 /// 5516 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5517 /// allow the call, or if it would be ambiguous). 5518 bool Sema::hasCStrMethod(const Expr *E) { 5519 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5520 MethodSet Results = 5521 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5522 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5523 MI != ME; ++MI) 5524 if ((*MI)->getMinRequiredArguments() == 0) 5525 return true; 5526 return false; 5527 } 5528 5529 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5530 // better diagnostic if so. AT is assumed to be valid. 5531 // Returns true when a c_str() conversion method is found. 5532 bool CheckPrintfHandler::checkForCStrMembers( 5533 const analyze_printf::ArgType &AT, const Expr *E) { 5534 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5535 5536 MethodSet Results = 5537 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5538 5539 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5540 MI != ME; ++MI) { 5541 const CXXMethodDecl *Method = *MI; 5542 if (Method->getMinRequiredArguments() == 0 && 5543 AT.matchesType(S.Context, Method->getReturnType())) { 5544 // FIXME: Suggest parens if the expression needs them. 5545 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5546 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5547 << "c_str()" 5548 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5549 return true; 5550 } 5551 } 5552 5553 return false; 5554 } 5555 5556 bool 5557 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5558 &FS, 5559 const char *startSpecifier, 5560 unsigned specifierLen) { 5561 using namespace analyze_format_string; 5562 using namespace analyze_printf; 5563 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5564 5565 if (FS.consumesDataArgument()) { 5566 if (atFirstArg) { 5567 atFirstArg = false; 5568 usesPositionalArgs = FS.usesPositionalArg(); 5569 } 5570 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5571 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5572 startSpecifier, specifierLen); 5573 return false; 5574 } 5575 } 5576 5577 // First check if the field width, precision, and conversion specifier 5578 // have matching data arguments. 5579 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5580 startSpecifier, specifierLen)) { 5581 return false; 5582 } 5583 5584 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5585 startSpecifier, specifierLen)) { 5586 return false; 5587 } 5588 5589 if (!CS.consumesDataArgument()) { 5590 // FIXME: Technically specifying a precision or field width here 5591 // makes no sense. Worth issuing a warning at some point. 5592 return true; 5593 } 5594 5595 // Consume the argument. 5596 unsigned argIndex = FS.getArgIndex(); 5597 if (argIndex < NumDataArgs) { 5598 // The check to see if the argIndex is valid will come later. 5599 // We set the bit here because we may exit early from this 5600 // function if we encounter some other error. 5601 CoveredArgs.set(argIndex); 5602 } 5603 5604 // FreeBSD kernel extensions. 5605 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5606 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5607 // We need at least two arguments. 5608 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5609 return false; 5610 5611 // Claim the second argument. 5612 CoveredArgs.set(argIndex + 1); 5613 5614 // Type check the first argument (int for %b, pointer for %D) 5615 const Expr *Ex = getDataArg(argIndex); 5616 const analyze_printf::ArgType &AT = 5617 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5618 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5619 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5620 EmitFormatDiagnostic( 5621 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5622 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5623 << false << Ex->getSourceRange(), 5624 Ex->getLocStart(), /*IsStringLocation*/false, 5625 getSpecifierRange(startSpecifier, specifierLen)); 5626 5627 // Type check the second argument (char * for both %b and %D) 5628 Ex = getDataArg(argIndex + 1); 5629 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5630 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5631 EmitFormatDiagnostic( 5632 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5633 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5634 << false << Ex->getSourceRange(), 5635 Ex->getLocStart(), /*IsStringLocation*/false, 5636 getSpecifierRange(startSpecifier, specifierLen)); 5637 5638 return true; 5639 } 5640 5641 // Check for using an Objective-C specific conversion specifier 5642 // in a non-ObjC literal. 5643 if (!allowsObjCArg() && CS.isObjCArg()) { 5644 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5645 specifierLen); 5646 } 5647 5648 // %P can only be used with os_log. 5649 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 5650 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5651 specifierLen); 5652 } 5653 5654 // %n is not allowed with os_log. 5655 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 5656 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 5657 getLocationOfByte(CS.getStart()), 5658 /*IsStringLocation*/ false, 5659 getSpecifierRange(startSpecifier, specifierLen)); 5660 5661 return true; 5662 } 5663 5664 // Only scalars are allowed for os_trace. 5665 if (FSType == Sema::FST_OSTrace && 5666 (CS.getKind() == ConversionSpecifier::PArg || 5667 CS.getKind() == ConversionSpecifier::sArg || 5668 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 5669 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5670 specifierLen); 5671 } 5672 5673 // Check for use of public/private annotation outside of os_log(). 5674 if (FSType != Sema::FST_OSLog) { 5675 if (FS.isPublic().isSet()) { 5676 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5677 << "public", 5678 getLocationOfByte(FS.isPublic().getPosition()), 5679 /*IsStringLocation*/ false, 5680 getSpecifierRange(startSpecifier, specifierLen)); 5681 } 5682 if (FS.isPrivate().isSet()) { 5683 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5684 << "private", 5685 getLocationOfByte(FS.isPrivate().getPosition()), 5686 /*IsStringLocation*/ false, 5687 getSpecifierRange(startSpecifier, specifierLen)); 5688 } 5689 } 5690 5691 // Check for invalid use of field width 5692 if (!FS.hasValidFieldWidth()) { 5693 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 5694 startSpecifier, specifierLen); 5695 } 5696 5697 // Check for invalid use of precision 5698 if (!FS.hasValidPrecision()) { 5699 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 5700 startSpecifier, specifierLen); 5701 } 5702 5703 // Precision is mandatory for %P specifier. 5704 if (CS.getKind() == ConversionSpecifier::PArg && 5705 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 5706 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 5707 getLocationOfByte(startSpecifier), 5708 /*IsStringLocation*/ false, 5709 getSpecifierRange(startSpecifier, specifierLen)); 5710 } 5711 5712 // Check each flag does not conflict with any other component. 5713 if (!FS.hasValidThousandsGroupingPrefix()) 5714 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 5715 if (!FS.hasValidLeadingZeros()) 5716 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 5717 if (!FS.hasValidPlusPrefix()) 5718 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 5719 if (!FS.hasValidSpacePrefix()) 5720 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 5721 if (!FS.hasValidAlternativeForm()) 5722 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 5723 if (!FS.hasValidLeftJustified()) 5724 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 5725 5726 // Check that flags are not ignored by another flag 5727 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 5728 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 5729 startSpecifier, specifierLen); 5730 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 5731 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 5732 startSpecifier, specifierLen); 5733 5734 // Check the length modifier is valid with the given conversion specifier. 5735 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5736 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5737 diag::warn_format_nonsensical_length); 5738 else if (!FS.hasStandardLengthModifier()) 5739 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5740 else if (!FS.hasStandardLengthConversionCombination()) 5741 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5742 diag::warn_format_non_standard_conversion_spec); 5743 5744 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5745 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5746 5747 // The remaining checks depend on the data arguments. 5748 if (HasVAListArg) 5749 return true; 5750 5751 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5752 return false; 5753 5754 const Expr *Arg = getDataArg(argIndex); 5755 if (!Arg) 5756 return true; 5757 5758 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 5759 } 5760 5761 static bool requiresParensToAddCast(const Expr *E) { 5762 // FIXME: We should have a general way to reason about operator 5763 // precedence and whether parens are actually needed here. 5764 // Take care of a few common cases where they aren't. 5765 const Expr *Inside = E->IgnoreImpCasts(); 5766 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 5767 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 5768 5769 switch (Inside->getStmtClass()) { 5770 case Stmt::ArraySubscriptExprClass: 5771 case Stmt::CallExprClass: 5772 case Stmt::CharacterLiteralClass: 5773 case Stmt::CXXBoolLiteralExprClass: 5774 case Stmt::DeclRefExprClass: 5775 case Stmt::FloatingLiteralClass: 5776 case Stmt::IntegerLiteralClass: 5777 case Stmt::MemberExprClass: 5778 case Stmt::ObjCArrayLiteralClass: 5779 case Stmt::ObjCBoolLiteralExprClass: 5780 case Stmt::ObjCBoxedExprClass: 5781 case Stmt::ObjCDictionaryLiteralClass: 5782 case Stmt::ObjCEncodeExprClass: 5783 case Stmt::ObjCIvarRefExprClass: 5784 case Stmt::ObjCMessageExprClass: 5785 case Stmt::ObjCPropertyRefExprClass: 5786 case Stmt::ObjCStringLiteralClass: 5787 case Stmt::ObjCSubscriptRefExprClass: 5788 case Stmt::ParenExprClass: 5789 case Stmt::StringLiteralClass: 5790 case Stmt::UnaryOperatorClass: 5791 return false; 5792 default: 5793 return true; 5794 } 5795 } 5796 5797 static std::pair<QualType, StringRef> 5798 shouldNotPrintDirectly(const ASTContext &Context, 5799 QualType IntendedTy, 5800 const Expr *E) { 5801 // Use a 'while' to peel off layers of typedefs. 5802 QualType TyTy = IntendedTy; 5803 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 5804 StringRef Name = UserTy->getDecl()->getName(); 5805 QualType CastTy = llvm::StringSwitch<QualType>(Name) 5806 .Case("NSInteger", Context.LongTy) 5807 .Case("NSUInteger", Context.UnsignedLongTy) 5808 .Case("SInt32", Context.IntTy) 5809 .Case("UInt32", Context.UnsignedIntTy) 5810 .Default(QualType()); 5811 5812 if (!CastTy.isNull()) 5813 return std::make_pair(CastTy, Name); 5814 5815 TyTy = UserTy->desugar(); 5816 } 5817 5818 // Strip parens if necessary. 5819 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 5820 return shouldNotPrintDirectly(Context, 5821 PE->getSubExpr()->getType(), 5822 PE->getSubExpr()); 5823 5824 // If this is a conditional expression, then its result type is constructed 5825 // via usual arithmetic conversions and thus there might be no necessary 5826 // typedef sugar there. Recurse to operands to check for NSInteger & 5827 // Co. usage condition. 5828 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 5829 QualType TrueTy, FalseTy; 5830 StringRef TrueName, FalseName; 5831 5832 std::tie(TrueTy, TrueName) = 5833 shouldNotPrintDirectly(Context, 5834 CO->getTrueExpr()->getType(), 5835 CO->getTrueExpr()); 5836 std::tie(FalseTy, FalseName) = 5837 shouldNotPrintDirectly(Context, 5838 CO->getFalseExpr()->getType(), 5839 CO->getFalseExpr()); 5840 5841 if (TrueTy == FalseTy) 5842 return std::make_pair(TrueTy, TrueName); 5843 else if (TrueTy.isNull()) 5844 return std::make_pair(FalseTy, FalseName); 5845 else if (FalseTy.isNull()) 5846 return std::make_pair(TrueTy, TrueName); 5847 } 5848 5849 return std::make_pair(QualType(), StringRef()); 5850 } 5851 5852 bool 5853 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5854 const char *StartSpecifier, 5855 unsigned SpecifierLen, 5856 const Expr *E) { 5857 using namespace analyze_format_string; 5858 using namespace analyze_printf; 5859 // Now type check the data expression that matches the 5860 // format specifier. 5861 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 5862 if (!AT.isValid()) 5863 return true; 5864 5865 QualType ExprTy = E->getType(); 5866 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 5867 ExprTy = TET->getUnderlyingExpr()->getType(); 5868 } 5869 5870 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 5871 5872 if (match == analyze_printf::ArgType::Match) { 5873 return true; 5874 } 5875 5876 // Look through argument promotions for our error message's reported type. 5877 // This includes the integral and floating promotions, but excludes array 5878 // and function pointer decay; seeing that an argument intended to be a 5879 // string has type 'char [6]' is probably more confusing than 'char *'. 5880 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5881 if (ICE->getCastKind() == CK_IntegralCast || 5882 ICE->getCastKind() == CK_FloatingCast) { 5883 E = ICE->getSubExpr(); 5884 ExprTy = E->getType(); 5885 5886 // Check if we didn't match because of an implicit cast from a 'char' 5887 // or 'short' to an 'int'. This is done because printf is a varargs 5888 // function. 5889 if (ICE->getType() == S.Context.IntTy || 5890 ICE->getType() == S.Context.UnsignedIntTy) { 5891 // All further checking is done on the subexpression. 5892 if (AT.matchesType(S.Context, ExprTy)) 5893 return true; 5894 } 5895 } 5896 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 5897 // Special case for 'a', which has type 'int' in C. 5898 // Note, however, that we do /not/ want to treat multibyte constants like 5899 // 'MooV' as characters! This form is deprecated but still exists. 5900 if (ExprTy == S.Context.IntTy) 5901 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 5902 ExprTy = S.Context.CharTy; 5903 } 5904 5905 // Look through enums to their underlying type. 5906 bool IsEnum = false; 5907 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 5908 ExprTy = EnumTy->getDecl()->getIntegerType(); 5909 IsEnum = true; 5910 } 5911 5912 // %C in an Objective-C context prints a unichar, not a wchar_t. 5913 // If the argument is an integer of some kind, believe the %C and suggest 5914 // a cast instead of changing the conversion specifier. 5915 QualType IntendedTy = ExprTy; 5916 if (isObjCContext() && 5917 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 5918 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 5919 !ExprTy->isCharType()) { 5920 // 'unichar' is defined as a typedef of unsigned short, but we should 5921 // prefer using the typedef if it is visible. 5922 IntendedTy = S.Context.UnsignedShortTy; 5923 5924 // While we are here, check if the value is an IntegerLiteral that happens 5925 // to be within the valid range. 5926 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 5927 const llvm::APInt &V = IL->getValue(); 5928 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 5929 return true; 5930 } 5931 5932 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 5933 Sema::LookupOrdinaryName); 5934 if (S.LookupName(Result, S.getCurScope())) { 5935 NamedDecl *ND = Result.getFoundDecl(); 5936 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 5937 if (TD->getUnderlyingType() == IntendedTy) 5938 IntendedTy = S.Context.getTypedefType(TD); 5939 } 5940 } 5941 } 5942 5943 // Special-case some of Darwin's platform-independence types by suggesting 5944 // casts to primitive types that are known to be large enough. 5945 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 5946 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 5947 QualType CastTy; 5948 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 5949 if (!CastTy.isNull()) { 5950 IntendedTy = CastTy; 5951 ShouldNotPrintDirectly = true; 5952 } 5953 } 5954 5955 // We may be able to offer a FixItHint if it is a supported type. 5956 PrintfSpecifier fixedFS = FS; 5957 bool success = 5958 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 5959 5960 if (success) { 5961 // Get the fix string from the fixed format specifier 5962 SmallString<16> buf; 5963 llvm::raw_svector_ostream os(buf); 5964 fixedFS.toString(os); 5965 5966 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 5967 5968 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 5969 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5970 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 5971 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5972 } 5973 // In this case, the specifier is wrong and should be changed to match 5974 // the argument. 5975 EmitFormatDiagnostic(S.PDiag(diag) 5976 << AT.getRepresentativeTypeName(S.Context) 5977 << IntendedTy << IsEnum << E->getSourceRange(), 5978 E->getLocStart(), 5979 /*IsStringLocation*/ false, SpecRange, 5980 FixItHint::CreateReplacement(SpecRange, os.str())); 5981 } else { 5982 // The canonical type for formatting this value is different from the 5983 // actual type of the expression. (This occurs, for example, with Darwin's 5984 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 5985 // should be printed as 'long' for 64-bit compatibility.) 5986 // Rather than emitting a normal format/argument mismatch, we want to 5987 // add a cast to the recommended type (and correct the format string 5988 // if necessary). 5989 SmallString<16> CastBuf; 5990 llvm::raw_svector_ostream CastFix(CastBuf); 5991 CastFix << "("; 5992 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 5993 CastFix << ")"; 5994 5995 SmallVector<FixItHint,4> Hints; 5996 if (!AT.matchesType(S.Context, IntendedTy)) 5997 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 5998 5999 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6000 // If there's already a cast present, just replace it. 6001 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6002 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6003 6004 } else if (!requiresParensToAddCast(E)) { 6005 // If the expression has high enough precedence, 6006 // just write the C-style cast. 6007 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6008 CastFix.str())); 6009 } else { 6010 // Otherwise, add parens around the expression as well as the cast. 6011 CastFix << "("; 6012 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6013 CastFix.str())); 6014 6015 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6016 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6017 } 6018 6019 if (ShouldNotPrintDirectly) { 6020 // The expression has a type that should not be printed directly. 6021 // We extract the name from the typedef because we don't want to show 6022 // the underlying type in the diagnostic. 6023 StringRef Name; 6024 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6025 Name = TypedefTy->getDecl()->getName(); 6026 else 6027 Name = CastTyName; 6028 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6029 << Name << IntendedTy << IsEnum 6030 << E->getSourceRange(), 6031 E->getLocStart(), /*IsStringLocation=*/false, 6032 SpecRange, Hints); 6033 } else { 6034 // In this case, the expression could be printed using a different 6035 // specifier, but we've decided that the specifier is probably correct 6036 // and we should cast instead. Just use the normal warning message. 6037 EmitFormatDiagnostic( 6038 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6039 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6040 << E->getSourceRange(), 6041 E->getLocStart(), /*IsStringLocation*/false, 6042 SpecRange, Hints); 6043 } 6044 } 6045 } else { 6046 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6047 SpecifierLen); 6048 // Since the warning for passing non-POD types to variadic functions 6049 // was deferred until now, we emit a warning for non-POD 6050 // arguments here. 6051 switch (S.isValidVarArgType(ExprTy)) { 6052 case Sema::VAK_Valid: 6053 case Sema::VAK_ValidInCXX11: { 6054 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6055 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6056 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6057 } 6058 6059 EmitFormatDiagnostic( 6060 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6061 << IsEnum << CSR << E->getSourceRange(), 6062 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6063 break; 6064 } 6065 case Sema::VAK_Undefined: 6066 case Sema::VAK_MSVCUndefined: 6067 EmitFormatDiagnostic( 6068 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6069 << S.getLangOpts().CPlusPlus11 6070 << ExprTy 6071 << CallType 6072 << AT.getRepresentativeTypeName(S.Context) 6073 << CSR 6074 << E->getSourceRange(), 6075 E->getLocStart(), /*IsStringLocation*/false, CSR); 6076 checkForCStrMembers(AT, E); 6077 break; 6078 6079 case Sema::VAK_Invalid: 6080 if (ExprTy->isObjCObjectType()) 6081 EmitFormatDiagnostic( 6082 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6083 << S.getLangOpts().CPlusPlus11 6084 << ExprTy 6085 << CallType 6086 << AT.getRepresentativeTypeName(S.Context) 6087 << CSR 6088 << E->getSourceRange(), 6089 E->getLocStart(), /*IsStringLocation*/false, CSR); 6090 else 6091 // FIXME: If this is an initializer list, suggest removing the braces 6092 // or inserting a cast to the target type. 6093 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6094 << isa<InitListExpr>(E) << ExprTy << CallType 6095 << AT.getRepresentativeTypeName(S.Context) 6096 << E->getSourceRange(); 6097 break; 6098 } 6099 6100 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6101 "format string specifier index out of range"); 6102 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6103 } 6104 6105 return true; 6106 } 6107 6108 //===--- CHECK: Scanf format string checking ------------------------------===// 6109 6110 namespace { 6111 class CheckScanfHandler : public CheckFormatHandler { 6112 public: 6113 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6114 const Expr *origFormatExpr, Sema::FormatStringType type, 6115 unsigned firstDataArg, unsigned numDataArgs, 6116 const char *beg, bool hasVAListArg, 6117 ArrayRef<const Expr *> Args, unsigned formatIdx, 6118 bool inFunctionCall, Sema::VariadicCallType CallType, 6119 llvm::SmallBitVector &CheckedVarArgs, 6120 UncoveredArgHandler &UncoveredArg) 6121 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6122 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6123 inFunctionCall, CallType, CheckedVarArgs, 6124 UncoveredArg) {} 6125 6126 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6127 const char *startSpecifier, 6128 unsigned specifierLen) override; 6129 6130 bool HandleInvalidScanfConversionSpecifier( 6131 const analyze_scanf::ScanfSpecifier &FS, 6132 const char *startSpecifier, 6133 unsigned specifierLen) override; 6134 6135 void HandleIncompleteScanList(const char *start, const char *end) override; 6136 }; 6137 } // end anonymous namespace 6138 6139 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6140 const char *end) { 6141 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6142 getLocationOfByte(end), /*IsStringLocation*/true, 6143 getSpecifierRange(start, end - start)); 6144 } 6145 6146 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6147 const analyze_scanf::ScanfSpecifier &FS, 6148 const char *startSpecifier, 6149 unsigned specifierLen) { 6150 6151 const analyze_scanf::ScanfConversionSpecifier &CS = 6152 FS.getConversionSpecifier(); 6153 6154 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6155 getLocationOfByte(CS.getStart()), 6156 startSpecifier, specifierLen, 6157 CS.getStart(), CS.getLength()); 6158 } 6159 6160 bool CheckScanfHandler::HandleScanfSpecifier( 6161 const analyze_scanf::ScanfSpecifier &FS, 6162 const char *startSpecifier, 6163 unsigned specifierLen) { 6164 using namespace analyze_scanf; 6165 using namespace analyze_format_string; 6166 6167 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6168 6169 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6170 // be used to decide if we are using positional arguments consistently. 6171 if (FS.consumesDataArgument()) { 6172 if (atFirstArg) { 6173 atFirstArg = false; 6174 usesPositionalArgs = FS.usesPositionalArg(); 6175 } 6176 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6177 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6178 startSpecifier, specifierLen); 6179 return false; 6180 } 6181 } 6182 6183 // Check if the field with is non-zero. 6184 const OptionalAmount &Amt = FS.getFieldWidth(); 6185 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6186 if (Amt.getConstantAmount() == 0) { 6187 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6188 Amt.getConstantLength()); 6189 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6190 getLocationOfByte(Amt.getStart()), 6191 /*IsStringLocation*/true, R, 6192 FixItHint::CreateRemoval(R)); 6193 } 6194 } 6195 6196 if (!FS.consumesDataArgument()) { 6197 // FIXME: Technically specifying a precision or field width here 6198 // makes no sense. Worth issuing a warning at some point. 6199 return true; 6200 } 6201 6202 // Consume the argument. 6203 unsigned argIndex = FS.getArgIndex(); 6204 if (argIndex < NumDataArgs) { 6205 // The check to see if the argIndex is valid will come later. 6206 // We set the bit here because we may exit early from this 6207 // function if we encounter some other error. 6208 CoveredArgs.set(argIndex); 6209 } 6210 6211 // Check the length modifier is valid with the given conversion specifier. 6212 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6213 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6214 diag::warn_format_nonsensical_length); 6215 else if (!FS.hasStandardLengthModifier()) 6216 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6217 else if (!FS.hasStandardLengthConversionCombination()) 6218 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6219 diag::warn_format_non_standard_conversion_spec); 6220 6221 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6222 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6223 6224 // The remaining checks depend on the data arguments. 6225 if (HasVAListArg) 6226 return true; 6227 6228 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6229 return false; 6230 6231 // Check that the argument type matches the format specifier. 6232 const Expr *Ex = getDataArg(argIndex); 6233 if (!Ex) 6234 return true; 6235 6236 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6237 6238 if (!AT.isValid()) { 6239 return true; 6240 } 6241 6242 analyze_format_string::ArgType::MatchKind match = 6243 AT.matchesType(S.Context, Ex->getType()); 6244 if (match == analyze_format_string::ArgType::Match) { 6245 return true; 6246 } 6247 6248 ScanfSpecifier fixedFS = FS; 6249 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6250 S.getLangOpts(), S.Context); 6251 6252 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6253 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6254 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6255 } 6256 6257 if (success) { 6258 // Get the fix string from the fixed format specifier. 6259 SmallString<128> buf; 6260 llvm::raw_svector_ostream os(buf); 6261 fixedFS.toString(os); 6262 6263 EmitFormatDiagnostic( 6264 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6265 << Ex->getType() << false << Ex->getSourceRange(), 6266 Ex->getLocStart(), 6267 /*IsStringLocation*/ false, 6268 getSpecifierRange(startSpecifier, specifierLen), 6269 FixItHint::CreateReplacement( 6270 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6271 } else { 6272 EmitFormatDiagnostic(S.PDiag(diag) 6273 << AT.getRepresentativeTypeName(S.Context) 6274 << Ex->getType() << false << Ex->getSourceRange(), 6275 Ex->getLocStart(), 6276 /*IsStringLocation*/ false, 6277 getSpecifierRange(startSpecifier, specifierLen)); 6278 } 6279 6280 return true; 6281 } 6282 6283 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6284 const Expr *OrigFormatExpr, 6285 ArrayRef<const Expr *> Args, 6286 bool HasVAListArg, unsigned format_idx, 6287 unsigned firstDataArg, 6288 Sema::FormatStringType Type, 6289 bool inFunctionCall, 6290 Sema::VariadicCallType CallType, 6291 llvm::SmallBitVector &CheckedVarArgs, 6292 UncoveredArgHandler &UncoveredArg) { 6293 // CHECK: is the format string a wide literal? 6294 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6295 CheckFormatHandler::EmitFormatDiagnostic( 6296 S, inFunctionCall, Args[format_idx], 6297 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6298 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6299 return; 6300 } 6301 6302 // Str - The format string. NOTE: this is NOT null-terminated! 6303 StringRef StrRef = FExpr->getString(); 6304 const char *Str = StrRef.data(); 6305 // Account for cases where the string literal is truncated in a declaration. 6306 const ConstantArrayType *T = 6307 S.Context.getAsConstantArrayType(FExpr->getType()); 6308 assert(T && "String literal not of constant array type!"); 6309 size_t TypeSize = T->getSize().getZExtValue(); 6310 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6311 const unsigned numDataArgs = Args.size() - firstDataArg; 6312 6313 // Emit a warning if the string literal is truncated and does not contain an 6314 // embedded null character. 6315 if (TypeSize <= StrRef.size() && 6316 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6317 CheckFormatHandler::EmitFormatDiagnostic( 6318 S, inFunctionCall, Args[format_idx], 6319 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6320 FExpr->getLocStart(), 6321 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6322 return; 6323 } 6324 6325 // CHECK: empty format string? 6326 if (StrLen == 0 && numDataArgs > 0) { 6327 CheckFormatHandler::EmitFormatDiagnostic( 6328 S, inFunctionCall, Args[format_idx], 6329 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6330 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6331 return; 6332 } 6333 6334 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6335 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6336 Type == Sema::FST_OSTrace) { 6337 CheckPrintfHandler H( 6338 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6339 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6340 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6341 CheckedVarArgs, UncoveredArg); 6342 6343 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6344 S.getLangOpts(), 6345 S.Context.getTargetInfo(), 6346 Type == Sema::FST_FreeBSDKPrintf)) 6347 H.DoneProcessing(); 6348 } else if (Type == Sema::FST_Scanf) { 6349 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6350 numDataArgs, Str, HasVAListArg, Args, format_idx, 6351 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6352 6353 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6354 S.getLangOpts(), 6355 S.Context.getTargetInfo())) 6356 H.DoneProcessing(); 6357 } // TODO: handle other formats 6358 } 6359 6360 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6361 // Str - The format string. NOTE: this is NOT null-terminated! 6362 StringRef StrRef = FExpr->getString(); 6363 const char *Str = StrRef.data(); 6364 // Account for cases where the string literal is truncated in a declaration. 6365 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6366 assert(T && "String literal not of constant array type!"); 6367 size_t TypeSize = T->getSize().getZExtValue(); 6368 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6369 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6370 getLangOpts(), 6371 Context.getTargetInfo()); 6372 } 6373 6374 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6375 6376 // Returns the related absolute value function that is larger, of 0 if one 6377 // does not exist. 6378 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6379 switch (AbsFunction) { 6380 default: 6381 return 0; 6382 6383 case Builtin::BI__builtin_abs: 6384 return Builtin::BI__builtin_labs; 6385 case Builtin::BI__builtin_labs: 6386 return Builtin::BI__builtin_llabs; 6387 case Builtin::BI__builtin_llabs: 6388 return 0; 6389 6390 case Builtin::BI__builtin_fabsf: 6391 return Builtin::BI__builtin_fabs; 6392 case Builtin::BI__builtin_fabs: 6393 return Builtin::BI__builtin_fabsl; 6394 case Builtin::BI__builtin_fabsl: 6395 return 0; 6396 6397 case Builtin::BI__builtin_cabsf: 6398 return Builtin::BI__builtin_cabs; 6399 case Builtin::BI__builtin_cabs: 6400 return Builtin::BI__builtin_cabsl; 6401 case Builtin::BI__builtin_cabsl: 6402 return 0; 6403 6404 case Builtin::BIabs: 6405 return Builtin::BIlabs; 6406 case Builtin::BIlabs: 6407 return Builtin::BIllabs; 6408 case Builtin::BIllabs: 6409 return 0; 6410 6411 case Builtin::BIfabsf: 6412 return Builtin::BIfabs; 6413 case Builtin::BIfabs: 6414 return Builtin::BIfabsl; 6415 case Builtin::BIfabsl: 6416 return 0; 6417 6418 case Builtin::BIcabsf: 6419 return Builtin::BIcabs; 6420 case Builtin::BIcabs: 6421 return Builtin::BIcabsl; 6422 case Builtin::BIcabsl: 6423 return 0; 6424 } 6425 } 6426 6427 // Returns the argument type of the absolute value function. 6428 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6429 unsigned AbsType) { 6430 if (AbsType == 0) 6431 return QualType(); 6432 6433 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6434 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6435 if (Error != ASTContext::GE_None) 6436 return QualType(); 6437 6438 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6439 if (!FT) 6440 return QualType(); 6441 6442 if (FT->getNumParams() != 1) 6443 return QualType(); 6444 6445 return FT->getParamType(0); 6446 } 6447 6448 // Returns the best absolute value function, or zero, based on type and 6449 // current absolute value function. 6450 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6451 unsigned AbsFunctionKind) { 6452 unsigned BestKind = 0; 6453 uint64_t ArgSize = Context.getTypeSize(ArgType); 6454 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6455 Kind = getLargerAbsoluteValueFunction(Kind)) { 6456 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6457 if (Context.getTypeSize(ParamType) >= ArgSize) { 6458 if (BestKind == 0) 6459 BestKind = Kind; 6460 else if (Context.hasSameType(ParamType, ArgType)) { 6461 BestKind = Kind; 6462 break; 6463 } 6464 } 6465 } 6466 return BestKind; 6467 } 6468 6469 enum AbsoluteValueKind { 6470 AVK_Integer, 6471 AVK_Floating, 6472 AVK_Complex 6473 }; 6474 6475 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6476 if (T->isIntegralOrEnumerationType()) 6477 return AVK_Integer; 6478 if (T->isRealFloatingType()) 6479 return AVK_Floating; 6480 if (T->isAnyComplexType()) 6481 return AVK_Complex; 6482 6483 llvm_unreachable("Type not integer, floating, or complex"); 6484 } 6485 6486 // Changes the absolute value function to a different type. Preserves whether 6487 // the function is a builtin. 6488 static unsigned changeAbsFunction(unsigned AbsKind, 6489 AbsoluteValueKind ValueKind) { 6490 switch (ValueKind) { 6491 case AVK_Integer: 6492 switch (AbsKind) { 6493 default: 6494 return 0; 6495 case Builtin::BI__builtin_fabsf: 6496 case Builtin::BI__builtin_fabs: 6497 case Builtin::BI__builtin_fabsl: 6498 case Builtin::BI__builtin_cabsf: 6499 case Builtin::BI__builtin_cabs: 6500 case Builtin::BI__builtin_cabsl: 6501 return Builtin::BI__builtin_abs; 6502 case Builtin::BIfabsf: 6503 case Builtin::BIfabs: 6504 case Builtin::BIfabsl: 6505 case Builtin::BIcabsf: 6506 case Builtin::BIcabs: 6507 case Builtin::BIcabsl: 6508 return Builtin::BIabs; 6509 } 6510 case AVK_Floating: 6511 switch (AbsKind) { 6512 default: 6513 return 0; 6514 case Builtin::BI__builtin_abs: 6515 case Builtin::BI__builtin_labs: 6516 case Builtin::BI__builtin_llabs: 6517 case Builtin::BI__builtin_cabsf: 6518 case Builtin::BI__builtin_cabs: 6519 case Builtin::BI__builtin_cabsl: 6520 return Builtin::BI__builtin_fabsf; 6521 case Builtin::BIabs: 6522 case Builtin::BIlabs: 6523 case Builtin::BIllabs: 6524 case Builtin::BIcabsf: 6525 case Builtin::BIcabs: 6526 case Builtin::BIcabsl: 6527 return Builtin::BIfabsf; 6528 } 6529 case AVK_Complex: 6530 switch (AbsKind) { 6531 default: 6532 return 0; 6533 case Builtin::BI__builtin_abs: 6534 case Builtin::BI__builtin_labs: 6535 case Builtin::BI__builtin_llabs: 6536 case Builtin::BI__builtin_fabsf: 6537 case Builtin::BI__builtin_fabs: 6538 case Builtin::BI__builtin_fabsl: 6539 return Builtin::BI__builtin_cabsf; 6540 case Builtin::BIabs: 6541 case Builtin::BIlabs: 6542 case Builtin::BIllabs: 6543 case Builtin::BIfabsf: 6544 case Builtin::BIfabs: 6545 case Builtin::BIfabsl: 6546 return Builtin::BIcabsf; 6547 } 6548 } 6549 llvm_unreachable("Unable to convert function"); 6550 } 6551 6552 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6553 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6554 if (!FnInfo) 6555 return 0; 6556 6557 switch (FDecl->getBuiltinID()) { 6558 default: 6559 return 0; 6560 case Builtin::BI__builtin_abs: 6561 case Builtin::BI__builtin_fabs: 6562 case Builtin::BI__builtin_fabsf: 6563 case Builtin::BI__builtin_fabsl: 6564 case Builtin::BI__builtin_labs: 6565 case Builtin::BI__builtin_llabs: 6566 case Builtin::BI__builtin_cabs: 6567 case Builtin::BI__builtin_cabsf: 6568 case Builtin::BI__builtin_cabsl: 6569 case Builtin::BIabs: 6570 case Builtin::BIlabs: 6571 case Builtin::BIllabs: 6572 case Builtin::BIfabs: 6573 case Builtin::BIfabsf: 6574 case Builtin::BIfabsl: 6575 case Builtin::BIcabs: 6576 case Builtin::BIcabsf: 6577 case Builtin::BIcabsl: 6578 return FDecl->getBuiltinID(); 6579 } 6580 llvm_unreachable("Unknown Builtin type"); 6581 } 6582 6583 // If the replacement is valid, emit a note with replacement function. 6584 // Additionally, suggest including the proper header if not already included. 6585 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6586 unsigned AbsKind, QualType ArgType) { 6587 bool EmitHeaderHint = true; 6588 const char *HeaderName = nullptr; 6589 const char *FunctionName = nullptr; 6590 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6591 FunctionName = "std::abs"; 6592 if (ArgType->isIntegralOrEnumerationType()) { 6593 HeaderName = "cstdlib"; 6594 } else if (ArgType->isRealFloatingType()) { 6595 HeaderName = "cmath"; 6596 } else { 6597 llvm_unreachable("Invalid Type"); 6598 } 6599 6600 // Lookup all std::abs 6601 if (NamespaceDecl *Std = S.getStdNamespace()) { 6602 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6603 R.suppressDiagnostics(); 6604 S.LookupQualifiedName(R, Std); 6605 6606 for (const auto *I : R) { 6607 const FunctionDecl *FDecl = nullptr; 6608 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6609 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6610 } else { 6611 FDecl = dyn_cast<FunctionDecl>(I); 6612 } 6613 if (!FDecl) 6614 continue; 6615 6616 // Found std::abs(), check that they are the right ones. 6617 if (FDecl->getNumParams() != 1) 6618 continue; 6619 6620 // Check that the parameter type can handle the argument. 6621 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6622 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6623 S.Context.getTypeSize(ArgType) <= 6624 S.Context.getTypeSize(ParamType)) { 6625 // Found a function, don't need the header hint. 6626 EmitHeaderHint = false; 6627 break; 6628 } 6629 } 6630 } 6631 } else { 6632 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6633 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6634 6635 if (HeaderName) { 6636 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6637 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6638 R.suppressDiagnostics(); 6639 S.LookupName(R, S.getCurScope()); 6640 6641 if (R.isSingleResult()) { 6642 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6643 if (FD && FD->getBuiltinID() == AbsKind) { 6644 EmitHeaderHint = false; 6645 } else { 6646 return; 6647 } 6648 } else if (!R.empty()) { 6649 return; 6650 } 6651 } 6652 } 6653 6654 S.Diag(Loc, diag::note_replace_abs_function) 6655 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 6656 6657 if (!HeaderName) 6658 return; 6659 6660 if (!EmitHeaderHint) 6661 return; 6662 6663 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 6664 << FunctionName; 6665 } 6666 6667 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) { 6668 if (!FDecl) 6669 return false; 6670 6671 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs")) 6672 return false; 6673 6674 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext()); 6675 6676 while (ND && ND->isInlineNamespace()) { 6677 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext()); 6678 } 6679 6680 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std")) 6681 return false; 6682 6683 if (!isa<TranslationUnitDecl>(ND->getDeclContext())) 6684 return false; 6685 6686 return true; 6687 } 6688 6689 // Warn when using the wrong abs() function. 6690 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 6691 const FunctionDecl *FDecl, 6692 IdentifierInfo *FnInfo) { 6693 if (Call->getNumArgs() != 1) 6694 return; 6695 6696 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 6697 bool IsStdAbs = IsFunctionStdAbs(FDecl); 6698 if (AbsKind == 0 && !IsStdAbs) 6699 return; 6700 6701 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6702 QualType ParamType = Call->getArg(0)->getType(); 6703 6704 // Unsigned types cannot be negative. Suggest removing the absolute value 6705 // function call. 6706 if (ArgType->isUnsignedIntegerType()) { 6707 const char *FunctionName = 6708 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 6709 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 6710 Diag(Call->getExprLoc(), diag::note_remove_abs) 6711 << FunctionName 6712 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 6713 return; 6714 } 6715 6716 // Taking the absolute value of a pointer is very suspicious, they probably 6717 // wanted to index into an array, dereference a pointer, call a function, etc. 6718 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 6719 unsigned DiagType = 0; 6720 if (ArgType->isFunctionType()) 6721 DiagType = 1; 6722 else if (ArgType->isArrayType()) 6723 DiagType = 2; 6724 6725 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 6726 return; 6727 } 6728 6729 // std::abs has overloads which prevent most of the absolute value problems 6730 // from occurring. 6731 if (IsStdAbs) 6732 return; 6733 6734 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 6735 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 6736 6737 // The argument and parameter are the same kind. Check if they are the right 6738 // size. 6739 if (ArgValueKind == ParamValueKind) { 6740 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 6741 return; 6742 6743 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 6744 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 6745 << FDecl << ArgType << ParamType; 6746 6747 if (NewAbsKind == 0) 6748 return; 6749 6750 emitReplacement(*this, Call->getExprLoc(), 6751 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6752 return; 6753 } 6754 6755 // ArgValueKind != ParamValueKind 6756 // The wrong type of absolute value function was used. Attempt to find the 6757 // proper one. 6758 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 6759 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 6760 if (NewAbsKind == 0) 6761 return; 6762 6763 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 6764 << FDecl << ParamValueKind << ArgValueKind; 6765 6766 emitReplacement(*this, Call->getExprLoc(), 6767 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6768 } 6769 6770 //===--- CHECK: Standard memory functions ---------------------------------===// 6771 6772 /// \brief Takes the expression passed to the size_t parameter of functions 6773 /// such as memcmp, strncat, etc and warns if it's a comparison. 6774 /// 6775 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 6776 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 6777 IdentifierInfo *FnName, 6778 SourceLocation FnLoc, 6779 SourceLocation RParenLoc) { 6780 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 6781 if (!Size) 6782 return false; 6783 6784 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 6785 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 6786 return false; 6787 6788 SourceRange SizeRange = Size->getSourceRange(); 6789 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 6790 << SizeRange << FnName; 6791 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 6792 << FnName << FixItHint::CreateInsertion( 6793 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 6794 << FixItHint::CreateRemoval(RParenLoc); 6795 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 6796 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 6797 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 6798 ")"); 6799 6800 return true; 6801 } 6802 6803 /// \brief Determine whether the given type is or contains a dynamic class type 6804 /// (e.g., whether it has a vtable). 6805 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 6806 bool &IsContained) { 6807 // Look through array types while ignoring qualifiers. 6808 const Type *Ty = T->getBaseElementTypeUnsafe(); 6809 IsContained = false; 6810 6811 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 6812 RD = RD ? RD->getDefinition() : nullptr; 6813 if (!RD || RD->isInvalidDecl()) 6814 return nullptr; 6815 6816 if (RD->isDynamicClass()) 6817 return RD; 6818 6819 // Check all the fields. If any bases were dynamic, the class is dynamic. 6820 // It's impossible for a class to transitively contain itself by value, so 6821 // infinite recursion is impossible. 6822 for (auto *FD : RD->fields()) { 6823 bool SubContained; 6824 if (const CXXRecordDecl *ContainedRD = 6825 getContainedDynamicClass(FD->getType(), SubContained)) { 6826 IsContained = true; 6827 return ContainedRD; 6828 } 6829 } 6830 6831 return nullptr; 6832 } 6833 6834 /// \brief If E is a sizeof expression, returns its argument expression, 6835 /// otherwise returns NULL. 6836 static const Expr *getSizeOfExprArg(const Expr *E) { 6837 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6838 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6839 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 6840 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 6841 6842 return nullptr; 6843 } 6844 6845 /// \brief If E is a sizeof expression, returns its argument type. 6846 static QualType getSizeOfArgType(const Expr *E) { 6847 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6848 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6849 if (SizeOf->getKind() == clang::UETT_SizeOf) 6850 return SizeOf->getTypeOfArgument(); 6851 6852 return QualType(); 6853 } 6854 6855 /// \brief Check for dangerous or invalid arguments to memset(). 6856 /// 6857 /// This issues warnings on known problematic, dangerous or unspecified 6858 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 6859 /// function calls. 6860 /// 6861 /// \param Call The call expression to diagnose. 6862 void Sema::CheckMemaccessArguments(const CallExpr *Call, 6863 unsigned BId, 6864 IdentifierInfo *FnName) { 6865 assert(BId != 0); 6866 6867 // It is possible to have a non-standard definition of memset. Validate 6868 // we have enough arguments, and if not, abort further checking. 6869 unsigned ExpectedNumArgs = 6870 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 6871 if (Call->getNumArgs() < ExpectedNumArgs) 6872 return; 6873 6874 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 6875 BId == Builtin::BIstrndup ? 1 : 2); 6876 unsigned LenArg = 6877 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 6878 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 6879 6880 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 6881 Call->getLocStart(), Call->getRParenLoc())) 6882 return; 6883 6884 // We have special checking when the length is a sizeof expression. 6885 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 6886 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 6887 llvm::FoldingSetNodeID SizeOfArgID; 6888 6889 // Although widely used, 'bzero' is not a standard function. Be more strict 6890 // with the argument types before allowing diagnostics and only allow the 6891 // form bzero(ptr, sizeof(...)). 6892 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6893 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 6894 return; 6895 6896 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 6897 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 6898 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 6899 6900 QualType DestTy = Dest->getType(); 6901 QualType PointeeTy; 6902 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 6903 PointeeTy = DestPtrTy->getPointeeType(); 6904 6905 // Never warn about void type pointers. This can be used to suppress 6906 // false positives. 6907 if (PointeeTy->isVoidType()) 6908 continue; 6909 6910 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 6911 // actually comparing the expressions for equality. Because computing the 6912 // expression IDs can be expensive, we only do this if the diagnostic is 6913 // enabled. 6914 if (SizeOfArg && 6915 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 6916 SizeOfArg->getExprLoc())) { 6917 // We only compute IDs for expressions if the warning is enabled, and 6918 // cache the sizeof arg's ID. 6919 if (SizeOfArgID == llvm::FoldingSetNodeID()) 6920 SizeOfArg->Profile(SizeOfArgID, Context, true); 6921 llvm::FoldingSetNodeID DestID; 6922 Dest->Profile(DestID, Context, true); 6923 if (DestID == SizeOfArgID) { 6924 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 6925 // over sizeof(src) as well. 6926 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 6927 StringRef ReadableName = FnName->getName(); 6928 6929 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 6930 if (UnaryOp->getOpcode() == UO_AddrOf) 6931 ActionIdx = 1; // If its an address-of operator, just remove it. 6932 if (!PointeeTy->isIncompleteType() && 6933 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 6934 ActionIdx = 2; // If the pointee's size is sizeof(char), 6935 // suggest an explicit length. 6936 6937 // If the function is defined as a builtin macro, do not show macro 6938 // expansion. 6939 SourceLocation SL = SizeOfArg->getExprLoc(); 6940 SourceRange DSR = Dest->getSourceRange(); 6941 SourceRange SSR = SizeOfArg->getSourceRange(); 6942 SourceManager &SM = getSourceManager(); 6943 6944 if (SM.isMacroArgExpansion(SL)) { 6945 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 6946 SL = SM.getSpellingLoc(SL); 6947 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 6948 SM.getSpellingLoc(DSR.getEnd())); 6949 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 6950 SM.getSpellingLoc(SSR.getEnd())); 6951 } 6952 6953 DiagRuntimeBehavior(SL, SizeOfArg, 6954 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 6955 << ReadableName 6956 << PointeeTy 6957 << DestTy 6958 << DSR 6959 << SSR); 6960 DiagRuntimeBehavior(SL, SizeOfArg, 6961 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 6962 << ActionIdx 6963 << SSR); 6964 6965 break; 6966 } 6967 } 6968 6969 // Also check for cases where the sizeof argument is the exact same 6970 // type as the memory argument, and where it points to a user-defined 6971 // record type. 6972 if (SizeOfArgTy != QualType()) { 6973 if (PointeeTy->isRecordType() && 6974 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 6975 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 6976 PDiag(diag::warn_sizeof_pointer_type_memaccess) 6977 << FnName << SizeOfArgTy << ArgIdx 6978 << PointeeTy << Dest->getSourceRange() 6979 << LenExpr->getSourceRange()); 6980 break; 6981 } 6982 } 6983 } else if (DestTy->isArrayType()) { 6984 PointeeTy = DestTy; 6985 } 6986 6987 if (PointeeTy == QualType()) 6988 continue; 6989 6990 // Always complain about dynamic classes. 6991 bool IsContained; 6992 if (const CXXRecordDecl *ContainedRD = 6993 getContainedDynamicClass(PointeeTy, IsContained)) { 6994 6995 unsigned OperationType = 0; 6996 // "overwritten" if we're warning about the destination for any call 6997 // but memcmp; otherwise a verb appropriate to the call. 6998 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 6999 if (BId == Builtin::BImemcpy) 7000 OperationType = 1; 7001 else if(BId == Builtin::BImemmove) 7002 OperationType = 2; 7003 else if (BId == Builtin::BImemcmp) 7004 OperationType = 3; 7005 } 7006 7007 DiagRuntimeBehavior( 7008 Dest->getExprLoc(), Dest, 7009 PDiag(diag::warn_dyn_class_memaccess) 7010 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7011 << FnName << IsContained << ContainedRD << OperationType 7012 << Call->getCallee()->getSourceRange()); 7013 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7014 BId != Builtin::BImemset) 7015 DiagRuntimeBehavior( 7016 Dest->getExprLoc(), Dest, 7017 PDiag(diag::warn_arc_object_memaccess) 7018 << ArgIdx << FnName << PointeeTy 7019 << Call->getCallee()->getSourceRange()); 7020 else 7021 continue; 7022 7023 DiagRuntimeBehavior( 7024 Dest->getExprLoc(), Dest, 7025 PDiag(diag::note_bad_memaccess_silence) 7026 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7027 break; 7028 } 7029 } 7030 7031 // A little helper routine: ignore addition and subtraction of integer literals. 7032 // This intentionally does not ignore all integer constant expressions because 7033 // we don't want to remove sizeof(). 7034 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7035 Ex = Ex->IgnoreParenCasts(); 7036 7037 for (;;) { 7038 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7039 if (!BO || !BO->isAdditiveOp()) 7040 break; 7041 7042 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7043 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7044 7045 if (isa<IntegerLiteral>(RHS)) 7046 Ex = LHS; 7047 else if (isa<IntegerLiteral>(LHS)) 7048 Ex = RHS; 7049 else 7050 break; 7051 } 7052 7053 return Ex; 7054 } 7055 7056 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7057 ASTContext &Context) { 7058 // Only handle constant-sized or VLAs, but not flexible members. 7059 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7060 // Only issue the FIXIT for arrays of size > 1. 7061 if (CAT->getSize().getSExtValue() <= 1) 7062 return false; 7063 } else if (!Ty->isVariableArrayType()) { 7064 return false; 7065 } 7066 return true; 7067 } 7068 7069 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7070 // be the size of the source, instead of the destination. 7071 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7072 IdentifierInfo *FnName) { 7073 7074 // Don't crash if the user has the wrong number of arguments 7075 unsigned NumArgs = Call->getNumArgs(); 7076 if ((NumArgs != 3) && (NumArgs != 4)) 7077 return; 7078 7079 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7080 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7081 const Expr *CompareWithSrc = nullptr; 7082 7083 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7084 Call->getLocStart(), Call->getRParenLoc())) 7085 return; 7086 7087 // Look for 'strlcpy(dst, x, sizeof(x))' 7088 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7089 CompareWithSrc = Ex; 7090 else { 7091 // Look for 'strlcpy(dst, x, strlen(x))' 7092 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7093 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7094 SizeCall->getNumArgs() == 1) 7095 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7096 } 7097 } 7098 7099 if (!CompareWithSrc) 7100 return; 7101 7102 // Determine if the argument to sizeof/strlen is equal to the source 7103 // argument. In principle there's all kinds of things you could do 7104 // here, for instance creating an == expression and evaluating it with 7105 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7106 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7107 if (!SrcArgDRE) 7108 return; 7109 7110 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7111 if (!CompareWithSrcDRE || 7112 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7113 return; 7114 7115 const Expr *OriginalSizeArg = Call->getArg(2); 7116 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7117 << OriginalSizeArg->getSourceRange() << FnName; 7118 7119 // Output a FIXIT hint if the destination is an array (rather than a 7120 // pointer to an array). This could be enhanced to handle some 7121 // pointers if we know the actual size, like if DstArg is 'array+2' 7122 // we could say 'sizeof(array)-2'. 7123 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7124 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7125 return; 7126 7127 SmallString<128> sizeString; 7128 llvm::raw_svector_ostream OS(sizeString); 7129 OS << "sizeof("; 7130 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7131 OS << ")"; 7132 7133 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7134 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7135 OS.str()); 7136 } 7137 7138 /// Check if two expressions refer to the same declaration. 7139 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7140 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7141 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7142 return D1->getDecl() == D2->getDecl(); 7143 return false; 7144 } 7145 7146 static const Expr *getStrlenExprArg(const Expr *E) { 7147 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7148 const FunctionDecl *FD = CE->getDirectCallee(); 7149 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7150 return nullptr; 7151 return CE->getArg(0)->IgnoreParenCasts(); 7152 } 7153 return nullptr; 7154 } 7155 7156 // Warn on anti-patterns as the 'size' argument to strncat. 7157 // The correct size argument should look like following: 7158 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7159 void Sema::CheckStrncatArguments(const CallExpr *CE, 7160 IdentifierInfo *FnName) { 7161 // Don't crash if the user has the wrong number of arguments. 7162 if (CE->getNumArgs() < 3) 7163 return; 7164 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7165 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7166 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7167 7168 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7169 CE->getRParenLoc())) 7170 return; 7171 7172 // Identify common expressions, which are wrongly used as the size argument 7173 // to strncat and may lead to buffer overflows. 7174 unsigned PatternType = 0; 7175 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7176 // - sizeof(dst) 7177 if (referToTheSameDecl(SizeOfArg, DstArg)) 7178 PatternType = 1; 7179 // - sizeof(src) 7180 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7181 PatternType = 2; 7182 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7183 if (BE->getOpcode() == BO_Sub) { 7184 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7185 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7186 // - sizeof(dst) - strlen(dst) 7187 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7188 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7189 PatternType = 1; 7190 // - sizeof(src) - (anything) 7191 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7192 PatternType = 2; 7193 } 7194 } 7195 7196 if (PatternType == 0) 7197 return; 7198 7199 // Generate the diagnostic. 7200 SourceLocation SL = LenArg->getLocStart(); 7201 SourceRange SR = LenArg->getSourceRange(); 7202 SourceManager &SM = getSourceManager(); 7203 7204 // If the function is defined as a builtin macro, do not show macro expansion. 7205 if (SM.isMacroArgExpansion(SL)) { 7206 SL = SM.getSpellingLoc(SL); 7207 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7208 SM.getSpellingLoc(SR.getEnd())); 7209 } 7210 7211 // Check if the destination is an array (rather than a pointer to an array). 7212 QualType DstTy = DstArg->getType(); 7213 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7214 Context); 7215 if (!isKnownSizeArray) { 7216 if (PatternType == 1) 7217 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7218 else 7219 Diag(SL, diag::warn_strncat_src_size) << SR; 7220 return; 7221 } 7222 7223 if (PatternType == 1) 7224 Diag(SL, diag::warn_strncat_large_size) << SR; 7225 else 7226 Diag(SL, diag::warn_strncat_src_size) << SR; 7227 7228 SmallString<128> sizeString; 7229 llvm::raw_svector_ostream OS(sizeString); 7230 OS << "sizeof("; 7231 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7232 OS << ") - "; 7233 OS << "strlen("; 7234 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7235 OS << ") - 1"; 7236 7237 Diag(SL, diag::note_strncat_wrong_size) 7238 << FixItHint::CreateReplacement(SR, OS.str()); 7239 } 7240 7241 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7242 7243 static const Expr *EvalVal(const Expr *E, 7244 SmallVectorImpl<const DeclRefExpr *> &refVars, 7245 const Decl *ParentDecl); 7246 static const Expr *EvalAddr(const Expr *E, 7247 SmallVectorImpl<const DeclRefExpr *> &refVars, 7248 const Decl *ParentDecl); 7249 7250 /// CheckReturnStackAddr - Check if a return statement returns the address 7251 /// of a stack variable. 7252 static void 7253 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7254 SourceLocation ReturnLoc) { 7255 7256 const Expr *stackE = nullptr; 7257 SmallVector<const DeclRefExpr *, 8> refVars; 7258 7259 // Perform checking for returned stack addresses, local blocks, 7260 // label addresses or references to temporaries. 7261 if (lhsType->isPointerType() || 7262 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7263 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7264 } else if (lhsType->isReferenceType()) { 7265 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7266 } 7267 7268 if (!stackE) 7269 return; // Nothing suspicious was found. 7270 7271 // Parameters are initalized in the calling scope, so taking the address 7272 // of a parameter reference doesn't need a warning. 7273 for (auto *DRE : refVars) 7274 if (isa<ParmVarDecl>(DRE->getDecl())) 7275 return; 7276 7277 SourceLocation diagLoc; 7278 SourceRange diagRange; 7279 if (refVars.empty()) { 7280 diagLoc = stackE->getLocStart(); 7281 diagRange = stackE->getSourceRange(); 7282 } else { 7283 // We followed through a reference variable. 'stackE' contains the 7284 // problematic expression but we will warn at the return statement pointing 7285 // at the reference variable. We will later display the "trail" of 7286 // reference variables using notes. 7287 diagLoc = refVars[0]->getLocStart(); 7288 diagRange = refVars[0]->getSourceRange(); 7289 } 7290 7291 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7292 // address of local var 7293 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7294 << DR->getDecl()->getDeclName() << diagRange; 7295 } else if (isa<BlockExpr>(stackE)) { // local block. 7296 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7297 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7298 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7299 } else { // local temporary. 7300 // If there is an LValue->RValue conversion, then the value of the 7301 // reference type is used, not the reference. 7302 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7303 if (ICE->getCastKind() == CK_LValueToRValue) { 7304 return; 7305 } 7306 } 7307 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7308 << lhsType->isReferenceType() << diagRange; 7309 } 7310 7311 // Display the "trail" of reference variables that we followed until we 7312 // found the problematic expression using notes. 7313 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7314 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7315 // If this var binds to another reference var, show the range of the next 7316 // var, otherwise the var binds to the problematic expression, in which case 7317 // show the range of the expression. 7318 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7319 : stackE->getSourceRange(); 7320 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7321 << VD->getDeclName() << range; 7322 } 7323 } 7324 7325 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7326 /// check if the expression in a return statement evaluates to an address 7327 /// to a location on the stack, a local block, an address of a label, or a 7328 /// reference to local temporary. The recursion is used to traverse the 7329 /// AST of the return expression, with recursion backtracking when we 7330 /// encounter a subexpression that (1) clearly does not lead to one of the 7331 /// above problematic expressions (2) is something we cannot determine leads to 7332 /// a problematic expression based on such local checking. 7333 /// 7334 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7335 /// the expression that they point to. Such variables are added to the 7336 /// 'refVars' vector so that we know what the reference variable "trail" was. 7337 /// 7338 /// EvalAddr processes expressions that are pointers that are used as 7339 /// references (and not L-values). EvalVal handles all other values. 7340 /// At the base case of the recursion is a check for the above problematic 7341 /// expressions. 7342 /// 7343 /// This implementation handles: 7344 /// 7345 /// * pointer-to-pointer casts 7346 /// * implicit conversions from array references to pointers 7347 /// * taking the address of fields 7348 /// * arbitrary interplay between "&" and "*" operators 7349 /// * pointer arithmetic from an address of a stack variable 7350 /// * taking the address of an array element where the array is on the stack 7351 static const Expr *EvalAddr(const Expr *E, 7352 SmallVectorImpl<const DeclRefExpr *> &refVars, 7353 const Decl *ParentDecl) { 7354 if (E->isTypeDependent()) 7355 return nullptr; 7356 7357 // We should only be called for evaluating pointer expressions. 7358 assert((E->getType()->isAnyPointerType() || 7359 E->getType()->isBlockPointerType() || 7360 E->getType()->isObjCQualifiedIdType()) && 7361 "EvalAddr only works on pointers"); 7362 7363 E = E->IgnoreParens(); 7364 7365 // Our "symbolic interpreter" is just a dispatch off the currently 7366 // viewed AST node. We then recursively traverse the AST by calling 7367 // EvalAddr and EvalVal appropriately. 7368 switch (E->getStmtClass()) { 7369 case Stmt::DeclRefExprClass: { 7370 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7371 7372 // If we leave the immediate function, the lifetime isn't about to end. 7373 if (DR->refersToEnclosingVariableOrCapture()) 7374 return nullptr; 7375 7376 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7377 // If this is a reference variable, follow through to the expression that 7378 // it points to. 7379 if (V->hasLocalStorage() && 7380 V->getType()->isReferenceType() && V->hasInit()) { 7381 // Add the reference variable to the "trail". 7382 refVars.push_back(DR); 7383 return EvalAddr(V->getInit(), refVars, ParentDecl); 7384 } 7385 7386 return nullptr; 7387 } 7388 7389 case Stmt::UnaryOperatorClass: { 7390 // The only unary operator that make sense to handle here 7391 // is AddrOf. All others don't make sense as pointers. 7392 const UnaryOperator *U = cast<UnaryOperator>(E); 7393 7394 if (U->getOpcode() == UO_AddrOf) 7395 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7396 return nullptr; 7397 } 7398 7399 case Stmt::BinaryOperatorClass: { 7400 // Handle pointer arithmetic. All other binary operators are not valid 7401 // in this context. 7402 const BinaryOperator *B = cast<BinaryOperator>(E); 7403 BinaryOperatorKind op = B->getOpcode(); 7404 7405 if (op != BO_Add && op != BO_Sub) 7406 return nullptr; 7407 7408 const Expr *Base = B->getLHS(); 7409 7410 // Determine which argument is the real pointer base. It could be 7411 // the RHS argument instead of the LHS. 7412 if (!Base->getType()->isPointerType()) 7413 Base = B->getRHS(); 7414 7415 assert(Base->getType()->isPointerType()); 7416 return EvalAddr(Base, refVars, ParentDecl); 7417 } 7418 7419 // For conditional operators we need to see if either the LHS or RHS are 7420 // valid DeclRefExpr*s. If one of them is valid, we return it. 7421 case Stmt::ConditionalOperatorClass: { 7422 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7423 7424 // Handle the GNU extension for missing LHS. 7425 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7426 if (const Expr *LHSExpr = C->getLHS()) { 7427 // In C++, we can have a throw-expression, which has 'void' type. 7428 if (!LHSExpr->getType()->isVoidType()) 7429 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7430 return LHS; 7431 } 7432 7433 // In C++, we can have a throw-expression, which has 'void' type. 7434 if (C->getRHS()->getType()->isVoidType()) 7435 return nullptr; 7436 7437 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7438 } 7439 7440 case Stmt::BlockExprClass: 7441 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7442 return E; // local block. 7443 return nullptr; 7444 7445 case Stmt::AddrLabelExprClass: 7446 return E; // address of label. 7447 7448 case Stmt::ExprWithCleanupsClass: 7449 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7450 ParentDecl); 7451 7452 // For casts, we need to handle conversions from arrays to 7453 // pointer values, and pointer-to-pointer conversions. 7454 case Stmt::ImplicitCastExprClass: 7455 case Stmt::CStyleCastExprClass: 7456 case Stmt::CXXFunctionalCastExprClass: 7457 case Stmt::ObjCBridgedCastExprClass: 7458 case Stmt::CXXStaticCastExprClass: 7459 case Stmt::CXXDynamicCastExprClass: 7460 case Stmt::CXXConstCastExprClass: 7461 case Stmt::CXXReinterpretCastExprClass: { 7462 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7463 switch (cast<CastExpr>(E)->getCastKind()) { 7464 case CK_LValueToRValue: 7465 case CK_NoOp: 7466 case CK_BaseToDerived: 7467 case CK_DerivedToBase: 7468 case CK_UncheckedDerivedToBase: 7469 case CK_Dynamic: 7470 case CK_CPointerToObjCPointerCast: 7471 case CK_BlockPointerToObjCPointerCast: 7472 case CK_AnyPointerToBlockPointerCast: 7473 return EvalAddr(SubExpr, refVars, ParentDecl); 7474 7475 case CK_ArrayToPointerDecay: 7476 return EvalVal(SubExpr, refVars, ParentDecl); 7477 7478 case CK_BitCast: 7479 if (SubExpr->getType()->isAnyPointerType() || 7480 SubExpr->getType()->isBlockPointerType() || 7481 SubExpr->getType()->isObjCQualifiedIdType()) 7482 return EvalAddr(SubExpr, refVars, ParentDecl); 7483 else 7484 return nullptr; 7485 7486 default: 7487 return nullptr; 7488 } 7489 } 7490 7491 case Stmt::MaterializeTemporaryExprClass: 7492 if (const Expr *Result = 7493 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7494 refVars, ParentDecl)) 7495 return Result; 7496 return E; 7497 7498 // Everything else: we simply don't reason about them. 7499 default: 7500 return nullptr; 7501 } 7502 } 7503 7504 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7505 /// See the comments for EvalAddr for more details. 7506 static const Expr *EvalVal(const Expr *E, 7507 SmallVectorImpl<const DeclRefExpr *> &refVars, 7508 const Decl *ParentDecl) { 7509 do { 7510 // We should only be called for evaluating non-pointer expressions, or 7511 // expressions with a pointer type that are not used as references but 7512 // instead 7513 // are l-values (e.g., DeclRefExpr with a pointer type). 7514 7515 // Our "symbolic interpreter" is just a dispatch off the currently 7516 // viewed AST node. We then recursively traverse the AST by calling 7517 // EvalAddr and EvalVal appropriately. 7518 7519 E = E->IgnoreParens(); 7520 switch (E->getStmtClass()) { 7521 case Stmt::ImplicitCastExprClass: { 7522 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7523 if (IE->getValueKind() == VK_LValue) { 7524 E = IE->getSubExpr(); 7525 continue; 7526 } 7527 return nullptr; 7528 } 7529 7530 case Stmt::ExprWithCleanupsClass: 7531 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7532 ParentDecl); 7533 7534 case Stmt::DeclRefExprClass: { 7535 // When we hit a DeclRefExpr we are looking at code that refers to a 7536 // variable's name. If it's not a reference variable we check if it has 7537 // local storage within the function, and if so, return the expression. 7538 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7539 7540 // If we leave the immediate function, the lifetime isn't about to end. 7541 if (DR->refersToEnclosingVariableOrCapture()) 7542 return nullptr; 7543 7544 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7545 // Check if it refers to itself, e.g. "int& i = i;". 7546 if (V == ParentDecl) 7547 return DR; 7548 7549 if (V->hasLocalStorage()) { 7550 if (!V->getType()->isReferenceType()) 7551 return DR; 7552 7553 // Reference variable, follow through to the expression that 7554 // it points to. 7555 if (V->hasInit()) { 7556 // Add the reference variable to the "trail". 7557 refVars.push_back(DR); 7558 return EvalVal(V->getInit(), refVars, V); 7559 } 7560 } 7561 } 7562 7563 return nullptr; 7564 } 7565 7566 case Stmt::UnaryOperatorClass: { 7567 // The only unary operator that make sense to handle here 7568 // is Deref. All others don't resolve to a "name." This includes 7569 // handling all sorts of rvalues passed to a unary operator. 7570 const UnaryOperator *U = cast<UnaryOperator>(E); 7571 7572 if (U->getOpcode() == UO_Deref) 7573 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7574 7575 return nullptr; 7576 } 7577 7578 case Stmt::ArraySubscriptExprClass: { 7579 // Array subscripts are potential references to data on the stack. We 7580 // retrieve the DeclRefExpr* for the array variable if it indeed 7581 // has local storage. 7582 const auto *ASE = cast<ArraySubscriptExpr>(E); 7583 if (ASE->isTypeDependent()) 7584 return nullptr; 7585 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7586 } 7587 7588 case Stmt::OMPArraySectionExprClass: { 7589 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7590 ParentDecl); 7591 } 7592 7593 case Stmt::ConditionalOperatorClass: { 7594 // For conditional operators we need to see if either the LHS or RHS are 7595 // non-NULL Expr's. If one is non-NULL, we return it. 7596 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7597 7598 // Handle the GNU extension for missing LHS. 7599 if (const Expr *LHSExpr = C->getLHS()) { 7600 // In C++, we can have a throw-expression, which has 'void' type. 7601 if (!LHSExpr->getType()->isVoidType()) 7602 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 7603 return LHS; 7604 } 7605 7606 // In C++, we can have a throw-expression, which has 'void' type. 7607 if (C->getRHS()->getType()->isVoidType()) 7608 return nullptr; 7609 7610 return EvalVal(C->getRHS(), refVars, ParentDecl); 7611 } 7612 7613 // Accesses to members are potential references to data on the stack. 7614 case Stmt::MemberExprClass: { 7615 const MemberExpr *M = cast<MemberExpr>(E); 7616 7617 // Check for indirect access. We only want direct field accesses. 7618 if (M->isArrow()) 7619 return nullptr; 7620 7621 // Check whether the member type is itself a reference, in which case 7622 // we're not going to refer to the member, but to what the member refers 7623 // to. 7624 if (M->getMemberDecl()->getType()->isReferenceType()) 7625 return nullptr; 7626 7627 return EvalVal(M->getBase(), refVars, ParentDecl); 7628 } 7629 7630 case Stmt::MaterializeTemporaryExprClass: 7631 if (const Expr *Result = 7632 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7633 refVars, ParentDecl)) 7634 return Result; 7635 return E; 7636 7637 default: 7638 // Check that we don't return or take the address of a reference to a 7639 // temporary. This is only useful in C++. 7640 if (!E->isTypeDependent() && E->isRValue()) 7641 return E; 7642 7643 // Everything else: we simply don't reason about them. 7644 return nullptr; 7645 } 7646 } while (true); 7647 } 7648 7649 void 7650 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 7651 SourceLocation ReturnLoc, 7652 bool isObjCMethod, 7653 const AttrVec *Attrs, 7654 const FunctionDecl *FD) { 7655 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 7656 7657 // Check if the return value is null but should not be. 7658 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 7659 (!isObjCMethod && isNonNullType(Context, lhsType))) && 7660 CheckNonNullExpr(*this, RetValExp)) 7661 Diag(ReturnLoc, diag::warn_null_ret) 7662 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 7663 7664 // C++11 [basic.stc.dynamic.allocation]p4: 7665 // If an allocation function declared with a non-throwing 7666 // exception-specification fails to allocate storage, it shall return 7667 // a null pointer. Any other allocation function that fails to allocate 7668 // storage shall indicate failure only by throwing an exception [...] 7669 if (FD) { 7670 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 7671 if (Op == OO_New || Op == OO_Array_New) { 7672 const FunctionProtoType *Proto 7673 = FD->getType()->castAs<FunctionProtoType>(); 7674 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 7675 CheckNonNullExpr(*this, RetValExp)) 7676 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 7677 << FD << getLangOpts().CPlusPlus11; 7678 } 7679 } 7680 } 7681 7682 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 7683 7684 /// Check for comparisons of floating point operands using != and ==. 7685 /// Issue a warning if these are no self-comparisons, as they are not likely 7686 /// to do what the programmer intended. 7687 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 7688 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 7689 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 7690 7691 // Special case: check for x == x (which is OK). 7692 // Do not emit warnings for such cases. 7693 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 7694 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 7695 if (DRL->getDecl() == DRR->getDecl()) 7696 return; 7697 7698 // Special case: check for comparisons against literals that can be exactly 7699 // represented by APFloat. In such cases, do not emit a warning. This 7700 // is a heuristic: often comparison against such literals are used to 7701 // detect if a value in a variable has not changed. This clearly can 7702 // lead to false negatives. 7703 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 7704 if (FLL->isExact()) 7705 return; 7706 } else 7707 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 7708 if (FLR->isExact()) 7709 return; 7710 7711 // Check for comparisons with builtin types. 7712 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 7713 if (CL->getBuiltinCallee()) 7714 return; 7715 7716 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 7717 if (CR->getBuiltinCallee()) 7718 return; 7719 7720 // Emit the diagnostic. 7721 Diag(Loc, diag::warn_floatingpoint_eq) 7722 << LHS->getSourceRange() << RHS->getSourceRange(); 7723 } 7724 7725 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 7726 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 7727 7728 namespace { 7729 7730 /// Structure recording the 'active' range of an integer-valued 7731 /// expression. 7732 struct IntRange { 7733 /// The number of bits active in the int. 7734 unsigned Width; 7735 7736 /// True if the int is known not to have negative values. 7737 bool NonNegative; 7738 7739 IntRange(unsigned Width, bool NonNegative) 7740 : Width(Width), NonNegative(NonNegative) 7741 {} 7742 7743 /// Returns the range of the bool type. 7744 static IntRange forBoolType() { 7745 return IntRange(1, true); 7746 } 7747 7748 /// Returns the range of an opaque value of the given integral type. 7749 static IntRange forValueOfType(ASTContext &C, QualType T) { 7750 return forValueOfCanonicalType(C, 7751 T->getCanonicalTypeInternal().getTypePtr()); 7752 } 7753 7754 /// Returns the range of an opaque value of a canonical integral type. 7755 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 7756 assert(T->isCanonicalUnqualified()); 7757 7758 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7759 T = VT->getElementType().getTypePtr(); 7760 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7761 T = CT->getElementType().getTypePtr(); 7762 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7763 T = AT->getValueType().getTypePtr(); 7764 7765 // For enum types, use the known bit width of the enumerators. 7766 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 7767 EnumDecl *Enum = ET->getDecl(); 7768 if (!Enum->isCompleteDefinition()) 7769 return IntRange(C.getIntWidth(QualType(T, 0)), false); 7770 7771 unsigned NumPositive = Enum->getNumPositiveBits(); 7772 unsigned NumNegative = Enum->getNumNegativeBits(); 7773 7774 if (NumNegative == 0) 7775 return IntRange(NumPositive, true/*NonNegative*/); 7776 else 7777 return IntRange(std::max(NumPositive + 1, NumNegative), 7778 false/*NonNegative*/); 7779 } 7780 7781 const BuiltinType *BT = cast<BuiltinType>(T); 7782 assert(BT->isInteger()); 7783 7784 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7785 } 7786 7787 /// Returns the "target" range of a canonical integral type, i.e. 7788 /// the range of values expressible in the type. 7789 /// 7790 /// This matches forValueOfCanonicalType except that enums have the 7791 /// full range of their type, not the range of their enumerators. 7792 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 7793 assert(T->isCanonicalUnqualified()); 7794 7795 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7796 T = VT->getElementType().getTypePtr(); 7797 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7798 T = CT->getElementType().getTypePtr(); 7799 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7800 T = AT->getValueType().getTypePtr(); 7801 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7802 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 7803 7804 const BuiltinType *BT = cast<BuiltinType>(T); 7805 assert(BT->isInteger()); 7806 7807 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7808 } 7809 7810 /// Returns the supremum of two ranges: i.e. their conservative merge. 7811 static IntRange join(IntRange L, IntRange R) { 7812 return IntRange(std::max(L.Width, R.Width), 7813 L.NonNegative && R.NonNegative); 7814 } 7815 7816 /// Returns the infinum of two ranges: i.e. their aggressive merge. 7817 static IntRange meet(IntRange L, IntRange R) { 7818 return IntRange(std::min(L.Width, R.Width), 7819 L.NonNegative || R.NonNegative); 7820 } 7821 }; 7822 7823 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 7824 if (value.isSigned() && value.isNegative()) 7825 return IntRange(value.getMinSignedBits(), false); 7826 7827 if (value.getBitWidth() > MaxWidth) 7828 value = value.trunc(MaxWidth); 7829 7830 // isNonNegative() just checks the sign bit without considering 7831 // signedness. 7832 return IntRange(value.getActiveBits(), true); 7833 } 7834 7835 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 7836 unsigned MaxWidth) { 7837 if (result.isInt()) 7838 return GetValueRange(C, result.getInt(), MaxWidth); 7839 7840 if (result.isVector()) { 7841 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 7842 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 7843 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 7844 R = IntRange::join(R, El); 7845 } 7846 return R; 7847 } 7848 7849 if (result.isComplexInt()) { 7850 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 7851 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 7852 return IntRange::join(R, I); 7853 } 7854 7855 // This can happen with lossless casts to intptr_t of "based" lvalues. 7856 // Assume it might use arbitrary bits. 7857 // FIXME: The only reason we need to pass the type in here is to get 7858 // the sign right on this one case. It would be nice if APValue 7859 // preserved this. 7860 assert(result.isLValue() || result.isAddrLabelDiff()); 7861 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 7862 } 7863 7864 QualType GetExprType(const Expr *E) { 7865 QualType Ty = E->getType(); 7866 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 7867 Ty = AtomicRHS->getValueType(); 7868 return Ty; 7869 } 7870 7871 /// Pseudo-evaluate the given integer expression, estimating the 7872 /// range of values it might take. 7873 /// 7874 /// \param MaxWidth - the width to which the value will be truncated 7875 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 7876 E = E->IgnoreParens(); 7877 7878 // Try a full evaluation first. 7879 Expr::EvalResult result; 7880 if (E->EvaluateAsRValue(result, C)) 7881 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 7882 7883 // I think we only want to look through implicit casts here; if the 7884 // user has an explicit widening cast, we should treat the value as 7885 // being of the new, wider type. 7886 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 7887 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 7888 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 7889 7890 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 7891 7892 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 7893 CE->getCastKind() == CK_BooleanToSignedIntegral; 7894 7895 // Assume that non-integer casts can span the full range of the type. 7896 if (!isIntegerCast) 7897 return OutputTypeRange; 7898 7899 IntRange SubRange 7900 = GetExprRange(C, CE->getSubExpr(), 7901 std::min(MaxWidth, OutputTypeRange.Width)); 7902 7903 // Bail out if the subexpr's range is as wide as the cast type. 7904 if (SubRange.Width >= OutputTypeRange.Width) 7905 return OutputTypeRange; 7906 7907 // Otherwise, we take the smaller width, and we're non-negative if 7908 // either the output type or the subexpr is. 7909 return IntRange(SubRange.Width, 7910 SubRange.NonNegative || OutputTypeRange.NonNegative); 7911 } 7912 7913 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 7914 // If we can fold the condition, just take that operand. 7915 bool CondResult; 7916 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 7917 return GetExprRange(C, CondResult ? CO->getTrueExpr() 7918 : CO->getFalseExpr(), 7919 MaxWidth); 7920 7921 // Otherwise, conservatively merge. 7922 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 7923 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 7924 return IntRange::join(L, R); 7925 } 7926 7927 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 7928 switch (BO->getOpcode()) { 7929 7930 // Boolean-valued operations are single-bit and positive. 7931 case BO_LAnd: 7932 case BO_LOr: 7933 case BO_LT: 7934 case BO_GT: 7935 case BO_LE: 7936 case BO_GE: 7937 case BO_EQ: 7938 case BO_NE: 7939 return IntRange::forBoolType(); 7940 7941 // The type of the assignments is the type of the LHS, so the RHS 7942 // is not necessarily the same type. 7943 case BO_MulAssign: 7944 case BO_DivAssign: 7945 case BO_RemAssign: 7946 case BO_AddAssign: 7947 case BO_SubAssign: 7948 case BO_XorAssign: 7949 case BO_OrAssign: 7950 // TODO: bitfields? 7951 return IntRange::forValueOfType(C, GetExprType(E)); 7952 7953 // Simple assignments just pass through the RHS, which will have 7954 // been coerced to the LHS type. 7955 case BO_Assign: 7956 // TODO: bitfields? 7957 return GetExprRange(C, BO->getRHS(), MaxWidth); 7958 7959 // Operations with opaque sources are black-listed. 7960 case BO_PtrMemD: 7961 case BO_PtrMemI: 7962 return IntRange::forValueOfType(C, GetExprType(E)); 7963 7964 // Bitwise-and uses the *infinum* of the two source ranges. 7965 case BO_And: 7966 case BO_AndAssign: 7967 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 7968 GetExprRange(C, BO->getRHS(), MaxWidth)); 7969 7970 // Left shift gets black-listed based on a judgement call. 7971 case BO_Shl: 7972 // ...except that we want to treat '1 << (blah)' as logically 7973 // positive. It's an important idiom. 7974 if (IntegerLiteral *I 7975 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 7976 if (I->getValue() == 1) { 7977 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 7978 return IntRange(R.Width, /*NonNegative*/ true); 7979 } 7980 } 7981 // fallthrough 7982 7983 case BO_ShlAssign: 7984 return IntRange::forValueOfType(C, GetExprType(E)); 7985 7986 // Right shift by a constant can narrow its left argument. 7987 case BO_Shr: 7988 case BO_ShrAssign: { 7989 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 7990 7991 // If the shift amount is a positive constant, drop the width by 7992 // that much. 7993 llvm::APSInt shift; 7994 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 7995 shift.isNonNegative()) { 7996 unsigned zext = shift.getZExtValue(); 7997 if (zext >= L.Width) 7998 L.Width = (L.NonNegative ? 0 : 1); 7999 else 8000 L.Width -= zext; 8001 } 8002 8003 return L; 8004 } 8005 8006 // Comma acts as its right operand. 8007 case BO_Comma: 8008 return GetExprRange(C, BO->getRHS(), MaxWidth); 8009 8010 // Black-list pointer subtractions. 8011 case BO_Sub: 8012 if (BO->getLHS()->getType()->isPointerType()) 8013 return IntRange::forValueOfType(C, GetExprType(E)); 8014 break; 8015 8016 // The width of a division result is mostly determined by the size 8017 // of the LHS. 8018 case BO_Div: { 8019 // Don't 'pre-truncate' the operands. 8020 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8021 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8022 8023 // If the divisor is constant, use that. 8024 llvm::APSInt divisor; 8025 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8026 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8027 if (log2 >= L.Width) 8028 L.Width = (L.NonNegative ? 0 : 1); 8029 else 8030 L.Width = std::min(L.Width - log2, MaxWidth); 8031 return L; 8032 } 8033 8034 // Otherwise, just use the LHS's width. 8035 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8036 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8037 } 8038 8039 // The result of a remainder can't be larger than the result of 8040 // either side. 8041 case BO_Rem: { 8042 // Don't 'pre-truncate' the operands. 8043 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8044 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8045 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8046 8047 IntRange meet = IntRange::meet(L, R); 8048 meet.Width = std::min(meet.Width, MaxWidth); 8049 return meet; 8050 } 8051 8052 // The default behavior is okay for these. 8053 case BO_Mul: 8054 case BO_Add: 8055 case BO_Xor: 8056 case BO_Or: 8057 break; 8058 } 8059 8060 // The default case is to treat the operation as if it were closed 8061 // on the narrowest type that encompasses both operands. 8062 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8063 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8064 return IntRange::join(L, R); 8065 } 8066 8067 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8068 switch (UO->getOpcode()) { 8069 // Boolean-valued operations are white-listed. 8070 case UO_LNot: 8071 return IntRange::forBoolType(); 8072 8073 // Operations with opaque sources are black-listed. 8074 case UO_Deref: 8075 case UO_AddrOf: // should be impossible 8076 return IntRange::forValueOfType(C, GetExprType(E)); 8077 8078 default: 8079 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8080 } 8081 } 8082 8083 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8084 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8085 8086 if (const auto *BitField = E->getSourceBitField()) 8087 return IntRange(BitField->getBitWidthValue(C), 8088 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8089 8090 return IntRange::forValueOfType(C, GetExprType(E)); 8091 } 8092 8093 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8094 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8095 } 8096 8097 /// Checks whether the given value, which currently has the given 8098 /// source semantics, has the same value when coerced through the 8099 /// target semantics. 8100 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8101 const llvm::fltSemantics &Src, 8102 const llvm::fltSemantics &Tgt) { 8103 llvm::APFloat truncated = value; 8104 8105 bool ignored; 8106 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8107 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8108 8109 return truncated.bitwiseIsEqual(value); 8110 } 8111 8112 /// Checks whether the given value, which currently has the given 8113 /// source semantics, has the same value when coerced through the 8114 /// target semantics. 8115 /// 8116 /// The value might be a vector of floats (or a complex number). 8117 bool IsSameFloatAfterCast(const APValue &value, 8118 const llvm::fltSemantics &Src, 8119 const llvm::fltSemantics &Tgt) { 8120 if (value.isFloat()) 8121 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8122 8123 if (value.isVector()) { 8124 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8125 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8126 return false; 8127 return true; 8128 } 8129 8130 assert(value.isComplexFloat()); 8131 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8132 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8133 } 8134 8135 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8136 8137 bool IsZero(Sema &S, Expr *E) { 8138 // Suppress cases where we are comparing against an enum constant. 8139 if (const DeclRefExpr *DR = 8140 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8141 if (isa<EnumConstantDecl>(DR->getDecl())) 8142 return false; 8143 8144 // Suppress cases where the '0' value is expanded from a macro. 8145 if (E->getLocStart().isMacroID()) 8146 return false; 8147 8148 llvm::APSInt Value; 8149 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 8150 } 8151 8152 bool HasEnumType(Expr *E) { 8153 // Strip off implicit integral promotions. 8154 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8155 if (ICE->getCastKind() != CK_IntegralCast && 8156 ICE->getCastKind() != CK_NoOp) 8157 break; 8158 E = ICE->getSubExpr(); 8159 } 8160 8161 return E->getType()->isEnumeralType(); 8162 } 8163 8164 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 8165 // Disable warning in template instantiations. 8166 if (!S.ActiveTemplateInstantiations.empty()) 8167 return; 8168 8169 BinaryOperatorKind op = E->getOpcode(); 8170 if (E->isValueDependent()) 8171 return; 8172 8173 if (op == BO_LT && IsZero(S, E->getRHS())) { 8174 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8175 << "< 0" << "false" << HasEnumType(E->getLHS()) 8176 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8177 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 8178 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8179 << ">= 0" << "true" << HasEnumType(E->getLHS()) 8180 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8181 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 8182 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8183 << "0 >" << "false" << HasEnumType(E->getRHS()) 8184 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8185 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 8186 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8187 << "0 <=" << "true" << HasEnumType(E->getRHS()) 8188 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8189 } 8190 } 8191 8192 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8193 Expr *Other, const llvm::APSInt &Value, 8194 bool RhsConstant) { 8195 // Disable warning in template instantiations. 8196 if (!S.ActiveTemplateInstantiations.empty()) 8197 return; 8198 8199 // TODO: Investigate using GetExprRange() to get tighter bounds 8200 // on the bit ranges. 8201 QualType OtherT = Other->getType(); 8202 if (const auto *AT = OtherT->getAs<AtomicType>()) 8203 OtherT = AT->getValueType(); 8204 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8205 unsigned OtherWidth = OtherRange.Width; 8206 8207 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8208 8209 // 0 values are handled later by CheckTrivialUnsignedComparison(). 8210 if ((Value == 0) && (!OtherIsBooleanType)) 8211 return; 8212 8213 BinaryOperatorKind op = E->getOpcode(); 8214 bool IsTrue = true; 8215 8216 // Used for diagnostic printout. 8217 enum { 8218 LiteralConstant = 0, 8219 CXXBoolLiteralTrue, 8220 CXXBoolLiteralFalse 8221 } LiteralOrBoolConstant = LiteralConstant; 8222 8223 if (!OtherIsBooleanType) { 8224 QualType ConstantT = Constant->getType(); 8225 QualType CommonT = E->getLHS()->getType(); 8226 8227 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8228 return; 8229 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8230 "comparison with non-integer type"); 8231 8232 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8233 bool CommonSigned = CommonT->isSignedIntegerType(); 8234 8235 bool EqualityOnly = false; 8236 8237 if (CommonSigned) { 8238 // The common type is signed, therefore no signed to unsigned conversion. 8239 if (!OtherRange.NonNegative) { 8240 // Check that the constant is representable in type OtherT. 8241 if (ConstantSigned) { 8242 if (OtherWidth >= Value.getMinSignedBits()) 8243 return; 8244 } else { // !ConstantSigned 8245 if (OtherWidth >= Value.getActiveBits() + 1) 8246 return; 8247 } 8248 } else { // !OtherSigned 8249 // Check that the constant is representable in type OtherT. 8250 // Negative values are out of range. 8251 if (ConstantSigned) { 8252 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8253 return; 8254 } else { // !ConstantSigned 8255 if (OtherWidth >= Value.getActiveBits()) 8256 return; 8257 } 8258 } 8259 } else { // !CommonSigned 8260 if (OtherRange.NonNegative) { 8261 if (OtherWidth >= Value.getActiveBits()) 8262 return; 8263 } else { // OtherSigned 8264 assert(!ConstantSigned && 8265 "Two signed types converted to unsigned types."); 8266 // Check to see if the constant is representable in OtherT. 8267 if (OtherWidth > Value.getActiveBits()) 8268 return; 8269 // Check to see if the constant is equivalent to a negative value 8270 // cast to CommonT. 8271 if (S.Context.getIntWidth(ConstantT) == 8272 S.Context.getIntWidth(CommonT) && 8273 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8274 return; 8275 // The constant value rests between values that OtherT can represent 8276 // after conversion. Relational comparison still works, but equality 8277 // comparisons will be tautological. 8278 EqualityOnly = true; 8279 } 8280 } 8281 8282 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8283 8284 if (op == BO_EQ || op == BO_NE) { 8285 IsTrue = op == BO_NE; 8286 } else if (EqualityOnly) { 8287 return; 8288 } else if (RhsConstant) { 8289 if (op == BO_GT || op == BO_GE) 8290 IsTrue = !PositiveConstant; 8291 else // op == BO_LT || op == BO_LE 8292 IsTrue = PositiveConstant; 8293 } else { 8294 if (op == BO_LT || op == BO_LE) 8295 IsTrue = !PositiveConstant; 8296 else // op == BO_GT || op == BO_GE 8297 IsTrue = PositiveConstant; 8298 } 8299 } else { 8300 // Other isKnownToHaveBooleanValue 8301 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8302 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8303 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8304 8305 static const struct LinkedConditions { 8306 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8307 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8308 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8309 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8310 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8311 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8312 8313 } TruthTable = { 8314 // Constant on LHS. | Constant on RHS. | 8315 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8316 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8317 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8318 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8319 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8320 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8321 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8322 }; 8323 8324 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8325 8326 enum ConstantValue ConstVal = Zero; 8327 if (Value.isUnsigned() || Value.isNonNegative()) { 8328 if (Value == 0) { 8329 LiteralOrBoolConstant = 8330 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8331 ConstVal = Zero; 8332 } else if (Value == 1) { 8333 LiteralOrBoolConstant = 8334 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8335 ConstVal = One; 8336 } else { 8337 LiteralOrBoolConstant = LiteralConstant; 8338 ConstVal = GT_One; 8339 } 8340 } else { 8341 ConstVal = LT_Zero; 8342 } 8343 8344 CompareBoolWithConstantResult CmpRes; 8345 8346 switch (op) { 8347 case BO_LT: 8348 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8349 break; 8350 case BO_GT: 8351 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8352 break; 8353 case BO_LE: 8354 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8355 break; 8356 case BO_GE: 8357 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8358 break; 8359 case BO_EQ: 8360 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8361 break; 8362 case BO_NE: 8363 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8364 break; 8365 default: 8366 CmpRes = Unkwn; 8367 break; 8368 } 8369 8370 if (CmpRes == AFals) { 8371 IsTrue = false; 8372 } else if (CmpRes == ATrue) { 8373 IsTrue = true; 8374 } else { 8375 return; 8376 } 8377 } 8378 8379 // If this is a comparison to an enum constant, include that 8380 // constant in the diagnostic. 8381 const EnumConstantDecl *ED = nullptr; 8382 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8383 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8384 8385 SmallString<64> PrettySourceValue; 8386 llvm::raw_svector_ostream OS(PrettySourceValue); 8387 if (ED) 8388 OS << '\'' << *ED << "' (" << Value << ")"; 8389 else 8390 OS << Value; 8391 8392 S.DiagRuntimeBehavior( 8393 E->getOperatorLoc(), E, 8394 S.PDiag(diag::warn_out_of_range_compare) 8395 << OS.str() << LiteralOrBoolConstant 8396 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8397 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8398 } 8399 8400 /// Analyze the operands of the given comparison. Implements the 8401 /// fallback case from AnalyzeComparison. 8402 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8403 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8404 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8405 } 8406 8407 /// \brief Implements -Wsign-compare. 8408 /// 8409 /// \param E the binary operator to check for warnings 8410 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8411 // The type the comparison is being performed in. 8412 QualType T = E->getLHS()->getType(); 8413 8414 // Only analyze comparison operators where both sides have been converted to 8415 // the same type. 8416 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8417 return AnalyzeImpConvsInComparison(S, E); 8418 8419 // Don't analyze value-dependent comparisons directly. 8420 if (E->isValueDependent()) 8421 return AnalyzeImpConvsInComparison(S, E); 8422 8423 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8424 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8425 8426 bool IsComparisonConstant = false; 8427 8428 // Check whether an integer constant comparison results in a value 8429 // of 'true' or 'false'. 8430 if (T->isIntegralType(S.Context)) { 8431 llvm::APSInt RHSValue; 8432 bool IsRHSIntegralLiteral = 8433 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8434 llvm::APSInt LHSValue; 8435 bool IsLHSIntegralLiteral = 8436 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8437 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8438 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8439 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8440 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8441 else 8442 IsComparisonConstant = 8443 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8444 } else if (!T->hasUnsignedIntegerRepresentation()) 8445 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8446 8447 // We don't do anything special if this isn't an unsigned integral 8448 // comparison: we're only interested in integral comparisons, and 8449 // signed comparisons only happen in cases we don't care to warn about. 8450 // 8451 // We also don't care about value-dependent expressions or expressions 8452 // whose result is a constant. 8453 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 8454 return AnalyzeImpConvsInComparison(S, E); 8455 8456 // Check to see if one of the (unmodified) operands is of different 8457 // signedness. 8458 Expr *signedOperand, *unsignedOperand; 8459 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8460 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8461 "unsigned comparison between two signed integer expressions?"); 8462 signedOperand = LHS; 8463 unsignedOperand = RHS; 8464 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8465 signedOperand = RHS; 8466 unsignedOperand = LHS; 8467 } else { 8468 CheckTrivialUnsignedComparison(S, E); 8469 return AnalyzeImpConvsInComparison(S, E); 8470 } 8471 8472 // Otherwise, calculate the effective range of the signed operand. 8473 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8474 8475 // Go ahead and analyze implicit conversions in the operands. Note 8476 // that we skip the implicit conversions on both sides. 8477 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8478 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8479 8480 // If the signed range is non-negative, -Wsign-compare won't fire, 8481 // but we should still check for comparisons which are always true 8482 // or false. 8483 if (signedRange.NonNegative) 8484 return CheckTrivialUnsignedComparison(S, E); 8485 8486 // For (in)equality comparisons, if the unsigned operand is a 8487 // constant which cannot collide with a overflowed signed operand, 8488 // then reinterpreting the signed operand as unsigned will not 8489 // change the result of the comparison. 8490 if (E->isEqualityOp()) { 8491 unsigned comparisonWidth = S.Context.getIntWidth(T); 8492 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8493 8494 // We should never be unable to prove that the unsigned operand is 8495 // non-negative. 8496 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8497 8498 if (unsignedRange.Width < comparisonWidth) 8499 return; 8500 } 8501 8502 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8503 S.PDiag(diag::warn_mixed_sign_comparison) 8504 << LHS->getType() << RHS->getType() 8505 << LHS->getSourceRange() << RHS->getSourceRange()); 8506 } 8507 8508 /// Analyzes an attempt to assign the given value to a bitfield. 8509 /// 8510 /// Returns true if there was something fishy about the attempt. 8511 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8512 SourceLocation InitLoc) { 8513 assert(Bitfield->isBitField()); 8514 if (Bitfield->isInvalidDecl()) 8515 return false; 8516 8517 // White-list bool bitfields. 8518 QualType BitfieldType = Bitfield->getType(); 8519 if (BitfieldType->isBooleanType()) 8520 return false; 8521 8522 if (BitfieldType->isEnumeralType()) { 8523 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 8524 // If the underlying enum type was not explicitly specified as an unsigned 8525 // type and the enum contain only positive values, MSVC++ will cause an 8526 // inconsistency by storing this as a signed type. 8527 if (S.getLangOpts().CPlusPlus11 && 8528 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 8529 BitfieldEnumDecl->getNumPositiveBits() > 0 && 8530 BitfieldEnumDecl->getNumNegativeBits() == 0) { 8531 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 8532 << BitfieldEnumDecl->getNameAsString(); 8533 } 8534 } 8535 8536 if (Bitfield->getType()->isBooleanType()) 8537 return false; 8538 8539 // Ignore value- or type-dependent expressions. 8540 if (Bitfield->getBitWidth()->isValueDependent() || 8541 Bitfield->getBitWidth()->isTypeDependent() || 8542 Init->isValueDependent() || 8543 Init->isTypeDependent()) 8544 return false; 8545 8546 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8547 8548 llvm::APSInt Value; 8549 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 8550 return false; 8551 8552 unsigned OriginalWidth = Value.getBitWidth(); 8553 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8554 8555 if (!Value.isSigned() || Value.isNegative()) 8556 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 8557 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 8558 OriginalWidth = Value.getMinSignedBits(); 8559 8560 if (OriginalWidth <= FieldWidth) 8561 return false; 8562 8563 // Compute the value which the bitfield will contain. 8564 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 8565 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 8566 8567 // Check whether the stored value is equal to the original value. 8568 TruncatedValue = TruncatedValue.extend(OriginalWidth); 8569 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 8570 return false; 8571 8572 // Special-case bitfields of width 1: booleans are naturally 0/1, and 8573 // therefore don't strictly fit into a signed bitfield of width 1. 8574 if (FieldWidth == 1 && Value == 1) 8575 return false; 8576 8577 std::string PrettyValue = Value.toString(10); 8578 std::string PrettyTrunc = TruncatedValue.toString(10); 8579 8580 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 8581 << PrettyValue << PrettyTrunc << OriginalInit->getType() 8582 << Init->getSourceRange(); 8583 8584 return true; 8585 } 8586 8587 /// Analyze the given simple or compound assignment for warning-worthy 8588 /// operations. 8589 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 8590 // Just recurse on the LHS. 8591 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8592 8593 // We want to recurse on the RHS as normal unless we're assigning to 8594 // a bitfield. 8595 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 8596 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 8597 E->getOperatorLoc())) { 8598 // Recurse, ignoring any implicit conversions on the RHS. 8599 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 8600 E->getOperatorLoc()); 8601 } 8602 } 8603 8604 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8605 } 8606 8607 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8608 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 8609 SourceLocation CContext, unsigned diag, 8610 bool pruneControlFlow = false) { 8611 if (pruneControlFlow) { 8612 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8613 S.PDiag(diag) 8614 << SourceType << T << E->getSourceRange() 8615 << SourceRange(CContext)); 8616 return; 8617 } 8618 S.Diag(E->getExprLoc(), diag) 8619 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 8620 } 8621 8622 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8623 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 8624 unsigned diag, bool pruneControlFlow = false) { 8625 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 8626 } 8627 8628 8629 /// Diagnose an implicit cast from a floating point value to an integer value. 8630 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 8631 8632 SourceLocation CContext) { 8633 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 8634 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty(); 8635 8636 Expr *InnerE = E->IgnoreParenImpCasts(); 8637 // We also want to warn on, e.g., "int i = -1.234" 8638 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 8639 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 8640 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 8641 8642 const bool IsLiteral = 8643 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 8644 8645 llvm::APFloat Value(0.0); 8646 bool IsConstant = 8647 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 8648 if (!IsConstant) { 8649 return DiagnoseImpCast(S, E, T, CContext, 8650 diag::warn_impcast_float_integer, PruneWarnings); 8651 } 8652 8653 bool isExact = false; 8654 8655 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 8656 T->hasUnsignedIntegerRepresentation()); 8657 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 8658 &isExact) == llvm::APFloat::opOK && 8659 isExact) { 8660 if (IsLiteral) return; 8661 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 8662 PruneWarnings); 8663 } 8664 8665 unsigned DiagID = 0; 8666 if (IsLiteral) { 8667 // Warn on floating point literal to integer. 8668 DiagID = diag::warn_impcast_literal_float_to_integer; 8669 } else if (IntegerValue == 0) { 8670 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 8671 return DiagnoseImpCast(S, E, T, CContext, 8672 diag::warn_impcast_float_integer, PruneWarnings); 8673 } 8674 // Warn on non-zero to zero conversion. 8675 DiagID = diag::warn_impcast_float_to_integer_zero; 8676 } else { 8677 if (IntegerValue.isUnsigned()) { 8678 if (!IntegerValue.isMaxValue()) { 8679 return DiagnoseImpCast(S, E, T, CContext, 8680 diag::warn_impcast_float_integer, PruneWarnings); 8681 } 8682 } else { // IntegerValue.isSigned() 8683 if (!IntegerValue.isMaxSignedValue() && 8684 !IntegerValue.isMinSignedValue()) { 8685 return DiagnoseImpCast(S, E, T, CContext, 8686 diag::warn_impcast_float_integer, PruneWarnings); 8687 } 8688 } 8689 // Warn on evaluatable floating point expression to integer conversion. 8690 DiagID = diag::warn_impcast_float_to_integer; 8691 } 8692 8693 // FIXME: Force the precision of the source value down so we don't print 8694 // digits which are usually useless (we don't really care here if we 8695 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 8696 // would automatically print the shortest representation, but it's a bit 8697 // tricky to implement. 8698 SmallString<16> PrettySourceValue; 8699 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 8700 precision = (precision * 59 + 195) / 196; 8701 Value.toString(PrettySourceValue, precision); 8702 8703 SmallString<16> PrettyTargetValue; 8704 if (IsBool) 8705 PrettyTargetValue = Value.isZero() ? "false" : "true"; 8706 else 8707 IntegerValue.toString(PrettyTargetValue); 8708 8709 if (PruneWarnings) { 8710 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8711 S.PDiag(DiagID) 8712 << E->getType() << T.getUnqualifiedType() 8713 << PrettySourceValue << PrettyTargetValue 8714 << E->getSourceRange() << SourceRange(CContext)); 8715 } else { 8716 S.Diag(E->getExprLoc(), DiagID) 8717 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 8718 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 8719 } 8720 } 8721 8722 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 8723 if (!Range.Width) return "0"; 8724 8725 llvm::APSInt ValueInRange = Value; 8726 ValueInRange.setIsSigned(!Range.NonNegative); 8727 ValueInRange = ValueInRange.trunc(Range.Width); 8728 return ValueInRange.toString(10); 8729 } 8730 8731 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 8732 if (!isa<ImplicitCastExpr>(Ex)) 8733 return false; 8734 8735 Expr *InnerE = Ex->IgnoreParenImpCasts(); 8736 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 8737 const Type *Source = 8738 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 8739 if (Target->isDependentType()) 8740 return false; 8741 8742 const BuiltinType *FloatCandidateBT = 8743 dyn_cast<BuiltinType>(ToBool ? Source : Target); 8744 const Type *BoolCandidateType = ToBool ? Target : Source; 8745 8746 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 8747 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 8748 } 8749 8750 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 8751 SourceLocation CC) { 8752 unsigned NumArgs = TheCall->getNumArgs(); 8753 for (unsigned i = 0; i < NumArgs; ++i) { 8754 Expr *CurrA = TheCall->getArg(i); 8755 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 8756 continue; 8757 8758 bool IsSwapped = ((i > 0) && 8759 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 8760 IsSwapped |= ((i < (NumArgs - 1)) && 8761 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 8762 if (IsSwapped) { 8763 // Warn on this floating-point to bool conversion. 8764 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 8765 CurrA->getType(), CC, 8766 diag::warn_impcast_floating_point_to_bool); 8767 } 8768 } 8769 } 8770 8771 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 8772 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 8773 E->getExprLoc())) 8774 return; 8775 8776 // Don't warn on functions which have return type nullptr_t. 8777 if (isa<CallExpr>(E)) 8778 return; 8779 8780 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 8781 const Expr::NullPointerConstantKind NullKind = 8782 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 8783 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 8784 return; 8785 8786 // Return if target type is a safe conversion. 8787 if (T->isAnyPointerType() || T->isBlockPointerType() || 8788 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 8789 return; 8790 8791 SourceLocation Loc = E->getSourceRange().getBegin(); 8792 8793 // Venture through the macro stacks to get to the source of macro arguments. 8794 // The new location is a better location than the complete location that was 8795 // passed in. 8796 while (S.SourceMgr.isMacroArgExpansion(Loc)) 8797 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 8798 8799 while (S.SourceMgr.isMacroArgExpansion(CC)) 8800 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 8801 8802 // __null is usually wrapped in a macro. Go up a macro if that is the case. 8803 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 8804 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 8805 Loc, S.SourceMgr, S.getLangOpts()); 8806 if (MacroName == "NULL") 8807 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 8808 } 8809 8810 // Only warn if the null and context location are in the same macro expansion. 8811 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 8812 return; 8813 8814 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 8815 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 8816 << FixItHint::CreateReplacement(Loc, 8817 S.getFixItZeroLiteralForType(T, Loc)); 8818 } 8819 8820 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8821 ObjCArrayLiteral *ArrayLiteral); 8822 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8823 ObjCDictionaryLiteral *DictionaryLiteral); 8824 8825 /// Check a single element within a collection literal against the 8826 /// target element type. 8827 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 8828 Expr *Element, unsigned ElementKind) { 8829 // Skip a bitcast to 'id' or qualified 'id'. 8830 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 8831 if (ICE->getCastKind() == CK_BitCast && 8832 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 8833 Element = ICE->getSubExpr(); 8834 } 8835 8836 QualType ElementType = Element->getType(); 8837 ExprResult ElementResult(Element); 8838 if (ElementType->getAs<ObjCObjectPointerType>() && 8839 S.CheckSingleAssignmentConstraints(TargetElementType, 8840 ElementResult, 8841 false, false) 8842 != Sema::Compatible) { 8843 S.Diag(Element->getLocStart(), 8844 diag::warn_objc_collection_literal_element) 8845 << ElementType << ElementKind << TargetElementType 8846 << Element->getSourceRange(); 8847 } 8848 8849 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 8850 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 8851 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 8852 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 8853 } 8854 8855 /// Check an Objective-C array literal being converted to the given 8856 /// target type. 8857 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8858 ObjCArrayLiteral *ArrayLiteral) { 8859 if (!S.NSArrayDecl) 8860 return; 8861 8862 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8863 if (!TargetObjCPtr) 8864 return; 8865 8866 if (TargetObjCPtr->isUnspecialized() || 8867 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8868 != S.NSArrayDecl->getCanonicalDecl()) 8869 return; 8870 8871 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8872 if (TypeArgs.size() != 1) 8873 return; 8874 8875 QualType TargetElementType = TypeArgs[0]; 8876 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 8877 checkObjCCollectionLiteralElement(S, TargetElementType, 8878 ArrayLiteral->getElement(I), 8879 0); 8880 } 8881 } 8882 8883 /// Check an Objective-C dictionary literal being converted to the given 8884 /// target type. 8885 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8886 ObjCDictionaryLiteral *DictionaryLiteral) { 8887 if (!S.NSDictionaryDecl) 8888 return; 8889 8890 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8891 if (!TargetObjCPtr) 8892 return; 8893 8894 if (TargetObjCPtr->isUnspecialized() || 8895 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8896 != S.NSDictionaryDecl->getCanonicalDecl()) 8897 return; 8898 8899 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8900 if (TypeArgs.size() != 2) 8901 return; 8902 8903 QualType TargetKeyType = TypeArgs[0]; 8904 QualType TargetObjectType = TypeArgs[1]; 8905 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 8906 auto Element = DictionaryLiteral->getKeyValueElement(I); 8907 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 8908 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 8909 } 8910 } 8911 8912 // Helper function to filter out cases for constant width constant conversion. 8913 // Don't warn on char array initialization or for non-decimal values. 8914 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 8915 SourceLocation CC) { 8916 // If initializing from a constant, and the constant starts with '0', 8917 // then it is a binary, octal, or hexadecimal. Allow these constants 8918 // to fill all the bits, even if there is a sign change. 8919 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 8920 const char FirstLiteralCharacter = 8921 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 8922 if (FirstLiteralCharacter == '0') 8923 return false; 8924 } 8925 8926 // If the CC location points to a '{', and the type is char, then assume 8927 // assume it is an array initialization. 8928 if (CC.isValid() && T->isCharType()) { 8929 const char FirstContextCharacter = 8930 S.getSourceManager().getCharacterData(CC)[0]; 8931 if (FirstContextCharacter == '{') 8932 return false; 8933 } 8934 8935 return true; 8936 } 8937 8938 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 8939 SourceLocation CC, bool *ICContext = nullptr) { 8940 if (E->isTypeDependent() || E->isValueDependent()) return; 8941 8942 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 8943 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 8944 if (Source == Target) return; 8945 if (Target->isDependentType()) return; 8946 8947 // If the conversion context location is invalid don't complain. We also 8948 // don't want to emit a warning if the issue occurs from the expansion of 8949 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 8950 // delay this check as long as possible. Once we detect we are in that 8951 // scenario, we just return. 8952 if (CC.isInvalid()) 8953 return; 8954 8955 // Diagnose implicit casts to bool. 8956 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 8957 if (isa<StringLiteral>(E)) 8958 // Warn on string literal to bool. Checks for string literals in logical 8959 // and expressions, for instance, assert(0 && "error here"), are 8960 // prevented by a check in AnalyzeImplicitConversions(). 8961 return DiagnoseImpCast(S, E, T, CC, 8962 diag::warn_impcast_string_literal_to_bool); 8963 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 8964 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 8965 // This covers the literal expressions that evaluate to Objective-C 8966 // objects. 8967 return DiagnoseImpCast(S, E, T, CC, 8968 diag::warn_impcast_objective_c_literal_to_bool); 8969 } 8970 if (Source->isPointerType() || Source->canDecayToPointerType()) { 8971 // Warn on pointer to bool conversion that is always true. 8972 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 8973 SourceRange(CC)); 8974 } 8975 } 8976 8977 // Check implicit casts from Objective-C collection literals to specialized 8978 // collection types, e.g., NSArray<NSString *> *. 8979 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 8980 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 8981 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 8982 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 8983 8984 // Strip vector types. 8985 if (isa<VectorType>(Source)) { 8986 if (!isa<VectorType>(Target)) { 8987 if (S.SourceMgr.isInSystemMacro(CC)) 8988 return; 8989 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 8990 } 8991 8992 // If the vector cast is cast between two vectors of the same size, it is 8993 // a bitcast, not a conversion. 8994 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 8995 return; 8996 8997 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 8998 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 8999 } 9000 if (auto VecTy = dyn_cast<VectorType>(Target)) 9001 Target = VecTy->getElementType().getTypePtr(); 9002 9003 // Strip complex types. 9004 if (isa<ComplexType>(Source)) { 9005 if (!isa<ComplexType>(Target)) { 9006 if (S.SourceMgr.isInSystemMacro(CC)) 9007 return; 9008 9009 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 9010 } 9011 9012 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9013 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9014 } 9015 9016 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9017 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9018 9019 // If the source is floating point... 9020 if (SourceBT && SourceBT->isFloatingPoint()) { 9021 // ...and the target is floating point... 9022 if (TargetBT && TargetBT->isFloatingPoint()) { 9023 // ...then warn if we're dropping FP rank. 9024 9025 // Builtin FP kinds are ordered by increasing FP rank. 9026 if (SourceBT->getKind() > TargetBT->getKind()) { 9027 // Don't warn about float constants that are precisely 9028 // representable in the target type. 9029 Expr::EvalResult result; 9030 if (E->EvaluateAsRValue(result, S.Context)) { 9031 // Value might be a float, a float vector, or a float complex. 9032 if (IsSameFloatAfterCast(result.Val, 9033 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9034 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9035 return; 9036 } 9037 9038 if (S.SourceMgr.isInSystemMacro(CC)) 9039 return; 9040 9041 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9042 } 9043 // ... or possibly if we're increasing rank, too 9044 else if (TargetBT->getKind() > SourceBT->getKind()) { 9045 if (S.SourceMgr.isInSystemMacro(CC)) 9046 return; 9047 9048 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9049 } 9050 return; 9051 } 9052 9053 // If the target is integral, always warn. 9054 if (TargetBT && TargetBT->isInteger()) { 9055 if (S.SourceMgr.isInSystemMacro(CC)) 9056 return; 9057 9058 DiagnoseFloatingImpCast(S, E, T, CC); 9059 } 9060 9061 // Detect the case where a call result is converted from floating-point to 9062 // to bool, and the final argument to the call is converted from bool, to 9063 // discover this typo: 9064 // 9065 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9066 // 9067 // FIXME: This is an incredibly special case; is there some more general 9068 // way to detect this class of misplaced-parentheses bug? 9069 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9070 // Check last argument of function call to see if it is an 9071 // implicit cast from a type matching the type the result 9072 // is being cast to. 9073 CallExpr *CEx = cast<CallExpr>(E); 9074 if (unsigned NumArgs = CEx->getNumArgs()) { 9075 Expr *LastA = CEx->getArg(NumArgs - 1); 9076 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9077 if (isa<ImplicitCastExpr>(LastA) && 9078 InnerE->getType()->isBooleanType()) { 9079 // Warn on this floating-point to bool conversion 9080 DiagnoseImpCast(S, E, T, CC, 9081 diag::warn_impcast_floating_point_to_bool); 9082 } 9083 } 9084 } 9085 return; 9086 } 9087 9088 DiagnoseNullConversion(S, E, T, CC); 9089 9090 S.DiscardMisalignedMemberAddress(Target, E); 9091 9092 if (!Source->isIntegerType() || !Target->isIntegerType()) 9093 return; 9094 9095 // TODO: remove this early return once the false positives for constant->bool 9096 // in templates, macros, etc, are reduced or removed. 9097 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9098 return; 9099 9100 IntRange SourceRange = GetExprRange(S.Context, E); 9101 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9102 9103 if (SourceRange.Width > TargetRange.Width) { 9104 // If the source is a constant, use a default-on diagnostic. 9105 // TODO: this should happen for bitfield stores, too. 9106 llvm::APSInt Value(32); 9107 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9108 if (S.SourceMgr.isInSystemMacro(CC)) 9109 return; 9110 9111 std::string PrettySourceValue = Value.toString(10); 9112 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9113 9114 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9115 S.PDiag(diag::warn_impcast_integer_precision_constant) 9116 << PrettySourceValue << PrettyTargetValue 9117 << E->getType() << T << E->getSourceRange() 9118 << clang::SourceRange(CC)); 9119 return; 9120 } 9121 9122 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9123 if (S.SourceMgr.isInSystemMacro(CC)) 9124 return; 9125 9126 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9127 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9128 /* pruneControlFlow */ true); 9129 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9130 } 9131 9132 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9133 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9134 // Warn when doing a signed to signed conversion, warn if the positive 9135 // source value is exactly the width of the target type, which will 9136 // cause a negative value to be stored. 9137 9138 llvm::APSInt Value; 9139 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9140 !S.SourceMgr.isInSystemMacro(CC)) { 9141 if (isSameWidthConstantConversion(S, E, T, CC)) { 9142 std::string PrettySourceValue = Value.toString(10); 9143 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9144 9145 S.DiagRuntimeBehavior( 9146 E->getExprLoc(), E, 9147 S.PDiag(diag::warn_impcast_integer_precision_constant) 9148 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9149 << E->getSourceRange() << clang::SourceRange(CC)); 9150 return; 9151 } 9152 } 9153 9154 // Fall through for non-constants to give a sign conversion warning. 9155 } 9156 9157 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9158 (!TargetRange.NonNegative && SourceRange.NonNegative && 9159 SourceRange.Width == TargetRange.Width)) { 9160 if (S.SourceMgr.isInSystemMacro(CC)) 9161 return; 9162 9163 unsigned DiagID = diag::warn_impcast_integer_sign; 9164 9165 // Traditionally, gcc has warned about this under -Wsign-compare. 9166 // We also want to warn about it in -Wconversion. 9167 // So if -Wconversion is off, use a completely identical diagnostic 9168 // in the sign-compare group. 9169 // The conditional-checking code will 9170 if (ICContext) { 9171 DiagID = diag::warn_impcast_integer_sign_conditional; 9172 *ICContext = true; 9173 } 9174 9175 return DiagnoseImpCast(S, E, T, CC, DiagID); 9176 } 9177 9178 // Diagnose conversions between different enumeration types. 9179 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9180 // type, to give us better diagnostics. 9181 QualType SourceType = E->getType(); 9182 if (!S.getLangOpts().CPlusPlus) { 9183 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9184 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9185 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9186 SourceType = S.Context.getTypeDeclType(Enum); 9187 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9188 } 9189 } 9190 9191 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9192 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9193 if (SourceEnum->getDecl()->hasNameForLinkage() && 9194 TargetEnum->getDecl()->hasNameForLinkage() && 9195 SourceEnum != TargetEnum) { 9196 if (S.SourceMgr.isInSystemMacro(CC)) 9197 return; 9198 9199 return DiagnoseImpCast(S, E, SourceType, T, CC, 9200 diag::warn_impcast_different_enum_types); 9201 } 9202 } 9203 9204 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9205 SourceLocation CC, QualType T); 9206 9207 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9208 SourceLocation CC, bool &ICContext) { 9209 E = E->IgnoreParenImpCasts(); 9210 9211 if (isa<ConditionalOperator>(E)) 9212 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9213 9214 AnalyzeImplicitConversions(S, E, CC); 9215 if (E->getType() != T) 9216 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9217 } 9218 9219 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9220 SourceLocation CC, QualType T) { 9221 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9222 9223 bool Suspicious = false; 9224 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9225 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9226 9227 // If -Wconversion would have warned about either of the candidates 9228 // for a signedness conversion to the context type... 9229 if (!Suspicious) return; 9230 9231 // ...but it's currently ignored... 9232 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9233 return; 9234 9235 // ...then check whether it would have warned about either of the 9236 // candidates for a signedness conversion to the condition type. 9237 if (E->getType() == T) return; 9238 9239 Suspicious = false; 9240 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9241 E->getType(), CC, &Suspicious); 9242 if (!Suspicious) 9243 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9244 E->getType(), CC, &Suspicious); 9245 } 9246 9247 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9248 /// Input argument E is a logical expression. 9249 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9250 if (S.getLangOpts().Bool) 9251 return; 9252 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9253 } 9254 9255 /// AnalyzeImplicitConversions - Find and report any interesting 9256 /// implicit conversions in the given expression. There are a couple 9257 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9258 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9259 QualType T = OrigE->getType(); 9260 Expr *E = OrigE->IgnoreParenImpCasts(); 9261 9262 if (E->isTypeDependent() || E->isValueDependent()) 9263 return; 9264 9265 // For conditional operators, we analyze the arguments as if they 9266 // were being fed directly into the output. 9267 if (isa<ConditionalOperator>(E)) { 9268 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9269 CheckConditionalOperator(S, CO, CC, T); 9270 return; 9271 } 9272 9273 // Check implicit argument conversions for function calls. 9274 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9275 CheckImplicitArgumentConversions(S, Call, CC); 9276 9277 // Go ahead and check any implicit conversions we might have skipped. 9278 // The non-canonical typecheck is just an optimization; 9279 // CheckImplicitConversion will filter out dead implicit conversions. 9280 if (E->getType() != T) 9281 CheckImplicitConversion(S, E, T, CC); 9282 9283 // Now continue drilling into this expression. 9284 9285 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9286 // The bound subexpressions in a PseudoObjectExpr are not reachable 9287 // as transitive children. 9288 // FIXME: Use a more uniform representation for this. 9289 for (auto *SE : POE->semantics()) 9290 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9291 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9292 } 9293 9294 // Skip past explicit casts. 9295 if (isa<ExplicitCastExpr>(E)) { 9296 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9297 return AnalyzeImplicitConversions(S, E, CC); 9298 } 9299 9300 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9301 // Do a somewhat different check with comparison operators. 9302 if (BO->isComparisonOp()) 9303 return AnalyzeComparison(S, BO); 9304 9305 // And with simple assignments. 9306 if (BO->getOpcode() == BO_Assign) 9307 return AnalyzeAssignment(S, BO); 9308 } 9309 9310 // These break the otherwise-useful invariant below. Fortunately, 9311 // we don't really need to recurse into them, because any internal 9312 // expressions should have been analyzed already when they were 9313 // built into statements. 9314 if (isa<StmtExpr>(E)) return; 9315 9316 // Don't descend into unevaluated contexts. 9317 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9318 9319 // Now just recurse over the expression's children. 9320 CC = E->getExprLoc(); 9321 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9322 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9323 for (Stmt *SubStmt : E->children()) { 9324 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9325 if (!ChildExpr) 9326 continue; 9327 9328 if (IsLogicalAndOperator && 9329 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9330 // Ignore checking string literals that are in logical and operators. 9331 // This is a common pattern for asserts. 9332 continue; 9333 AnalyzeImplicitConversions(S, ChildExpr, CC); 9334 } 9335 9336 if (BO && BO->isLogicalOp()) { 9337 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9338 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9339 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9340 9341 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9342 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9343 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9344 } 9345 9346 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9347 if (U->getOpcode() == UO_LNot) 9348 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9349 } 9350 9351 } // end anonymous namespace 9352 9353 /// Diagnose integer type and any valid implicit convertion to it. 9354 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 9355 // Taking into account implicit conversions, 9356 // allow any integer. 9357 if (!E->getType()->isIntegerType()) { 9358 S.Diag(E->getLocStart(), 9359 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9360 return true; 9361 } 9362 // Potentially emit standard warnings for implicit conversions if enabled 9363 // using -Wconversion. 9364 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 9365 return false; 9366 } 9367 9368 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9369 // Returns true when emitting a warning about taking the address of a reference. 9370 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9371 const PartialDiagnostic &PD) { 9372 E = E->IgnoreParenImpCasts(); 9373 9374 const FunctionDecl *FD = nullptr; 9375 9376 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9377 if (!DRE->getDecl()->getType()->isReferenceType()) 9378 return false; 9379 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9380 if (!M->getMemberDecl()->getType()->isReferenceType()) 9381 return false; 9382 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9383 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9384 return false; 9385 FD = Call->getDirectCallee(); 9386 } else { 9387 return false; 9388 } 9389 9390 SemaRef.Diag(E->getExprLoc(), PD); 9391 9392 // If possible, point to location of function. 9393 if (FD) { 9394 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9395 } 9396 9397 return true; 9398 } 9399 9400 // Returns true if the SourceLocation is expanded from any macro body. 9401 // Returns false if the SourceLocation is invalid, is from not in a macro 9402 // expansion, or is from expanded from a top-level macro argument. 9403 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9404 if (Loc.isInvalid()) 9405 return false; 9406 9407 while (Loc.isMacroID()) { 9408 if (SM.isMacroBodyExpansion(Loc)) 9409 return true; 9410 Loc = SM.getImmediateMacroCallerLoc(Loc); 9411 } 9412 9413 return false; 9414 } 9415 9416 /// \brief Diagnose pointers that are always non-null. 9417 /// \param E the expression containing the pointer 9418 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9419 /// compared to a null pointer 9420 /// \param IsEqual True when the comparison is equal to a null pointer 9421 /// \param Range Extra SourceRange to highlight in the diagnostic 9422 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9423 Expr::NullPointerConstantKind NullKind, 9424 bool IsEqual, SourceRange Range) { 9425 if (!E) 9426 return; 9427 9428 // Don't warn inside macros. 9429 if (E->getExprLoc().isMacroID()) { 9430 const SourceManager &SM = getSourceManager(); 9431 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9432 IsInAnyMacroBody(SM, Range.getBegin())) 9433 return; 9434 } 9435 E = E->IgnoreImpCasts(); 9436 9437 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9438 9439 if (isa<CXXThisExpr>(E)) { 9440 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9441 : diag::warn_this_bool_conversion; 9442 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9443 return; 9444 } 9445 9446 bool IsAddressOf = false; 9447 9448 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9449 if (UO->getOpcode() != UO_AddrOf) 9450 return; 9451 IsAddressOf = true; 9452 E = UO->getSubExpr(); 9453 } 9454 9455 if (IsAddressOf) { 9456 unsigned DiagID = IsCompare 9457 ? diag::warn_address_of_reference_null_compare 9458 : diag::warn_address_of_reference_bool_conversion; 9459 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 9460 << IsEqual; 9461 if (CheckForReference(*this, E, PD)) { 9462 return; 9463 } 9464 } 9465 9466 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 9467 bool IsParam = isa<NonNullAttr>(NonnullAttr); 9468 std::string Str; 9469 llvm::raw_string_ostream S(Str); 9470 E->printPretty(S, nullptr, getPrintingPolicy()); 9471 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 9472 : diag::warn_cast_nonnull_to_bool; 9473 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 9474 << E->getSourceRange() << Range << IsEqual; 9475 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 9476 }; 9477 9478 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 9479 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 9480 if (auto *Callee = Call->getDirectCallee()) { 9481 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 9482 ComplainAboutNonnullParamOrCall(A); 9483 return; 9484 } 9485 } 9486 } 9487 9488 // Expect to find a single Decl. Skip anything more complicated. 9489 ValueDecl *D = nullptr; 9490 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 9491 D = R->getDecl(); 9492 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9493 D = M->getMemberDecl(); 9494 } 9495 9496 // Weak Decls can be null. 9497 if (!D || D->isWeak()) 9498 return; 9499 9500 // Check for parameter decl with nonnull attribute 9501 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 9502 if (getCurFunction() && 9503 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 9504 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 9505 ComplainAboutNonnullParamOrCall(A); 9506 return; 9507 } 9508 9509 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 9510 auto ParamIter = llvm::find(FD->parameters(), PV); 9511 assert(ParamIter != FD->param_end()); 9512 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 9513 9514 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 9515 if (!NonNull->args_size()) { 9516 ComplainAboutNonnullParamOrCall(NonNull); 9517 return; 9518 } 9519 9520 for (unsigned ArgNo : NonNull->args()) { 9521 if (ArgNo == ParamNo) { 9522 ComplainAboutNonnullParamOrCall(NonNull); 9523 return; 9524 } 9525 } 9526 } 9527 } 9528 } 9529 } 9530 9531 QualType T = D->getType(); 9532 const bool IsArray = T->isArrayType(); 9533 const bool IsFunction = T->isFunctionType(); 9534 9535 // Address of function is used to silence the function warning. 9536 if (IsAddressOf && IsFunction) { 9537 return; 9538 } 9539 9540 // Found nothing. 9541 if (!IsAddressOf && !IsFunction && !IsArray) 9542 return; 9543 9544 // Pretty print the expression for the diagnostic. 9545 std::string Str; 9546 llvm::raw_string_ostream S(Str); 9547 E->printPretty(S, nullptr, getPrintingPolicy()); 9548 9549 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 9550 : diag::warn_impcast_pointer_to_bool; 9551 enum { 9552 AddressOf, 9553 FunctionPointer, 9554 ArrayPointer 9555 } DiagType; 9556 if (IsAddressOf) 9557 DiagType = AddressOf; 9558 else if (IsFunction) 9559 DiagType = FunctionPointer; 9560 else if (IsArray) 9561 DiagType = ArrayPointer; 9562 else 9563 llvm_unreachable("Could not determine diagnostic."); 9564 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 9565 << Range << IsEqual; 9566 9567 if (!IsFunction) 9568 return; 9569 9570 // Suggest '&' to silence the function warning. 9571 Diag(E->getExprLoc(), diag::note_function_warning_silence) 9572 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 9573 9574 // Check to see if '()' fixit should be emitted. 9575 QualType ReturnType; 9576 UnresolvedSet<4> NonTemplateOverloads; 9577 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 9578 if (ReturnType.isNull()) 9579 return; 9580 9581 if (IsCompare) { 9582 // There are two cases here. If there is null constant, the only suggest 9583 // for a pointer return type. If the null is 0, then suggest if the return 9584 // type is a pointer or an integer type. 9585 if (!ReturnType->isPointerType()) { 9586 if (NullKind == Expr::NPCK_ZeroExpression || 9587 NullKind == Expr::NPCK_ZeroLiteral) { 9588 if (!ReturnType->isIntegerType()) 9589 return; 9590 } else { 9591 return; 9592 } 9593 } 9594 } else { // !IsCompare 9595 // For function to bool, only suggest if the function pointer has bool 9596 // return type. 9597 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 9598 return; 9599 } 9600 Diag(E->getExprLoc(), diag::note_function_to_function_call) 9601 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 9602 } 9603 9604 /// Diagnoses "dangerous" implicit conversions within the given 9605 /// expression (which is a full expression). Implements -Wconversion 9606 /// and -Wsign-compare. 9607 /// 9608 /// \param CC the "context" location of the implicit conversion, i.e. 9609 /// the most location of the syntactic entity requiring the implicit 9610 /// conversion 9611 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 9612 // Don't diagnose in unevaluated contexts. 9613 if (isUnevaluatedContext()) 9614 return; 9615 9616 // Don't diagnose for value- or type-dependent expressions. 9617 if (E->isTypeDependent() || E->isValueDependent()) 9618 return; 9619 9620 // Check for array bounds violations in cases where the check isn't triggered 9621 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 9622 // ArraySubscriptExpr is on the RHS of a variable initialization. 9623 CheckArrayAccess(E); 9624 9625 // This is not the right CC for (e.g.) a variable initialization. 9626 AnalyzeImplicitConversions(*this, E, CC); 9627 } 9628 9629 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9630 /// Input argument E is a logical expression. 9631 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 9632 ::CheckBoolLikeConversion(*this, E, CC); 9633 } 9634 9635 /// Diagnose when expression is an integer constant expression and its evaluation 9636 /// results in integer overflow 9637 void Sema::CheckForIntOverflow (Expr *E) { 9638 // Use a work list to deal with nested struct initializers. 9639 SmallVector<Expr *, 2> Exprs(1, E); 9640 9641 do { 9642 Expr *E = Exprs.pop_back_val(); 9643 9644 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 9645 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 9646 continue; 9647 } 9648 9649 if (auto InitList = dyn_cast<InitListExpr>(E)) 9650 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 9651 } while (!Exprs.empty()); 9652 } 9653 9654 namespace { 9655 /// \brief Visitor for expressions which looks for unsequenced operations on the 9656 /// same object. 9657 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 9658 typedef EvaluatedExprVisitor<SequenceChecker> Base; 9659 9660 /// \brief A tree of sequenced regions within an expression. Two regions are 9661 /// unsequenced if one is an ancestor or a descendent of the other. When we 9662 /// finish processing an expression with sequencing, such as a comma 9663 /// expression, we fold its tree nodes into its parent, since they are 9664 /// unsequenced with respect to nodes we will visit later. 9665 class SequenceTree { 9666 struct Value { 9667 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 9668 unsigned Parent : 31; 9669 unsigned Merged : 1; 9670 }; 9671 SmallVector<Value, 8> Values; 9672 9673 public: 9674 /// \brief A region within an expression which may be sequenced with respect 9675 /// to some other region. 9676 class Seq { 9677 explicit Seq(unsigned N) : Index(N) {} 9678 unsigned Index; 9679 friend class SequenceTree; 9680 public: 9681 Seq() : Index(0) {} 9682 }; 9683 9684 SequenceTree() { Values.push_back(Value(0)); } 9685 Seq root() const { return Seq(0); } 9686 9687 /// \brief Create a new sequence of operations, which is an unsequenced 9688 /// subset of \p Parent. This sequence of operations is sequenced with 9689 /// respect to other children of \p Parent. 9690 Seq allocate(Seq Parent) { 9691 Values.push_back(Value(Parent.Index)); 9692 return Seq(Values.size() - 1); 9693 } 9694 9695 /// \brief Merge a sequence of operations into its parent. 9696 void merge(Seq S) { 9697 Values[S.Index].Merged = true; 9698 } 9699 9700 /// \brief Determine whether two operations are unsequenced. This operation 9701 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 9702 /// should have been merged into its parent as appropriate. 9703 bool isUnsequenced(Seq Cur, Seq Old) { 9704 unsigned C = representative(Cur.Index); 9705 unsigned Target = representative(Old.Index); 9706 while (C >= Target) { 9707 if (C == Target) 9708 return true; 9709 C = Values[C].Parent; 9710 } 9711 return false; 9712 } 9713 9714 private: 9715 /// \brief Pick a representative for a sequence. 9716 unsigned representative(unsigned K) { 9717 if (Values[K].Merged) 9718 // Perform path compression as we go. 9719 return Values[K].Parent = representative(Values[K].Parent); 9720 return K; 9721 } 9722 }; 9723 9724 /// An object for which we can track unsequenced uses. 9725 typedef NamedDecl *Object; 9726 9727 /// Different flavors of object usage which we track. We only track the 9728 /// least-sequenced usage of each kind. 9729 enum UsageKind { 9730 /// A read of an object. Multiple unsequenced reads are OK. 9731 UK_Use, 9732 /// A modification of an object which is sequenced before the value 9733 /// computation of the expression, such as ++n in C++. 9734 UK_ModAsValue, 9735 /// A modification of an object which is not sequenced before the value 9736 /// computation of the expression, such as n++. 9737 UK_ModAsSideEffect, 9738 9739 UK_Count = UK_ModAsSideEffect + 1 9740 }; 9741 9742 struct Usage { 9743 Usage() : Use(nullptr), Seq() {} 9744 Expr *Use; 9745 SequenceTree::Seq Seq; 9746 }; 9747 9748 struct UsageInfo { 9749 UsageInfo() : Diagnosed(false) {} 9750 Usage Uses[UK_Count]; 9751 /// Have we issued a diagnostic for this variable already? 9752 bool Diagnosed; 9753 }; 9754 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 9755 9756 Sema &SemaRef; 9757 /// Sequenced regions within the expression. 9758 SequenceTree Tree; 9759 /// Declaration modifications and references which we have seen. 9760 UsageInfoMap UsageMap; 9761 /// The region we are currently within. 9762 SequenceTree::Seq Region; 9763 /// Filled in with declarations which were modified as a side-effect 9764 /// (that is, post-increment operations). 9765 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 9766 /// Expressions to check later. We defer checking these to reduce 9767 /// stack usage. 9768 SmallVectorImpl<Expr *> &WorkList; 9769 9770 /// RAII object wrapping the visitation of a sequenced subexpression of an 9771 /// expression. At the end of this process, the side-effects of the evaluation 9772 /// become sequenced with respect to the value computation of the result, so 9773 /// we downgrade any UK_ModAsSideEffect within the evaluation to 9774 /// UK_ModAsValue. 9775 struct SequencedSubexpression { 9776 SequencedSubexpression(SequenceChecker &Self) 9777 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 9778 Self.ModAsSideEffect = &ModAsSideEffect; 9779 } 9780 ~SequencedSubexpression() { 9781 for (auto &M : llvm::reverse(ModAsSideEffect)) { 9782 UsageInfo &U = Self.UsageMap[M.first]; 9783 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 9784 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 9785 SideEffectUsage = M.second; 9786 } 9787 Self.ModAsSideEffect = OldModAsSideEffect; 9788 } 9789 9790 SequenceChecker &Self; 9791 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 9792 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 9793 }; 9794 9795 /// RAII object wrapping the visitation of a subexpression which we might 9796 /// choose to evaluate as a constant. If any subexpression is evaluated and 9797 /// found to be non-constant, this allows us to suppress the evaluation of 9798 /// the outer expression. 9799 class EvaluationTracker { 9800 public: 9801 EvaluationTracker(SequenceChecker &Self) 9802 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 9803 Self.EvalTracker = this; 9804 } 9805 ~EvaluationTracker() { 9806 Self.EvalTracker = Prev; 9807 if (Prev) 9808 Prev->EvalOK &= EvalOK; 9809 } 9810 9811 bool evaluate(const Expr *E, bool &Result) { 9812 if (!EvalOK || E->isValueDependent()) 9813 return false; 9814 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 9815 return EvalOK; 9816 } 9817 9818 private: 9819 SequenceChecker &Self; 9820 EvaluationTracker *Prev; 9821 bool EvalOK; 9822 } *EvalTracker; 9823 9824 /// \brief Find the object which is produced by the specified expression, 9825 /// if any. 9826 Object getObject(Expr *E, bool Mod) const { 9827 E = E->IgnoreParenCasts(); 9828 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9829 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 9830 return getObject(UO->getSubExpr(), Mod); 9831 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9832 if (BO->getOpcode() == BO_Comma) 9833 return getObject(BO->getRHS(), Mod); 9834 if (Mod && BO->isAssignmentOp()) 9835 return getObject(BO->getLHS(), Mod); 9836 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9837 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 9838 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 9839 return ME->getMemberDecl(); 9840 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9841 // FIXME: If this is a reference, map through to its value. 9842 return DRE->getDecl(); 9843 return nullptr; 9844 } 9845 9846 /// \brief Note that an object was modified or used by an expression. 9847 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 9848 Usage &U = UI.Uses[UK]; 9849 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 9850 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 9851 ModAsSideEffect->push_back(std::make_pair(O, U)); 9852 U.Use = Ref; 9853 U.Seq = Region; 9854 } 9855 } 9856 /// \brief Check whether a modification or use conflicts with a prior usage. 9857 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 9858 bool IsModMod) { 9859 if (UI.Diagnosed) 9860 return; 9861 9862 const Usage &U = UI.Uses[OtherKind]; 9863 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 9864 return; 9865 9866 Expr *Mod = U.Use; 9867 Expr *ModOrUse = Ref; 9868 if (OtherKind == UK_Use) 9869 std::swap(Mod, ModOrUse); 9870 9871 SemaRef.Diag(Mod->getExprLoc(), 9872 IsModMod ? diag::warn_unsequenced_mod_mod 9873 : diag::warn_unsequenced_mod_use) 9874 << O << SourceRange(ModOrUse->getExprLoc()); 9875 UI.Diagnosed = true; 9876 } 9877 9878 void notePreUse(Object O, Expr *Use) { 9879 UsageInfo &U = UsageMap[O]; 9880 // Uses conflict with other modifications. 9881 checkUsage(O, U, Use, UK_ModAsValue, false); 9882 } 9883 void notePostUse(Object O, Expr *Use) { 9884 UsageInfo &U = UsageMap[O]; 9885 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 9886 addUsage(U, O, Use, UK_Use); 9887 } 9888 9889 void notePreMod(Object O, Expr *Mod) { 9890 UsageInfo &U = UsageMap[O]; 9891 // Modifications conflict with other modifications and with uses. 9892 checkUsage(O, U, Mod, UK_ModAsValue, true); 9893 checkUsage(O, U, Mod, UK_Use, false); 9894 } 9895 void notePostMod(Object O, Expr *Use, UsageKind UK) { 9896 UsageInfo &U = UsageMap[O]; 9897 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 9898 addUsage(U, O, Use, UK); 9899 } 9900 9901 public: 9902 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 9903 : Base(S.Context), SemaRef(S), Region(Tree.root()), 9904 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 9905 Visit(E); 9906 } 9907 9908 void VisitStmt(Stmt *S) { 9909 // Skip all statements which aren't expressions for now. 9910 } 9911 9912 void VisitExpr(Expr *E) { 9913 // By default, just recurse to evaluated subexpressions. 9914 Base::VisitStmt(E); 9915 } 9916 9917 void VisitCastExpr(CastExpr *E) { 9918 Object O = Object(); 9919 if (E->getCastKind() == CK_LValueToRValue) 9920 O = getObject(E->getSubExpr(), false); 9921 9922 if (O) 9923 notePreUse(O, E); 9924 VisitExpr(E); 9925 if (O) 9926 notePostUse(O, E); 9927 } 9928 9929 void VisitBinComma(BinaryOperator *BO) { 9930 // C++11 [expr.comma]p1: 9931 // Every value computation and side effect associated with the left 9932 // expression is sequenced before every value computation and side 9933 // effect associated with the right expression. 9934 SequenceTree::Seq LHS = Tree.allocate(Region); 9935 SequenceTree::Seq RHS = Tree.allocate(Region); 9936 SequenceTree::Seq OldRegion = Region; 9937 9938 { 9939 SequencedSubexpression SeqLHS(*this); 9940 Region = LHS; 9941 Visit(BO->getLHS()); 9942 } 9943 9944 Region = RHS; 9945 Visit(BO->getRHS()); 9946 9947 Region = OldRegion; 9948 9949 // Forget that LHS and RHS are sequenced. They are both unsequenced 9950 // with respect to other stuff. 9951 Tree.merge(LHS); 9952 Tree.merge(RHS); 9953 } 9954 9955 void VisitBinAssign(BinaryOperator *BO) { 9956 // The modification is sequenced after the value computation of the LHS 9957 // and RHS, so check it before inspecting the operands and update the 9958 // map afterwards. 9959 Object O = getObject(BO->getLHS(), true); 9960 if (!O) 9961 return VisitExpr(BO); 9962 9963 notePreMod(O, BO); 9964 9965 // C++11 [expr.ass]p7: 9966 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 9967 // only once. 9968 // 9969 // Therefore, for a compound assignment operator, O is considered used 9970 // everywhere except within the evaluation of E1 itself. 9971 if (isa<CompoundAssignOperator>(BO)) 9972 notePreUse(O, BO); 9973 9974 Visit(BO->getLHS()); 9975 9976 if (isa<CompoundAssignOperator>(BO)) 9977 notePostUse(O, BO); 9978 9979 Visit(BO->getRHS()); 9980 9981 // C++11 [expr.ass]p1: 9982 // the assignment is sequenced [...] before the value computation of the 9983 // assignment expression. 9984 // C11 6.5.16/3 has no such rule. 9985 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 9986 : UK_ModAsSideEffect); 9987 } 9988 9989 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 9990 VisitBinAssign(CAO); 9991 } 9992 9993 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 9994 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 9995 void VisitUnaryPreIncDec(UnaryOperator *UO) { 9996 Object O = getObject(UO->getSubExpr(), true); 9997 if (!O) 9998 return VisitExpr(UO); 9999 10000 notePreMod(O, UO); 10001 Visit(UO->getSubExpr()); 10002 // C++11 [expr.pre.incr]p1: 10003 // the expression ++x is equivalent to x+=1 10004 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10005 : UK_ModAsSideEffect); 10006 } 10007 10008 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10009 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10010 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10011 Object O = getObject(UO->getSubExpr(), true); 10012 if (!O) 10013 return VisitExpr(UO); 10014 10015 notePreMod(O, UO); 10016 Visit(UO->getSubExpr()); 10017 notePostMod(O, UO, UK_ModAsSideEffect); 10018 } 10019 10020 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10021 void VisitBinLOr(BinaryOperator *BO) { 10022 // The side-effects of the LHS of an '&&' are sequenced before the 10023 // value computation of the RHS, and hence before the value computation 10024 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10025 // as if they were unconditionally sequenced. 10026 EvaluationTracker Eval(*this); 10027 { 10028 SequencedSubexpression Sequenced(*this); 10029 Visit(BO->getLHS()); 10030 } 10031 10032 bool Result; 10033 if (Eval.evaluate(BO->getLHS(), Result)) { 10034 if (!Result) 10035 Visit(BO->getRHS()); 10036 } else { 10037 // Check for unsequenced operations in the RHS, treating it as an 10038 // entirely separate evaluation. 10039 // 10040 // FIXME: If there are operations in the RHS which are unsequenced 10041 // with respect to operations outside the RHS, and those operations 10042 // are unconditionally evaluated, diagnose them. 10043 WorkList.push_back(BO->getRHS()); 10044 } 10045 } 10046 void VisitBinLAnd(BinaryOperator *BO) { 10047 EvaluationTracker Eval(*this); 10048 { 10049 SequencedSubexpression Sequenced(*this); 10050 Visit(BO->getLHS()); 10051 } 10052 10053 bool Result; 10054 if (Eval.evaluate(BO->getLHS(), Result)) { 10055 if (Result) 10056 Visit(BO->getRHS()); 10057 } else { 10058 WorkList.push_back(BO->getRHS()); 10059 } 10060 } 10061 10062 // Only visit the condition, unless we can be sure which subexpression will 10063 // be chosen. 10064 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10065 EvaluationTracker Eval(*this); 10066 { 10067 SequencedSubexpression Sequenced(*this); 10068 Visit(CO->getCond()); 10069 } 10070 10071 bool Result; 10072 if (Eval.evaluate(CO->getCond(), Result)) 10073 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10074 else { 10075 WorkList.push_back(CO->getTrueExpr()); 10076 WorkList.push_back(CO->getFalseExpr()); 10077 } 10078 } 10079 10080 void VisitCallExpr(CallExpr *CE) { 10081 // C++11 [intro.execution]p15: 10082 // When calling a function [...], every value computation and side effect 10083 // associated with any argument expression, or with the postfix expression 10084 // designating the called function, is sequenced before execution of every 10085 // expression or statement in the body of the function [and thus before 10086 // the value computation of its result]. 10087 SequencedSubexpression Sequenced(*this); 10088 Base::VisitCallExpr(CE); 10089 10090 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10091 } 10092 10093 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10094 // This is a call, so all subexpressions are sequenced before the result. 10095 SequencedSubexpression Sequenced(*this); 10096 10097 if (!CCE->isListInitialization()) 10098 return VisitExpr(CCE); 10099 10100 // In C++11, list initializations are sequenced. 10101 SmallVector<SequenceTree::Seq, 32> Elts; 10102 SequenceTree::Seq Parent = Region; 10103 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10104 E = CCE->arg_end(); 10105 I != E; ++I) { 10106 Region = Tree.allocate(Parent); 10107 Elts.push_back(Region); 10108 Visit(*I); 10109 } 10110 10111 // Forget that the initializers are sequenced. 10112 Region = Parent; 10113 for (unsigned I = 0; I < Elts.size(); ++I) 10114 Tree.merge(Elts[I]); 10115 } 10116 10117 void VisitInitListExpr(InitListExpr *ILE) { 10118 if (!SemaRef.getLangOpts().CPlusPlus11) 10119 return VisitExpr(ILE); 10120 10121 // In C++11, list initializations are sequenced. 10122 SmallVector<SequenceTree::Seq, 32> Elts; 10123 SequenceTree::Seq Parent = Region; 10124 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10125 Expr *E = ILE->getInit(I); 10126 if (!E) continue; 10127 Region = Tree.allocate(Parent); 10128 Elts.push_back(Region); 10129 Visit(E); 10130 } 10131 10132 // Forget that the initializers are sequenced. 10133 Region = Parent; 10134 for (unsigned I = 0; I < Elts.size(); ++I) 10135 Tree.merge(Elts[I]); 10136 } 10137 }; 10138 } // end anonymous namespace 10139 10140 void Sema::CheckUnsequencedOperations(Expr *E) { 10141 SmallVector<Expr *, 8> WorkList; 10142 WorkList.push_back(E); 10143 while (!WorkList.empty()) { 10144 Expr *Item = WorkList.pop_back_val(); 10145 SequenceChecker(*this, Item, WorkList); 10146 } 10147 } 10148 10149 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10150 bool IsConstexpr) { 10151 CheckImplicitConversions(E, CheckLoc); 10152 if (!E->isInstantiationDependent()) 10153 CheckUnsequencedOperations(E); 10154 if (!IsConstexpr && !E->isValueDependent()) 10155 CheckForIntOverflow(E); 10156 DiagnoseMisalignedMembers(); 10157 } 10158 10159 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10160 FieldDecl *BitField, 10161 Expr *Init) { 10162 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10163 } 10164 10165 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10166 SourceLocation Loc) { 10167 if (!PType->isVariablyModifiedType()) 10168 return; 10169 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10170 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10171 return; 10172 } 10173 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10174 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10175 return; 10176 } 10177 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10178 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10179 return; 10180 } 10181 10182 const ArrayType *AT = S.Context.getAsArrayType(PType); 10183 if (!AT) 10184 return; 10185 10186 if (AT->getSizeModifier() != ArrayType::Star) { 10187 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10188 return; 10189 } 10190 10191 S.Diag(Loc, diag::err_array_star_in_function_definition); 10192 } 10193 10194 /// CheckParmsForFunctionDef - Check that the parameters of the given 10195 /// function are appropriate for the definition of a function. This 10196 /// takes care of any checks that cannot be performed on the 10197 /// declaration itself, e.g., that the types of each of the function 10198 /// parameters are complete. 10199 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10200 bool CheckParameterNames) { 10201 bool HasInvalidParm = false; 10202 for (ParmVarDecl *Param : Parameters) { 10203 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10204 // function declarator that is part of a function definition of 10205 // that function shall not have incomplete type. 10206 // 10207 // This is also C++ [dcl.fct]p6. 10208 if (!Param->isInvalidDecl() && 10209 RequireCompleteType(Param->getLocation(), Param->getType(), 10210 diag::err_typecheck_decl_incomplete_type)) { 10211 Param->setInvalidDecl(); 10212 HasInvalidParm = true; 10213 } 10214 10215 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10216 // declaration of each parameter shall include an identifier. 10217 if (CheckParameterNames && 10218 Param->getIdentifier() == nullptr && 10219 !Param->isImplicit() && 10220 !getLangOpts().CPlusPlus) 10221 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10222 10223 // C99 6.7.5.3p12: 10224 // If the function declarator is not part of a definition of that 10225 // function, parameters may have incomplete type and may use the [*] 10226 // notation in their sequences of declarator specifiers to specify 10227 // variable length array types. 10228 QualType PType = Param->getOriginalType(); 10229 // FIXME: This diagnostic should point the '[*]' if source-location 10230 // information is added for it. 10231 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10232 10233 // MSVC destroys objects passed by value in the callee. Therefore a 10234 // function definition which takes such a parameter must be able to call the 10235 // object's destructor. However, we don't perform any direct access check 10236 // on the dtor. 10237 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10238 .getCXXABI() 10239 .areArgsDestroyedLeftToRightInCallee()) { 10240 if (!Param->isInvalidDecl()) { 10241 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10242 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10243 if (!ClassDecl->isInvalidDecl() && 10244 !ClassDecl->hasIrrelevantDestructor() && 10245 !ClassDecl->isDependentContext()) { 10246 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10247 MarkFunctionReferenced(Param->getLocation(), Destructor); 10248 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10249 } 10250 } 10251 } 10252 } 10253 10254 // Parameters with the pass_object_size attribute only need to be marked 10255 // constant at function definitions. Because we lack information about 10256 // whether we're on a declaration or definition when we're instantiating the 10257 // attribute, we need to check for constness here. 10258 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10259 if (!Param->getType().isConstQualified()) 10260 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10261 << Attr->getSpelling() << 1; 10262 } 10263 10264 return HasInvalidParm; 10265 } 10266 10267 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10268 /// pointer cast increases the alignment requirements. 10269 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10270 // This is actually a lot of work to potentially be doing on every 10271 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10272 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10273 return; 10274 10275 // Ignore dependent types. 10276 if (T->isDependentType() || Op->getType()->isDependentType()) 10277 return; 10278 10279 // Require that the destination be a pointer type. 10280 const PointerType *DestPtr = T->getAs<PointerType>(); 10281 if (!DestPtr) return; 10282 10283 // If the destination has alignment 1, we're done. 10284 QualType DestPointee = DestPtr->getPointeeType(); 10285 if (DestPointee->isIncompleteType()) return; 10286 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10287 if (DestAlign.isOne()) return; 10288 10289 // Require that the source be a pointer type. 10290 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10291 if (!SrcPtr) return; 10292 QualType SrcPointee = SrcPtr->getPointeeType(); 10293 10294 // Whitelist casts from cv void*. We already implicitly 10295 // whitelisted casts to cv void*, since they have alignment 1. 10296 // Also whitelist casts involving incomplete types, which implicitly 10297 // includes 'void'. 10298 if (SrcPointee->isIncompleteType()) return; 10299 10300 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10301 if (SrcAlign >= DestAlign) return; 10302 10303 Diag(TRange.getBegin(), diag::warn_cast_align) 10304 << Op->getType() << T 10305 << static_cast<unsigned>(SrcAlign.getQuantity()) 10306 << static_cast<unsigned>(DestAlign.getQuantity()) 10307 << TRange << Op->getSourceRange(); 10308 } 10309 10310 /// \brief Check whether this array fits the idiom of a size-one tail padded 10311 /// array member of a struct. 10312 /// 10313 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10314 /// commonly used to emulate flexible arrays in C89 code. 10315 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10316 const NamedDecl *ND) { 10317 if (Size != 1 || !ND) return false; 10318 10319 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10320 if (!FD) return false; 10321 10322 // Don't consider sizes resulting from macro expansions or template argument 10323 // substitution to form C89 tail-padded arrays. 10324 10325 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10326 while (TInfo) { 10327 TypeLoc TL = TInfo->getTypeLoc(); 10328 // Look through typedefs. 10329 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10330 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10331 TInfo = TDL->getTypeSourceInfo(); 10332 continue; 10333 } 10334 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10335 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10336 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10337 return false; 10338 } 10339 break; 10340 } 10341 10342 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10343 if (!RD) return false; 10344 if (RD->isUnion()) return false; 10345 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10346 if (!CRD->isStandardLayout()) return false; 10347 } 10348 10349 // See if this is the last field decl in the record. 10350 const Decl *D = FD; 10351 while ((D = D->getNextDeclInContext())) 10352 if (isa<FieldDecl>(D)) 10353 return false; 10354 return true; 10355 } 10356 10357 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10358 const ArraySubscriptExpr *ASE, 10359 bool AllowOnePastEnd, bool IndexNegated) { 10360 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10361 if (IndexExpr->isValueDependent()) 10362 return; 10363 10364 const Type *EffectiveType = 10365 BaseExpr->getType()->getPointeeOrArrayElementType(); 10366 BaseExpr = BaseExpr->IgnoreParenCasts(); 10367 const ConstantArrayType *ArrayTy = 10368 Context.getAsConstantArrayType(BaseExpr->getType()); 10369 if (!ArrayTy) 10370 return; 10371 10372 llvm::APSInt index; 10373 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10374 return; 10375 if (IndexNegated) 10376 index = -index; 10377 10378 const NamedDecl *ND = nullptr; 10379 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10380 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10381 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10382 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10383 10384 if (index.isUnsigned() || !index.isNegative()) { 10385 llvm::APInt size = ArrayTy->getSize(); 10386 if (!size.isStrictlyPositive()) 10387 return; 10388 10389 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10390 if (BaseType != EffectiveType) { 10391 // Make sure we're comparing apples to apples when comparing index to size 10392 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10393 uint64_t array_typesize = Context.getTypeSize(BaseType); 10394 // Handle ptrarith_typesize being zero, such as when casting to void* 10395 if (!ptrarith_typesize) ptrarith_typesize = 1; 10396 if (ptrarith_typesize != array_typesize) { 10397 // There's a cast to a different size type involved 10398 uint64_t ratio = array_typesize / ptrarith_typesize; 10399 // TODO: Be smarter about handling cases where array_typesize is not a 10400 // multiple of ptrarith_typesize 10401 if (ptrarith_typesize * ratio == array_typesize) 10402 size *= llvm::APInt(size.getBitWidth(), ratio); 10403 } 10404 } 10405 10406 if (size.getBitWidth() > index.getBitWidth()) 10407 index = index.zext(size.getBitWidth()); 10408 else if (size.getBitWidth() < index.getBitWidth()) 10409 size = size.zext(index.getBitWidth()); 10410 10411 // For array subscripting the index must be less than size, but for pointer 10412 // arithmetic also allow the index (offset) to be equal to size since 10413 // computing the next address after the end of the array is legal and 10414 // commonly done e.g. in C++ iterators and range-based for loops. 10415 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10416 return; 10417 10418 // Also don't warn for arrays of size 1 which are members of some 10419 // structure. These are often used to approximate flexible arrays in C89 10420 // code. 10421 if (IsTailPaddedMemberArray(*this, size, ND)) 10422 return; 10423 10424 // Suppress the warning if the subscript expression (as identified by the 10425 // ']' location) and the index expression are both from macro expansions 10426 // within a system header. 10427 if (ASE) { 10428 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 10429 ASE->getRBracketLoc()); 10430 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 10431 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 10432 IndexExpr->getLocStart()); 10433 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 10434 return; 10435 } 10436 } 10437 10438 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 10439 if (ASE) 10440 DiagID = diag::warn_array_index_exceeds_bounds; 10441 10442 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10443 PDiag(DiagID) << index.toString(10, true) 10444 << size.toString(10, true) 10445 << (unsigned)size.getLimitedValue(~0U) 10446 << IndexExpr->getSourceRange()); 10447 } else { 10448 unsigned DiagID = diag::warn_array_index_precedes_bounds; 10449 if (!ASE) { 10450 DiagID = diag::warn_ptr_arith_precedes_bounds; 10451 if (index.isNegative()) index = -index; 10452 } 10453 10454 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10455 PDiag(DiagID) << index.toString(10, true) 10456 << IndexExpr->getSourceRange()); 10457 } 10458 10459 if (!ND) { 10460 // Try harder to find a NamedDecl to point at in the note. 10461 while (const ArraySubscriptExpr *ASE = 10462 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 10463 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 10464 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10465 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10466 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10467 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10468 } 10469 10470 if (ND) 10471 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 10472 PDiag(diag::note_array_index_out_of_bounds) 10473 << ND->getDeclName()); 10474 } 10475 10476 void Sema::CheckArrayAccess(const Expr *expr) { 10477 int AllowOnePastEnd = 0; 10478 while (expr) { 10479 expr = expr->IgnoreParenImpCasts(); 10480 switch (expr->getStmtClass()) { 10481 case Stmt::ArraySubscriptExprClass: { 10482 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 10483 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 10484 AllowOnePastEnd > 0); 10485 return; 10486 } 10487 case Stmt::OMPArraySectionExprClass: { 10488 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 10489 if (ASE->getLowerBound()) 10490 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 10491 /*ASE=*/nullptr, AllowOnePastEnd > 0); 10492 return; 10493 } 10494 case Stmt::UnaryOperatorClass: { 10495 // Only unwrap the * and & unary operators 10496 const UnaryOperator *UO = cast<UnaryOperator>(expr); 10497 expr = UO->getSubExpr(); 10498 switch (UO->getOpcode()) { 10499 case UO_AddrOf: 10500 AllowOnePastEnd++; 10501 break; 10502 case UO_Deref: 10503 AllowOnePastEnd--; 10504 break; 10505 default: 10506 return; 10507 } 10508 break; 10509 } 10510 case Stmt::ConditionalOperatorClass: { 10511 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 10512 if (const Expr *lhs = cond->getLHS()) 10513 CheckArrayAccess(lhs); 10514 if (const Expr *rhs = cond->getRHS()) 10515 CheckArrayAccess(rhs); 10516 return; 10517 } 10518 default: 10519 return; 10520 } 10521 } 10522 } 10523 10524 //===--- CHECK: Objective-C retain cycles ----------------------------------// 10525 10526 namespace { 10527 struct RetainCycleOwner { 10528 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 10529 VarDecl *Variable; 10530 SourceRange Range; 10531 SourceLocation Loc; 10532 bool Indirect; 10533 10534 void setLocsFrom(Expr *e) { 10535 Loc = e->getExprLoc(); 10536 Range = e->getSourceRange(); 10537 } 10538 }; 10539 } // end anonymous namespace 10540 10541 /// Consider whether capturing the given variable can possibly lead to 10542 /// a retain cycle. 10543 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 10544 // In ARC, it's captured strongly iff the variable has __strong 10545 // lifetime. In MRR, it's captured strongly if the variable is 10546 // __block and has an appropriate type. 10547 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10548 return false; 10549 10550 owner.Variable = var; 10551 if (ref) 10552 owner.setLocsFrom(ref); 10553 return true; 10554 } 10555 10556 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 10557 while (true) { 10558 e = e->IgnoreParens(); 10559 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 10560 switch (cast->getCastKind()) { 10561 case CK_BitCast: 10562 case CK_LValueBitCast: 10563 case CK_LValueToRValue: 10564 case CK_ARCReclaimReturnedObject: 10565 e = cast->getSubExpr(); 10566 continue; 10567 10568 default: 10569 return false; 10570 } 10571 } 10572 10573 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 10574 ObjCIvarDecl *ivar = ref->getDecl(); 10575 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10576 return false; 10577 10578 // Try to find a retain cycle in the base. 10579 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 10580 return false; 10581 10582 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 10583 owner.Indirect = true; 10584 return true; 10585 } 10586 10587 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 10588 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 10589 if (!var) return false; 10590 return considerVariable(var, ref, owner); 10591 } 10592 10593 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 10594 if (member->isArrow()) return false; 10595 10596 // Don't count this as an indirect ownership. 10597 e = member->getBase(); 10598 continue; 10599 } 10600 10601 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 10602 // Only pay attention to pseudo-objects on property references. 10603 ObjCPropertyRefExpr *pre 10604 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 10605 ->IgnoreParens()); 10606 if (!pre) return false; 10607 if (pre->isImplicitProperty()) return false; 10608 ObjCPropertyDecl *property = pre->getExplicitProperty(); 10609 if (!property->isRetaining() && 10610 !(property->getPropertyIvarDecl() && 10611 property->getPropertyIvarDecl()->getType() 10612 .getObjCLifetime() == Qualifiers::OCL_Strong)) 10613 return false; 10614 10615 owner.Indirect = true; 10616 if (pre->isSuperReceiver()) { 10617 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 10618 if (!owner.Variable) 10619 return false; 10620 owner.Loc = pre->getLocation(); 10621 owner.Range = pre->getSourceRange(); 10622 return true; 10623 } 10624 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 10625 ->getSourceExpr()); 10626 continue; 10627 } 10628 10629 // Array ivars? 10630 10631 return false; 10632 } 10633 } 10634 10635 namespace { 10636 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 10637 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 10638 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 10639 Context(Context), Variable(variable), Capturer(nullptr), 10640 VarWillBeReased(false) {} 10641 ASTContext &Context; 10642 VarDecl *Variable; 10643 Expr *Capturer; 10644 bool VarWillBeReased; 10645 10646 void VisitDeclRefExpr(DeclRefExpr *ref) { 10647 if (ref->getDecl() == Variable && !Capturer) 10648 Capturer = ref; 10649 } 10650 10651 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 10652 if (Capturer) return; 10653 Visit(ref->getBase()); 10654 if (Capturer && ref->isFreeIvar()) 10655 Capturer = ref; 10656 } 10657 10658 void VisitBlockExpr(BlockExpr *block) { 10659 // Look inside nested blocks 10660 if (block->getBlockDecl()->capturesVariable(Variable)) 10661 Visit(block->getBlockDecl()->getBody()); 10662 } 10663 10664 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 10665 if (Capturer) return; 10666 if (OVE->getSourceExpr()) 10667 Visit(OVE->getSourceExpr()); 10668 } 10669 void VisitBinaryOperator(BinaryOperator *BinOp) { 10670 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 10671 return; 10672 Expr *LHS = BinOp->getLHS(); 10673 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 10674 if (DRE->getDecl() != Variable) 10675 return; 10676 if (Expr *RHS = BinOp->getRHS()) { 10677 RHS = RHS->IgnoreParenCasts(); 10678 llvm::APSInt Value; 10679 VarWillBeReased = 10680 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 10681 } 10682 } 10683 } 10684 }; 10685 } // end anonymous namespace 10686 10687 /// Check whether the given argument is a block which captures a 10688 /// variable. 10689 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 10690 assert(owner.Variable && owner.Loc.isValid()); 10691 10692 e = e->IgnoreParenCasts(); 10693 10694 // Look through [^{...} copy] and Block_copy(^{...}). 10695 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 10696 Selector Cmd = ME->getSelector(); 10697 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 10698 e = ME->getInstanceReceiver(); 10699 if (!e) 10700 return nullptr; 10701 e = e->IgnoreParenCasts(); 10702 } 10703 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 10704 if (CE->getNumArgs() == 1) { 10705 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 10706 if (Fn) { 10707 const IdentifierInfo *FnI = Fn->getIdentifier(); 10708 if (FnI && FnI->isStr("_Block_copy")) { 10709 e = CE->getArg(0)->IgnoreParenCasts(); 10710 } 10711 } 10712 } 10713 } 10714 10715 BlockExpr *block = dyn_cast<BlockExpr>(e); 10716 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 10717 return nullptr; 10718 10719 FindCaptureVisitor visitor(S.Context, owner.Variable); 10720 visitor.Visit(block->getBlockDecl()->getBody()); 10721 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 10722 } 10723 10724 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 10725 RetainCycleOwner &owner) { 10726 assert(capturer); 10727 assert(owner.Variable && owner.Loc.isValid()); 10728 10729 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 10730 << owner.Variable << capturer->getSourceRange(); 10731 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 10732 << owner.Indirect << owner.Range; 10733 } 10734 10735 /// Check for a keyword selector that starts with the word 'add' or 10736 /// 'set'. 10737 static bool isSetterLikeSelector(Selector sel) { 10738 if (sel.isUnarySelector()) return false; 10739 10740 StringRef str = sel.getNameForSlot(0); 10741 while (!str.empty() && str.front() == '_') str = str.substr(1); 10742 if (str.startswith("set")) 10743 str = str.substr(3); 10744 else if (str.startswith("add")) { 10745 // Specially whitelist 'addOperationWithBlock:'. 10746 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 10747 return false; 10748 str = str.substr(3); 10749 } 10750 else 10751 return false; 10752 10753 if (str.empty()) return true; 10754 return !isLowercase(str.front()); 10755 } 10756 10757 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 10758 ObjCMessageExpr *Message) { 10759 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 10760 Message->getReceiverInterface(), 10761 NSAPI::ClassId_NSMutableArray); 10762 if (!IsMutableArray) { 10763 return None; 10764 } 10765 10766 Selector Sel = Message->getSelector(); 10767 10768 Optional<NSAPI::NSArrayMethodKind> MKOpt = 10769 S.NSAPIObj->getNSArrayMethodKind(Sel); 10770 if (!MKOpt) { 10771 return None; 10772 } 10773 10774 NSAPI::NSArrayMethodKind MK = *MKOpt; 10775 10776 switch (MK) { 10777 case NSAPI::NSMutableArr_addObject: 10778 case NSAPI::NSMutableArr_insertObjectAtIndex: 10779 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 10780 return 0; 10781 case NSAPI::NSMutableArr_replaceObjectAtIndex: 10782 return 1; 10783 10784 default: 10785 return None; 10786 } 10787 10788 return None; 10789 } 10790 10791 static 10792 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 10793 ObjCMessageExpr *Message) { 10794 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 10795 Message->getReceiverInterface(), 10796 NSAPI::ClassId_NSMutableDictionary); 10797 if (!IsMutableDictionary) { 10798 return None; 10799 } 10800 10801 Selector Sel = Message->getSelector(); 10802 10803 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 10804 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 10805 if (!MKOpt) { 10806 return None; 10807 } 10808 10809 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 10810 10811 switch (MK) { 10812 case NSAPI::NSMutableDict_setObjectForKey: 10813 case NSAPI::NSMutableDict_setValueForKey: 10814 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 10815 return 0; 10816 10817 default: 10818 return None; 10819 } 10820 10821 return None; 10822 } 10823 10824 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 10825 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 10826 Message->getReceiverInterface(), 10827 NSAPI::ClassId_NSMutableSet); 10828 10829 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 10830 Message->getReceiverInterface(), 10831 NSAPI::ClassId_NSMutableOrderedSet); 10832 if (!IsMutableSet && !IsMutableOrderedSet) { 10833 return None; 10834 } 10835 10836 Selector Sel = Message->getSelector(); 10837 10838 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 10839 if (!MKOpt) { 10840 return None; 10841 } 10842 10843 NSAPI::NSSetMethodKind MK = *MKOpt; 10844 10845 switch (MK) { 10846 case NSAPI::NSMutableSet_addObject: 10847 case NSAPI::NSOrderedSet_setObjectAtIndex: 10848 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 10849 case NSAPI::NSOrderedSet_insertObjectAtIndex: 10850 return 0; 10851 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 10852 return 1; 10853 } 10854 10855 return None; 10856 } 10857 10858 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 10859 if (!Message->isInstanceMessage()) { 10860 return; 10861 } 10862 10863 Optional<int> ArgOpt; 10864 10865 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 10866 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 10867 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 10868 return; 10869 } 10870 10871 int ArgIndex = *ArgOpt; 10872 10873 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 10874 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 10875 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 10876 } 10877 10878 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 10879 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10880 if (ArgRE->isObjCSelfExpr()) { 10881 Diag(Message->getSourceRange().getBegin(), 10882 diag::warn_objc_circular_container) 10883 << ArgRE->getDecl()->getName() << StringRef("super"); 10884 } 10885 } 10886 } else { 10887 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 10888 10889 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 10890 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 10891 } 10892 10893 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 10894 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10895 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 10896 ValueDecl *Decl = ReceiverRE->getDecl(); 10897 Diag(Message->getSourceRange().getBegin(), 10898 diag::warn_objc_circular_container) 10899 << Decl->getName() << Decl->getName(); 10900 if (!ArgRE->isObjCSelfExpr()) { 10901 Diag(Decl->getLocation(), 10902 diag::note_objc_circular_container_declared_here) 10903 << Decl->getName(); 10904 } 10905 } 10906 } 10907 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 10908 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 10909 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 10910 ObjCIvarDecl *Decl = IvarRE->getDecl(); 10911 Diag(Message->getSourceRange().getBegin(), 10912 diag::warn_objc_circular_container) 10913 << Decl->getName() << Decl->getName(); 10914 Diag(Decl->getLocation(), 10915 diag::note_objc_circular_container_declared_here) 10916 << Decl->getName(); 10917 } 10918 } 10919 } 10920 } 10921 } 10922 10923 /// Check a message send to see if it's likely to cause a retain cycle. 10924 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 10925 // Only check instance methods whose selector looks like a setter. 10926 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 10927 return; 10928 10929 // Try to find a variable that the receiver is strongly owned by. 10930 RetainCycleOwner owner; 10931 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 10932 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 10933 return; 10934 } else { 10935 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 10936 owner.Variable = getCurMethodDecl()->getSelfDecl(); 10937 owner.Loc = msg->getSuperLoc(); 10938 owner.Range = msg->getSuperLoc(); 10939 } 10940 10941 // Check whether the receiver is captured by any of the arguments. 10942 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 10943 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 10944 return diagnoseRetainCycle(*this, capturer, owner); 10945 } 10946 10947 /// Check a property assign to see if it's likely to cause a retain cycle. 10948 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 10949 RetainCycleOwner owner; 10950 if (!findRetainCycleOwner(*this, receiver, owner)) 10951 return; 10952 10953 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 10954 diagnoseRetainCycle(*this, capturer, owner); 10955 } 10956 10957 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 10958 RetainCycleOwner Owner; 10959 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 10960 return; 10961 10962 // Because we don't have an expression for the variable, we have to set the 10963 // location explicitly here. 10964 Owner.Loc = Var->getLocation(); 10965 Owner.Range = Var->getSourceRange(); 10966 10967 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 10968 diagnoseRetainCycle(*this, Capturer, Owner); 10969 } 10970 10971 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 10972 Expr *RHS, bool isProperty) { 10973 // Check if RHS is an Objective-C object literal, which also can get 10974 // immediately zapped in a weak reference. Note that we explicitly 10975 // allow ObjCStringLiterals, since those are designed to never really die. 10976 RHS = RHS->IgnoreParenImpCasts(); 10977 10978 // This enum needs to match with the 'select' in 10979 // warn_objc_arc_literal_assign (off-by-1). 10980 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 10981 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 10982 return false; 10983 10984 S.Diag(Loc, diag::warn_arc_literal_assign) 10985 << (unsigned) Kind 10986 << (isProperty ? 0 : 1) 10987 << RHS->getSourceRange(); 10988 10989 return true; 10990 } 10991 10992 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 10993 Qualifiers::ObjCLifetime LT, 10994 Expr *RHS, bool isProperty) { 10995 // Strip off any implicit cast added to get to the one ARC-specific. 10996 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 10997 if (cast->getCastKind() == CK_ARCConsumeObject) { 10998 S.Diag(Loc, diag::warn_arc_retained_assign) 10999 << (LT == Qualifiers::OCL_ExplicitNone) 11000 << (isProperty ? 0 : 1) 11001 << RHS->getSourceRange(); 11002 return true; 11003 } 11004 RHS = cast->getSubExpr(); 11005 } 11006 11007 if (LT == Qualifiers::OCL_Weak && 11008 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11009 return true; 11010 11011 return false; 11012 } 11013 11014 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11015 QualType LHS, Expr *RHS) { 11016 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11017 11018 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11019 return false; 11020 11021 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11022 return true; 11023 11024 return false; 11025 } 11026 11027 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11028 Expr *LHS, Expr *RHS) { 11029 QualType LHSType; 11030 // PropertyRef on LHS type need be directly obtained from 11031 // its declaration as it has a PseudoType. 11032 ObjCPropertyRefExpr *PRE 11033 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11034 if (PRE && !PRE->isImplicitProperty()) { 11035 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11036 if (PD) 11037 LHSType = PD->getType(); 11038 } 11039 11040 if (LHSType.isNull()) 11041 LHSType = LHS->getType(); 11042 11043 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11044 11045 if (LT == Qualifiers::OCL_Weak) { 11046 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11047 getCurFunction()->markSafeWeakUse(LHS); 11048 } 11049 11050 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11051 return; 11052 11053 // FIXME. Check for other life times. 11054 if (LT != Qualifiers::OCL_None) 11055 return; 11056 11057 if (PRE) { 11058 if (PRE->isImplicitProperty()) 11059 return; 11060 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11061 if (!PD) 11062 return; 11063 11064 unsigned Attributes = PD->getPropertyAttributes(); 11065 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11066 // when 'assign' attribute was not explicitly specified 11067 // by user, ignore it and rely on property type itself 11068 // for lifetime info. 11069 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11070 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11071 LHSType->isObjCRetainableType()) 11072 return; 11073 11074 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11075 if (cast->getCastKind() == CK_ARCConsumeObject) { 11076 Diag(Loc, diag::warn_arc_retained_property_assign) 11077 << RHS->getSourceRange(); 11078 return; 11079 } 11080 RHS = cast->getSubExpr(); 11081 } 11082 } 11083 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11084 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11085 return; 11086 } 11087 } 11088 } 11089 11090 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11091 11092 namespace { 11093 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11094 SourceLocation StmtLoc, 11095 const NullStmt *Body) { 11096 // Do not warn if the body is a macro that expands to nothing, e.g: 11097 // 11098 // #define CALL(x) 11099 // if (condition) 11100 // CALL(0); 11101 // 11102 if (Body->hasLeadingEmptyMacro()) 11103 return false; 11104 11105 // Get line numbers of statement and body. 11106 bool StmtLineInvalid; 11107 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11108 &StmtLineInvalid); 11109 if (StmtLineInvalid) 11110 return false; 11111 11112 bool BodyLineInvalid; 11113 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11114 &BodyLineInvalid); 11115 if (BodyLineInvalid) 11116 return false; 11117 11118 // Warn if null statement and body are on the same line. 11119 if (StmtLine != BodyLine) 11120 return false; 11121 11122 return true; 11123 } 11124 } // end anonymous namespace 11125 11126 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11127 const Stmt *Body, 11128 unsigned DiagID) { 11129 // Since this is a syntactic check, don't emit diagnostic for template 11130 // instantiations, this just adds noise. 11131 if (CurrentInstantiationScope) 11132 return; 11133 11134 // The body should be a null statement. 11135 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11136 if (!NBody) 11137 return; 11138 11139 // Do the usual checks. 11140 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11141 return; 11142 11143 Diag(NBody->getSemiLoc(), DiagID); 11144 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11145 } 11146 11147 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11148 const Stmt *PossibleBody) { 11149 assert(!CurrentInstantiationScope); // Ensured by caller 11150 11151 SourceLocation StmtLoc; 11152 const Stmt *Body; 11153 unsigned DiagID; 11154 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11155 StmtLoc = FS->getRParenLoc(); 11156 Body = FS->getBody(); 11157 DiagID = diag::warn_empty_for_body; 11158 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11159 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11160 Body = WS->getBody(); 11161 DiagID = diag::warn_empty_while_body; 11162 } else 11163 return; // Neither `for' nor `while'. 11164 11165 // The body should be a null statement. 11166 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11167 if (!NBody) 11168 return; 11169 11170 // Skip expensive checks if diagnostic is disabled. 11171 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11172 return; 11173 11174 // Do the usual checks. 11175 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11176 return; 11177 11178 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11179 // noise level low, emit diagnostics only if for/while is followed by a 11180 // CompoundStmt, e.g.: 11181 // for (int i = 0; i < n; i++); 11182 // { 11183 // a(i); 11184 // } 11185 // or if for/while is followed by a statement with more indentation 11186 // than for/while itself: 11187 // for (int i = 0; i < n; i++); 11188 // a(i); 11189 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11190 if (!ProbableTypo) { 11191 bool BodyColInvalid; 11192 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11193 PossibleBody->getLocStart(), 11194 &BodyColInvalid); 11195 if (BodyColInvalid) 11196 return; 11197 11198 bool StmtColInvalid; 11199 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11200 S->getLocStart(), 11201 &StmtColInvalid); 11202 if (StmtColInvalid) 11203 return; 11204 11205 if (BodyCol > StmtCol) 11206 ProbableTypo = true; 11207 } 11208 11209 if (ProbableTypo) { 11210 Diag(NBody->getSemiLoc(), DiagID); 11211 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11212 } 11213 } 11214 11215 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11216 11217 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11218 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11219 SourceLocation OpLoc) { 11220 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11221 return; 11222 11223 if (!ActiveTemplateInstantiations.empty()) 11224 return; 11225 11226 // Strip parens and casts away. 11227 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11228 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11229 11230 // Check for a call expression 11231 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11232 if (!CE || CE->getNumArgs() != 1) 11233 return; 11234 11235 // Check for a call to std::move 11236 const FunctionDecl *FD = CE->getDirectCallee(); 11237 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 11238 !FD->getIdentifier()->isStr("move")) 11239 return; 11240 11241 // Get argument from std::move 11242 RHSExpr = CE->getArg(0); 11243 11244 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11245 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11246 11247 // Two DeclRefExpr's, check that the decls are the same. 11248 if (LHSDeclRef && RHSDeclRef) { 11249 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11250 return; 11251 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11252 RHSDeclRef->getDecl()->getCanonicalDecl()) 11253 return; 11254 11255 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11256 << LHSExpr->getSourceRange() 11257 << RHSExpr->getSourceRange(); 11258 return; 11259 } 11260 11261 // Member variables require a different approach to check for self moves. 11262 // MemberExpr's are the same if every nested MemberExpr refers to the same 11263 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11264 // the base Expr's are CXXThisExpr's. 11265 const Expr *LHSBase = LHSExpr; 11266 const Expr *RHSBase = RHSExpr; 11267 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11268 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11269 if (!LHSME || !RHSME) 11270 return; 11271 11272 while (LHSME && RHSME) { 11273 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11274 RHSME->getMemberDecl()->getCanonicalDecl()) 11275 return; 11276 11277 LHSBase = LHSME->getBase(); 11278 RHSBase = RHSME->getBase(); 11279 LHSME = dyn_cast<MemberExpr>(LHSBase); 11280 RHSME = dyn_cast<MemberExpr>(RHSBase); 11281 } 11282 11283 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11284 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11285 if (LHSDeclRef && RHSDeclRef) { 11286 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11287 return; 11288 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11289 RHSDeclRef->getDecl()->getCanonicalDecl()) 11290 return; 11291 11292 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11293 << LHSExpr->getSourceRange() 11294 << RHSExpr->getSourceRange(); 11295 return; 11296 } 11297 11298 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11299 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11300 << LHSExpr->getSourceRange() 11301 << RHSExpr->getSourceRange(); 11302 } 11303 11304 //===--- Layout compatibility ----------------------------------------------// 11305 11306 namespace { 11307 11308 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11309 11310 /// \brief Check if two enumeration types are layout-compatible. 11311 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11312 // C++11 [dcl.enum] p8: 11313 // Two enumeration types are layout-compatible if they have the same 11314 // underlying type. 11315 return ED1->isComplete() && ED2->isComplete() && 11316 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11317 } 11318 11319 /// \brief Check if two fields are layout-compatible. 11320 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11321 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11322 return false; 11323 11324 if (Field1->isBitField() != Field2->isBitField()) 11325 return false; 11326 11327 if (Field1->isBitField()) { 11328 // Make sure that the bit-fields are the same length. 11329 unsigned Bits1 = Field1->getBitWidthValue(C); 11330 unsigned Bits2 = Field2->getBitWidthValue(C); 11331 11332 if (Bits1 != Bits2) 11333 return false; 11334 } 11335 11336 return true; 11337 } 11338 11339 /// \brief Check if two standard-layout structs are layout-compatible. 11340 /// (C++11 [class.mem] p17) 11341 bool isLayoutCompatibleStruct(ASTContext &C, 11342 RecordDecl *RD1, 11343 RecordDecl *RD2) { 11344 // If both records are C++ classes, check that base classes match. 11345 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11346 // If one of records is a CXXRecordDecl we are in C++ mode, 11347 // thus the other one is a CXXRecordDecl, too. 11348 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11349 // Check number of base classes. 11350 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11351 return false; 11352 11353 // Check the base classes. 11354 for (CXXRecordDecl::base_class_const_iterator 11355 Base1 = D1CXX->bases_begin(), 11356 BaseEnd1 = D1CXX->bases_end(), 11357 Base2 = D2CXX->bases_begin(); 11358 Base1 != BaseEnd1; 11359 ++Base1, ++Base2) { 11360 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11361 return false; 11362 } 11363 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11364 // If only RD2 is a C++ class, it should have zero base classes. 11365 if (D2CXX->getNumBases() > 0) 11366 return false; 11367 } 11368 11369 // Check the fields. 11370 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11371 Field2End = RD2->field_end(), 11372 Field1 = RD1->field_begin(), 11373 Field1End = RD1->field_end(); 11374 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11375 if (!isLayoutCompatible(C, *Field1, *Field2)) 11376 return false; 11377 } 11378 if (Field1 != Field1End || Field2 != Field2End) 11379 return false; 11380 11381 return true; 11382 } 11383 11384 /// \brief Check if two standard-layout unions are layout-compatible. 11385 /// (C++11 [class.mem] p18) 11386 bool isLayoutCompatibleUnion(ASTContext &C, 11387 RecordDecl *RD1, 11388 RecordDecl *RD2) { 11389 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11390 for (auto *Field2 : RD2->fields()) 11391 UnmatchedFields.insert(Field2); 11392 11393 for (auto *Field1 : RD1->fields()) { 11394 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11395 I = UnmatchedFields.begin(), 11396 E = UnmatchedFields.end(); 11397 11398 for ( ; I != E; ++I) { 11399 if (isLayoutCompatible(C, Field1, *I)) { 11400 bool Result = UnmatchedFields.erase(*I); 11401 (void) Result; 11402 assert(Result); 11403 break; 11404 } 11405 } 11406 if (I == E) 11407 return false; 11408 } 11409 11410 return UnmatchedFields.empty(); 11411 } 11412 11413 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11414 if (RD1->isUnion() != RD2->isUnion()) 11415 return false; 11416 11417 if (RD1->isUnion()) 11418 return isLayoutCompatibleUnion(C, RD1, RD2); 11419 else 11420 return isLayoutCompatibleStruct(C, RD1, RD2); 11421 } 11422 11423 /// \brief Check if two types are layout-compatible in C++11 sense. 11424 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 11425 if (T1.isNull() || T2.isNull()) 11426 return false; 11427 11428 // C++11 [basic.types] p11: 11429 // If two types T1 and T2 are the same type, then T1 and T2 are 11430 // layout-compatible types. 11431 if (C.hasSameType(T1, T2)) 11432 return true; 11433 11434 T1 = T1.getCanonicalType().getUnqualifiedType(); 11435 T2 = T2.getCanonicalType().getUnqualifiedType(); 11436 11437 const Type::TypeClass TC1 = T1->getTypeClass(); 11438 const Type::TypeClass TC2 = T2->getTypeClass(); 11439 11440 if (TC1 != TC2) 11441 return false; 11442 11443 if (TC1 == Type::Enum) { 11444 return isLayoutCompatible(C, 11445 cast<EnumType>(T1)->getDecl(), 11446 cast<EnumType>(T2)->getDecl()); 11447 } else if (TC1 == Type::Record) { 11448 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 11449 return false; 11450 11451 return isLayoutCompatible(C, 11452 cast<RecordType>(T1)->getDecl(), 11453 cast<RecordType>(T2)->getDecl()); 11454 } 11455 11456 return false; 11457 } 11458 } // end anonymous namespace 11459 11460 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 11461 11462 namespace { 11463 /// \brief Given a type tag expression find the type tag itself. 11464 /// 11465 /// \param TypeExpr Type tag expression, as it appears in user's code. 11466 /// 11467 /// \param VD Declaration of an identifier that appears in a type tag. 11468 /// 11469 /// \param MagicValue Type tag magic value. 11470 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 11471 const ValueDecl **VD, uint64_t *MagicValue) { 11472 while(true) { 11473 if (!TypeExpr) 11474 return false; 11475 11476 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 11477 11478 switch (TypeExpr->getStmtClass()) { 11479 case Stmt::UnaryOperatorClass: { 11480 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 11481 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 11482 TypeExpr = UO->getSubExpr(); 11483 continue; 11484 } 11485 return false; 11486 } 11487 11488 case Stmt::DeclRefExprClass: { 11489 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 11490 *VD = DRE->getDecl(); 11491 return true; 11492 } 11493 11494 case Stmt::IntegerLiteralClass: { 11495 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 11496 llvm::APInt MagicValueAPInt = IL->getValue(); 11497 if (MagicValueAPInt.getActiveBits() <= 64) { 11498 *MagicValue = MagicValueAPInt.getZExtValue(); 11499 return true; 11500 } else 11501 return false; 11502 } 11503 11504 case Stmt::BinaryConditionalOperatorClass: 11505 case Stmt::ConditionalOperatorClass: { 11506 const AbstractConditionalOperator *ACO = 11507 cast<AbstractConditionalOperator>(TypeExpr); 11508 bool Result; 11509 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 11510 if (Result) 11511 TypeExpr = ACO->getTrueExpr(); 11512 else 11513 TypeExpr = ACO->getFalseExpr(); 11514 continue; 11515 } 11516 return false; 11517 } 11518 11519 case Stmt::BinaryOperatorClass: { 11520 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 11521 if (BO->getOpcode() == BO_Comma) { 11522 TypeExpr = BO->getRHS(); 11523 continue; 11524 } 11525 return false; 11526 } 11527 11528 default: 11529 return false; 11530 } 11531 } 11532 } 11533 11534 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 11535 /// 11536 /// \param TypeExpr Expression that specifies a type tag. 11537 /// 11538 /// \param MagicValues Registered magic values. 11539 /// 11540 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 11541 /// kind. 11542 /// 11543 /// \param TypeInfo Information about the corresponding C type. 11544 /// 11545 /// \returns true if the corresponding C type was found. 11546 bool GetMatchingCType( 11547 const IdentifierInfo *ArgumentKind, 11548 const Expr *TypeExpr, const ASTContext &Ctx, 11549 const llvm::DenseMap<Sema::TypeTagMagicValue, 11550 Sema::TypeTagData> *MagicValues, 11551 bool &FoundWrongKind, 11552 Sema::TypeTagData &TypeInfo) { 11553 FoundWrongKind = false; 11554 11555 // Variable declaration that has type_tag_for_datatype attribute. 11556 const ValueDecl *VD = nullptr; 11557 11558 uint64_t MagicValue; 11559 11560 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 11561 return false; 11562 11563 if (VD) { 11564 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 11565 if (I->getArgumentKind() != ArgumentKind) { 11566 FoundWrongKind = true; 11567 return false; 11568 } 11569 TypeInfo.Type = I->getMatchingCType(); 11570 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 11571 TypeInfo.MustBeNull = I->getMustBeNull(); 11572 return true; 11573 } 11574 return false; 11575 } 11576 11577 if (!MagicValues) 11578 return false; 11579 11580 llvm::DenseMap<Sema::TypeTagMagicValue, 11581 Sema::TypeTagData>::const_iterator I = 11582 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 11583 if (I == MagicValues->end()) 11584 return false; 11585 11586 TypeInfo = I->second; 11587 return true; 11588 } 11589 } // end anonymous namespace 11590 11591 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 11592 uint64_t MagicValue, QualType Type, 11593 bool LayoutCompatible, 11594 bool MustBeNull) { 11595 if (!TypeTagForDatatypeMagicValues) 11596 TypeTagForDatatypeMagicValues.reset( 11597 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 11598 11599 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 11600 (*TypeTagForDatatypeMagicValues)[Magic] = 11601 TypeTagData(Type, LayoutCompatible, MustBeNull); 11602 } 11603 11604 namespace { 11605 bool IsSameCharType(QualType T1, QualType T2) { 11606 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 11607 if (!BT1) 11608 return false; 11609 11610 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 11611 if (!BT2) 11612 return false; 11613 11614 BuiltinType::Kind T1Kind = BT1->getKind(); 11615 BuiltinType::Kind T2Kind = BT2->getKind(); 11616 11617 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 11618 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 11619 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 11620 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 11621 } 11622 } // end anonymous namespace 11623 11624 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 11625 const Expr * const *ExprArgs) { 11626 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 11627 bool IsPointerAttr = Attr->getIsPointer(); 11628 11629 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 11630 bool FoundWrongKind; 11631 TypeTagData TypeInfo; 11632 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 11633 TypeTagForDatatypeMagicValues.get(), 11634 FoundWrongKind, TypeInfo)) { 11635 if (FoundWrongKind) 11636 Diag(TypeTagExpr->getExprLoc(), 11637 diag::warn_type_tag_for_datatype_wrong_kind) 11638 << TypeTagExpr->getSourceRange(); 11639 return; 11640 } 11641 11642 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 11643 if (IsPointerAttr) { 11644 // Skip implicit cast of pointer to `void *' (as a function argument). 11645 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 11646 if (ICE->getType()->isVoidPointerType() && 11647 ICE->getCastKind() == CK_BitCast) 11648 ArgumentExpr = ICE->getSubExpr(); 11649 } 11650 QualType ArgumentType = ArgumentExpr->getType(); 11651 11652 // Passing a `void*' pointer shouldn't trigger a warning. 11653 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 11654 return; 11655 11656 if (TypeInfo.MustBeNull) { 11657 // Type tag with matching void type requires a null pointer. 11658 if (!ArgumentExpr->isNullPointerConstant(Context, 11659 Expr::NPC_ValueDependentIsNotNull)) { 11660 Diag(ArgumentExpr->getExprLoc(), 11661 diag::warn_type_safety_null_pointer_required) 11662 << ArgumentKind->getName() 11663 << ArgumentExpr->getSourceRange() 11664 << TypeTagExpr->getSourceRange(); 11665 } 11666 return; 11667 } 11668 11669 QualType RequiredType = TypeInfo.Type; 11670 if (IsPointerAttr) 11671 RequiredType = Context.getPointerType(RequiredType); 11672 11673 bool mismatch = false; 11674 if (!TypeInfo.LayoutCompatible) { 11675 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 11676 11677 // C++11 [basic.fundamental] p1: 11678 // Plain char, signed char, and unsigned char are three distinct types. 11679 // 11680 // But we treat plain `char' as equivalent to `signed char' or `unsigned 11681 // char' depending on the current char signedness mode. 11682 if (mismatch) 11683 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 11684 RequiredType->getPointeeType())) || 11685 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 11686 mismatch = false; 11687 } else 11688 if (IsPointerAttr) 11689 mismatch = !isLayoutCompatible(Context, 11690 ArgumentType->getPointeeType(), 11691 RequiredType->getPointeeType()); 11692 else 11693 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 11694 11695 if (mismatch) 11696 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 11697 << ArgumentType << ArgumentKind 11698 << TypeInfo.LayoutCompatible << RequiredType 11699 << ArgumentExpr->getSourceRange() 11700 << TypeTagExpr->getSourceRange(); 11701 } 11702 11703 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 11704 CharUnits Alignment) { 11705 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 11706 } 11707 11708 void Sema::DiagnoseMisalignedMembers() { 11709 for (MisalignedMember &m : MisalignedMembers) { 11710 const NamedDecl *ND = m.RD; 11711 if (ND->getName().empty()) { 11712 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 11713 ND = TD; 11714 } 11715 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 11716 << m.MD << ND << m.E->getSourceRange(); 11717 } 11718 MisalignedMembers.clear(); 11719 } 11720 11721 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 11722 E = E->IgnoreParens(); 11723 if (!T->isPointerType() && !T->isIntegerType()) 11724 return; 11725 if (isa<UnaryOperator>(E) && 11726 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 11727 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 11728 if (isa<MemberExpr>(Op)) { 11729 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 11730 MisalignedMember(Op)); 11731 if (MA != MisalignedMembers.end() && 11732 (T->isIntegerType() || 11733 (T->isPointerType() && 11734 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment))) 11735 MisalignedMembers.erase(MA); 11736 } 11737 } 11738 } 11739 11740 void Sema::RefersToMemberWithReducedAlignment( 11741 Expr *E, 11742 std::function<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action) { 11743 const auto *ME = dyn_cast<MemberExpr>(E); 11744 if (!ME) 11745 return; 11746 11747 // For a chain of MemberExpr like "a.b.c.d" this list 11748 // will keep FieldDecl's like [d, c, b]. 11749 SmallVector<FieldDecl *, 4> ReverseMemberChain; 11750 const MemberExpr *TopME = nullptr; 11751 bool AnyIsPacked = false; 11752 do { 11753 QualType BaseType = ME->getBase()->getType(); 11754 if (ME->isArrow()) 11755 BaseType = BaseType->getPointeeType(); 11756 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 11757 11758 ValueDecl *MD = ME->getMemberDecl(); 11759 auto *FD = dyn_cast<FieldDecl>(MD); 11760 // We do not care about non-data members. 11761 if (!FD || FD->isInvalidDecl()) 11762 return; 11763 11764 AnyIsPacked = 11765 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 11766 ReverseMemberChain.push_back(FD); 11767 11768 TopME = ME; 11769 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 11770 } while (ME); 11771 assert(TopME && "We did not compute a topmost MemberExpr!"); 11772 11773 // Not the scope of this diagnostic. 11774 if (!AnyIsPacked) 11775 return; 11776 11777 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 11778 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 11779 // TODO: The innermost base of the member expression may be too complicated. 11780 // For now, just disregard these cases. This is left for future 11781 // improvement. 11782 if (!DRE && !isa<CXXThisExpr>(TopBase)) 11783 return; 11784 11785 // Alignment expected by the whole expression. 11786 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 11787 11788 // No need to do anything else with this case. 11789 if (ExpectedAlignment.isOne()) 11790 return; 11791 11792 // Synthesize offset of the whole access. 11793 CharUnits Offset; 11794 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 11795 I++) { 11796 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 11797 } 11798 11799 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 11800 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 11801 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 11802 11803 // The base expression of the innermost MemberExpr may give 11804 // stronger guarantees than the class containing the member. 11805 if (DRE && !TopME->isArrow()) { 11806 const ValueDecl *VD = DRE->getDecl(); 11807 if (!VD->getType()->isReferenceType()) 11808 CompleteObjectAlignment = 11809 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 11810 } 11811 11812 // Check if the synthesized offset fulfills the alignment. 11813 if (Offset % ExpectedAlignment != 0 || 11814 // It may fulfill the offset it but the effective alignment may still be 11815 // lower than the expected expression alignment. 11816 CompleteObjectAlignment < ExpectedAlignment) { 11817 // If this happens, we want to determine a sensible culprit of this. 11818 // Intuitively, watching the chain of member expressions from right to 11819 // left, we start with the required alignment (as required by the field 11820 // type) but some packed attribute in that chain has reduced the alignment. 11821 // It may happen that another packed structure increases it again. But if 11822 // we are here such increase has not been enough. So pointing the first 11823 // FieldDecl that either is packed or else its RecordDecl is, 11824 // seems reasonable. 11825 FieldDecl *FD = nullptr; 11826 CharUnits Alignment; 11827 for (FieldDecl *FDI : ReverseMemberChain) { 11828 if (FDI->hasAttr<PackedAttr>() || 11829 FDI->getParent()->hasAttr<PackedAttr>()) { 11830 FD = FDI; 11831 Alignment = std::min( 11832 Context.getTypeAlignInChars(FD->getType()), 11833 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 11834 break; 11835 } 11836 } 11837 assert(FD && "We did not find a packed FieldDecl!"); 11838 Action(E, FD->getParent(), FD, Alignment); 11839 } 11840 } 11841 11842 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 11843 using namespace std::placeholders; 11844 RefersToMemberWithReducedAlignment( 11845 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 11846 _2, _3, _4)); 11847 } 11848 11849