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 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 319 unsigned Start, unsigned End); 320 321 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 322 /// 'local void*' parameter of passed block. 323 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 324 Expr *BlockArg, 325 unsigned NumNonVarArgs) { 326 const BlockPointerType *BPT = 327 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 328 unsigned NumBlockParams = 329 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 330 unsigned TotalNumArgs = TheCall->getNumArgs(); 331 332 // For each argument passed to the block, a corresponding uint needs to 333 // be passed to describe the size of the local memory. 334 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 335 S.Diag(TheCall->getLocStart(), 336 diag::err_opencl_enqueue_kernel_local_size_args); 337 return true; 338 } 339 340 // Check that the sizes of the local memory are specified by integers. 341 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 342 TotalNumArgs - 1); 343 } 344 345 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 346 /// overload formats specified in Table 6.13.17.1. 347 /// int enqueue_kernel(queue_t queue, 348 /// kernel_enqueue_flags_t flags, 349 /// const ndrange_t ndrange, 350 /// void (^block)(void)) 351 /// int enqueue_kernel(queue_t queue, 352 /// kernel_enqueue_flags_t flags, 353 /// const ndrange_t ndrange, 354 /// uint num_events_in_wait_list, 355 /// clk_event_t *event_wait_list, 356 /// clk_event_t *event_ret, 357 /// void (^block)(void)) 358 /// int enqueue_kernel(queue_t queue, 359 /// kernel_enqueue_flags_t flags, 360 /// const ndrange_t ndrange, 361 /// void (^block)(local void*, ...), 362 /// uint size0, ...) 363 /// int enqueue_kernel(queue_t queue, 364 /// kernel_enqueue_flags_t flags, 365 /// const ndrange_t ndrange, 366 /// uint num_events_in_wait_list, 367 /// clk_event_t *event_wait_list, 368 /// clk_event_t *event_ret, 369 /// void (^block)(local void*, ...), 370 /// uint size0, ...) 371 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 372 unsigned NumArgs = TheCall->getNumArgs(); 373 374 if (NumArgs < 4) { 375 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 376 return true; 377 } 378 379 Expr *Arg0 = TheCall->getArg(0); 380 Expr *Arg1 = TheCall->getArg(1); 381 Expr *Arg2 = TheCall->getArg(2); 382 Expr *Arg3 = TheCall->getArg(3); 383 384 // First argument always needs to be a queue_t type. 385 if (!Arg0->getType()->isQueueT()) { 386 S.Diag(TheCall->getArg(0)->getLocStart(), 387 diag::err_opencl_enqueue_kernel_expected_type) 388 << S.Context.OCLQueueTy; 389 return true; 390 } 391 392 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 393 if (!Arg1->getType()->isIntegerType()) { 394 S.Diag(TheCall->getArg(1)->getLocStart(), 395 diag::err_opencl_enqueue_kernel_expected_type) 396 << "'kernel_enqueue_flags_t' (i.e. uint)"; 397 return true; 398 } 399 400 // Third argument is always an ndrange_t type. 401 if (!Arg2->getType()->isNDRangeT()) { 402 S.Diag(TheCall->getArg(2)->getLocStart(), 403 diag::err_opencl_enqueue_kernel_expected_type) 404 << S.Context.OCLNDRangeTy; 405 return true; 406 } 407 408 // With four arguments, there is only one form that the function could be 409 // called in: no events and no variable arguments. 410 if (NumArgs == 4) { 411 // check that the last argument is the right block type. 412 if (!isBlockPointer(Arg3)) { 413 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 414 << "block"; 415 return true; 416 } 417 // we have a block type, check the prototype 418 const BlockPointerType *BPT = 419 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 420 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 421 S.Diag(Arg3->getLocStart(), 422 diag::err_opencl_enqueue_kernel_blocks_no_args); 423 return true; 424 } 425 return false; 426 } 427 // we can have block + varargs. 428 if (isBlockPointer(Arg3)) 429 return (checkOpenCLBlockArgs(S, Arg3) || 430 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 431 // last two cases with either exactly 7 args or 7 args and varargs. 432 if (NumArgs >= 7) { 433 // check common block argument. 434 Expr *Arg6 = TheCall->getArg(6); 435 if (!isBlockPointer(Arg6)) { 436 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 437 << "block"; 438 return true; 439 } 440 if (checkOpenCLBlockArgs(S, Arg6)) 441 return true; 442 443 // Forth argument has to be any integer type. 444 if (!Arg3->getType()->isIntegerType()) { 445 S.Diag(TheCall->getArg(3)->getLocStart(), 446 diag::err_opencl_enqueue_kernel_expected_type) 447 << "integer"; 448 return true; 449 } 450 // check remaining common arguments. 451 Expr *Arg4 = TheCall->getArg(4); 452 Expr *Arg5 = TheCall->getArg(5); 453 454 // Fith argument is always passed as pointers to clk_event_t. 455 if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 456 S.Diag(TheCall->getArg(4)->getLocStart(), 457 diag::err_opencl_enqueue_kernel_expected_type) 458 << S.Context.getPointerType(S.Context.OCLClkEventTy); 459 return true; 460 } 461 462 // Sixth argument is always passed as pointers to clk_event_t. 463 if (!(Arg5->getType()->isPointerType() && 464 Arg5->getType()->getPointeeType()->isClkEventT())) { 465 S.Diag(TheCall->getArg(5)->getLocStart(), 466 diag::err_opencl_enqueue_kernel_expected_type) 467 << S.Context.getPointerType(S.Context.OCLClkEventTy); 468 return true; 469 } 470 471 if (NumArgs == 7) 472 return false; 473 474 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 475 } 476 477 // None of the specific case has been detected, give generic error 478 S.Diag(TheCall->getLocStart(), 479 diag::err_opencl_enqueue_kernel_incorrect_args); 480 return true; 481 } 482 483 /// Returns OpenCL access qual. 484 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 485 return D->getAttr<OpenCLAccessAttr>(); 486 } 487 488 /// Returns true if pipe element type is different from the pointer. 489 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 490 const Expr *Arg0 = Call->getArg(0); 491 // First argument type should always be pipe. 492 if (!Arg0->getType()->isPipeType()) { 493 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 494 << Call->getDirectCallee() << Arg0->getSourceRange(); 495 return true; 496 } 497 OpenCLAccessAttr *AccessQual = 498 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 499 // Validates the access qualifier is compatible with the call. 500 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 501 // read_only and write_only, and assumed to be read_only if no qualifier is 502 // specified. 503 switch (Call->getDirectCallee()->getBuiltinID()) { 504 case Builtin::BIread_pipe: 505 case Builtin::BIreserve_read_pipe: 506 case Builtin::BIcommit_read_pipe: 507 case Builtin::BIwork_group_reserve_read_pipe: 508 case Builtin::BIsub_group_reserve_read_pipe: 509 case Builtin::BIwork_group_commit_read_pipe: 510 case Builtin::BIsub_group_commit_read_pipe: 511 if (!(!AccessQual || AccessQual->isReadOnly())) { 512 S.Diag(Arg0->getLocStart(), 513 diag::err_opencl_builtin_pipe_invalid_access_modifier) 514 << "read_only" << Arg0->getSourceRange(); 515 return true; 516 } 517 break; 518 case Builtin::BIwrite_pipe: 519 case Builtin::BIreserve_write_pipe: 520 case Builtin::BIcommit_write_pipe: 521 case Builtin::BIwork_group_reserve_write_pipe: 522 case Builtin::BIsub_group_reserve_write_pipe: 523 case Builtin::BIwork_group_commit_write_pipe: 524 case Builtin::BIsub_group_commit_write_pipe: 525 if (!(AccessQual && AccessQual->isWriteOnly())) { 526 S.Diag(Arg0->getLocStart(), 527 diag::err_opencl_builtin_pipe_invalid_access_modifier) 528 << "write_only" << Arg0->getSourceRange(); 529 return true; 530 } 531 break; 532 default: 533 break; 534 } 535 return false; 536 } 537 538 /// Returns true if pipe element type is different from the pointer. 539 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 540 const Expr *Arg0 = Call->getArg(0); 541 const Expr *ArgIdx = Call->getArg(Idx); 542 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 543 const QualType EltTy = PipeTy->getElementType(); 544 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 545 // The Idx argument should be a pointer and the type of the pointer and 546 // the type of pipe element should also be the same. 547 if (!ArgTy || 548 !S.Context.hasSameType( 549 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 550 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 551 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 552 << ArgIdx->getType() << ArgIdx->getSourceRange(); 553 return true; 554 } 555 return false; 556 } 557 558 // \brief Performs semantic analysis for the read/write_pipe call. 559 // \param S Reference to the semantic analyzer. 560 // \param Call A pointer to the builtin call. 561 // \return True if a semantic error has been found, false otherwise. 562 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 563 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 564 // functions have two forms. 565 switch (Call->getNumArgs()) { 566 case 2: { 567 if (checkOpenCLPipeArg(S, Call)) 568 return true; 569 // The call with 2 arguments should be 570 // read/write_pipe(pipe T, T*). 571 // Check packet type T. 572 if (checkOpenCLPipePacketType(S, Call, 1)) 573 return true; 574 } break; 575 576 case 4: { 577 if (checkOpenCLPipeArg(S, Call)) 578 return true; 579 // The call with 4 arguments should be 580 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 581 // Check reserve_id_t. 582 if (!Call->getArg(1)->getType()->isReserveIDT()) { 583 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 584 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 585 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 586 return true; 587 } 588 589 // Check the index. 590 const Expr *Arg2 = Call->getArg(2); 591 if (!Arg2->getType()->isIntegerType() && 592 !Arg2->getType()->isUnsignedIntegerType()) { 593 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 594 << Call->getDirectCallee() << S.Context.UnsignedIntTy 595 << Arg2->getType() << Arg2->getSourceRange(); 596 return true; 597 } 598 599 // Check packet type T. 600 if (checkOpenCLPipePacketType(S, Call, 3)) 601 return true; 602 } break; 603 default: 604 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 605 << Call->getDirectCallee() << Call->getSourceRange(); 606 return true; 607 } 608 609 return false; 610 } 611 612 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 613 // /_}reserve_{read/write}_pipe 614 // \param S Reference to the semantic analyzer. 615 // \param Call The call to the builtin function to be analyzed. 616 // \return True if a semantic error was found, false otherwise. 617 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 618 if (checkArgCount(S, Call, 2)) 619 return true; 620 621 if (checkOpenCLPipeArg(S, Call)) 622 return true; 623 624 // Check the reserve size. 625 if (!Call->getArg(1)->getType()->isIntegerType() && 626 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 627 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 628 << Call->getDirectCallee() << S.Context.UnsignedIntTy 629 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 630 return true; 631 } 632 633 return false; 634 } 635 636 // \brief Performs a semantic analysis on {work_group_/sub_group_ 637 // /_}commit_{read/write}_pipe 638 // \param S Reference to the semantic analyzer. 639 // \param Call The call to the builtin function to be analyzed. 640 // \return True if a semantic error was found, false otherwise. 641 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 642 if (checkArgCount(S, Call, 2)) 643 return true; 644 645 if (checkOpenCLPipeArg(S, Call)) 646 return true; 647 648 // Check reserve_id_t. 649 if (!Call->getArg(1)->getType()->isReserveIDT()) { 650 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 651 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 652 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 653 return true; 654 } 655 656 return false; 657 } 658 659 // \brief Performs a semantic analysis on the call to built-in Pipe 660 // Query Functions. 661 // \param S Reference to the semantic analyzer. 662 // \param Call The call to the builtin function to be analyzed. 663 // \return True if a semantic error was found, false otherwise. 664 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 665 if (checkArgCount(S, Call, 1)) 666 return true; 667 668 if (!Call->getArg(0)->getType()->isPipeType()) { 669 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 670 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 671 return true; 672 } 673 674 return false; 675 } 676 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 677 // \brief Performs semantic analysis for the to_global/local/private call. 678 // \param S Reference to the semantic analyzer. 679 // \param BuiltinID ID of the builtin function. 680 // \param Call A pointer to the builtin call. 681 // \return True if a semantic error has been found, false otherwise. 682 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 683 CallExpr *Call) { 684 if (Call->getNumArgs() != 1) { 685 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 686 << Call->getDirectCallee() << Call->getSourceRange(); 687 return true; 688 } 689 690 auto RT = Call->getArg(0)->getType(); 691 if (!RT->isPointerType() || RT->getPointeeType() 692 .getAddressSpace() == LangAS::opencl_constant) { 693 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 694 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 695 return true; 696 } 697 698 RT = RT->getPointeeType(); 699 auto Qual = RT.getQualifiers(); 700 switch (BuiltinID) { 701 case Builtin::BIto_global: 702 Qual.setAddressSpace(LangAS::opencl_global); 703 break; 704 case Builtin::BIto_local: 705 Qual.setAddressSpace(LangAS::opencl_local); 706 break; 707 default: 708 Qual.removeAddressSpace(); 709 } 710 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 711 RT.getUnqualifiedType(), Qual))); 712 713 return false; 714 } 715 716 ExprResult 717 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 718 CallExpr *TheCall) { 719 ExprResult TheCallResult(TheCall); 720 721 // Find out if any arguments are required to be integer constant expressions. 722 unsigned ICEArguments = 0; 723 ASTContext::GetBuiltinTypeError Error; 724 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 725 if (Error != ASTContext::GE_None) 726 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 727 728 // If any arguments are required to be ICE's, check and diagnose. 729 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 730 // Skip arguments not required to be ICE's. 731 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 732 733 llvm::APSInt Result; 734 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 735 return true; 736 ICEArguments &= ~(1 << ArgNo); 737 } 738 739 switch (BuiltinID) { 740 case Builtin::BI__builtin___CFStringMakeConstantString: 741 assert(TheCall->getNumArgs() == 1 && 742 "Wrong # arguments to builtin CFStringMakeConstantString"); 743 if (CheckObjCString(TheCall->getArg(0))) 744 return ExprError(); 745 break; 746 case Builtin::BI__builtin_stdarg_start: 747 case Builtin::BI__builtin_va_start: 748 if (SemaBuiltinVAStart(TheCall)) 749 return ExprError(); 750 break; 751 case Builtin::BI__va_start: { 752 switch (Context.getTargetInfo().getTriple().getArch()) { 753 case llvm::Triple::arm: 754 case llvm::Triple::thumb: 755 if (SemaBuiltinVAStartARM(TheCall)) 756 return ExprError(); 757 break; 758 default: 759 if (SemaBuiltinVAStart(TheCall)) 760 return ExprError(); 761 break; 762 } 763 break; 764 } 765 case Builtin::BI__builtin_isgreater: 766 case Builtin::BI__builtin_isgreaterequal: 767 case Builtin::BI__builtin_isless: 768 case Builtin::BI__builtin_islessequal: 769 case Builtin::BI__builtin_islessgreater: 770 case Builtin::BI__builtin_isunordered: 771 if (SemaBuiltinUnorderedCompare(TheCall)) 772 return ExprError(); 773 break; 774 case Builtin::BI__builtin_fpclassify: 775 if (SemaBuiltinFPClassification(TheCall, 6)) 776 return ExprError(); 777 break; 778 case Builtin::BI__builtin_isfinite: 779 case Builtin::BI__builtin_isinf: 780 case Builtin::BI__builtin_isinf_sign: 781 case Builtin::BI__builtin_isnan: 782 case Builtin::BI__builtin_isnormal: 783 if (SemaBuiltinFPClassification(TheCall, 1)) 784 return ExprError(); 785 break; 786 case Builtin::BI__builtin_shufflevector: 787 return SemaBuiltinShuffleVector(TheCall); 788 // TheCall will be freed by the smart pointer here, but that's fine, since 789 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 790 case Builtin::BI__builtin_prefetch: 791 if (SemaBuiltinPrefetch(TheCall)) 792 return ExprError(); 793 break; 794 case Builtin::BI__assume: 795 case Builtin::BI__builtin_assume: 796 if (SemaBuiltinAssume(TheCall)) 797 return ExprError(); 798 break; 799 case Builtin::BI__builtin_assume_aligned: 800 if (SemaBuiltinAssumeAligned(TheCall)) 801 return ExprError(); 802 break; 803 case Builtin::BI__builtin_object_size: 804 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 805 return ExprError(); 806 break; 807 case Builtin::BI__builtin_longjmp: 808 if (SemaBuiltinLongjmp(TheCall)) 809 return ExprError(); 810 break; 811 case Builtin::BI__builtin_setjmp: 812 if (SemaBuiltinSetjmp(TheCall)) 813 return ExprError(); 814 break; 815 case Builtin::BI_setjmp: 816 case Builtin::BI_setjmpex: 817 if (checkArgCount(*this, TheCall, 1)) 818 return true; 819 break; 820 821 case Builtin::BI__builtin_classify_type: 822 if (checkArgCount(*this, TheCall, 1)) return true; 823 TheCall->setType(Context.IntTy); 824 break; 825 case Builtin::BI__builtin_constant_p: 826 if (checkArgCount(*this, TheCall, 1)) return true; 827 TheCall->setType(Context.IntTy); 828 break; 829 case Builtin::BI__sync_fetch_and_add: 830 case Builtin::BI__sync_fetch_and_add_1: 831 case Builtin::BI__sync_fetch_and_add_2: 832 case Builtin::BI__sync_fetch_and_add_4: 833 case Builtin::BI__sync_fetch_and_add_8: 834 case Builtin::BI__sync_fetch_and_add_16: 835 case Builtin::BI__sync_fetch_and_sub: 836 case Builtin::BI__sync_fetch_and_sub_1: 837 case Builtin::BI__sync_fetch_and_sub_2: 838 case Builtin::BI__sync_fetch_and_sub_4: 839 case Builtin::BI__sync_fetch_and_sub_8: 840 case Builtin::BI__sync_fetch_and_sub_16: 841 case Builtin::BI__sync_fetch_and_or: 842 case Builtin::BI__sync_fetch_and_or_1: 843 case Builtin::BI__sync_fetch_and_or_2: 844 case Builtin::BI__sync_fetch_and_or_4: 845 case Builtin::BI__sync_fetch_and_or_8: 846 case Builtin::BI__sync_fetch_and_or_16: 847 case Builtin::BI__sync_fetch_and_and: 848 case Builtin::BI__sync_fetch_and_and_1: 849 case Builtin::BI__sync_fetch_and_and_2: 850 case Builtin::BI__sync_fetch_and_and_4: 851 case Builtin::BI__sync_fetch_and_and_8: 852 case Builtin::BI__sync_fetch_and_and_16: 853 case Builtin::BI__sync_fetch_and_xor: 854 case Builtin::BI__sync_fetch_and_xor_1: 855 case Builtin::BI__sync_fetch_and_xor_2: 856 case Builtin::BI__sync_fetch_and_xor_4: 857 case Builtin::BI__sync_fetch_and_xor_8: 858 case Builtin::BI__sync_fetch_and_xor_16: 859 case Builtin::BI__sync_fetch_and_nand: 860 case Builtin::BI__sync_fetch_and_nand_1: 861 case Builtin::BI__sync_fetch_and_nand_2: 862 case Builtin::BI__sync_fetch_and_nand_4: 863 case Builtin::BI__sync_fetch_and_nand_8: 864 case Builtin::BI__sync_fetch_and_nand_16: 865 case Builtin::BI__sync_add_and_fetch: 866 case Builtin::BI__sync_add_and_fetch_1: 867 case Builtin::BI__sync_add_and_fetch_2: 868 case Builtin::BI__sync_add_and_fetch_4: 869 case Builtin::BI__sync_add_and_fetch_8: 870 case Builtin::BI__sync_add_and_fetch_16: 871 case Builtin::BI__sync_sub_and_fetch: 872 case Builtin::BI__sync_sub_and_fetch_1: 873 case Builtin::BI__sync_sub_and_fetch_2: 874 case Builtin::BI__sync_sub_and_fetch_4: 875 case Builtin::BI__sync_sub_and_fetch_8: 876 case Builtin::BI__sync_sub_and_fetch_16: 877 case Builtin::BI__sync_and_and_fetch: 878 case Builtin::BI__sync_and_and_fetch_1: 879 case Builtin::BI__sync_and_and_fetch_2: 880 case Builtin::BI__sync_and_and_fetch_4: 881 case Builtin::BI__sync_and_and_fetch_8: 882 case Builtin::BI__sync_and_and_fetch_16: 883 case Builtin::BI__sync_or_and_fetch: 884 case Builtin::BI__sync_or_and_fetch_1: 885 case Builtin::BI__sync_or_and_fetch_2: 886 case Builtin::BI__sync_or_and_fetch_4: 887 case Builtin::BI__sync_or_and_fetch_8: 888 case Builtin::BI__sync_or_and_fetch_16: 889 case Builtin::BI__sync_xor_and_fetch: 890 case Builtin::BI__sync_xor_and_fetch_1: 891 case Builtin::BI__sync_xor_and_fetch_2: 892 case Builtin::BI__sync_xor_and_fetch_4: 893 case Builtin::BI__sync_xor_and_fetch_8: 894 case Builtin::BI__sync_xor_and_fetch_16: 895 case Builtin::BI__sync_nand_and_fetch: 896 case Builtin::BI__sync_nand_and_fetch_1: 897 case Builtin::BI__sync_nand_and_fetch_2: 898 case Builtin::BI__sync_nand_and_fetch_4: 899 case Builtin::BI__sync_nand_and_fetch_8: 900 case Builtin::BI__sync_nand_and_fetch_16: 901 case Builtin::BI__sync_val_compare_and_swap: 902 case Builtin::BI__sync_val_compare_and_swap_1: 903 case Builtin::BI__sync_val_compare_and_swap_2: 904 case Builtin::BI__sync_val_compare_and_swap_4: 905 case Builtin::BI__sync_val_compare_and_swap_8: 906 case Builtin::BI__sync_val_compare_and_swap_16: 907 case Builtin::BI__sync_bool_compare_and_swap: 908 case Builtin::BI__sync_bool_compare_and_swap_1: 909 case Builtin::BI__sync_bool_compare_and_swap_2: 910 case Builtin::BI__sync_bool_compare_and_swap_4: 911 case Builtin::BI__sync_bool_compare_and_swap_8: 912 case Builtin::BI__sync_bool_compare_and_swap_16: 913 case Builtin::BI__sync_lock_test_and_set: 914 case Builtin::BI__sync_lock_test_and_set_1: 915 case Builtin::BI__sync_lock_test_and_set_2: 916 case Builtin::BI__sync_lock_test_and_set_4: 917 case Builtin::BI__sync_lock_test_and_set_8: 918 case Builtin::BI__sync_lock_test_and_set_16: 919 case Builtin::BI__sync_lock_release: 920 case Builtin::BI__sync_lock_release_1: 921 case Builtin::BI__sync_lock_release_2: 922 case Builtin::BI__sync_lock_release_4: 923 case Builtin::BI__sync_lock_release_8: 924 case Builtin::BI__sync_lock_release_16: 925 case Builtin::BI__sync_swap: 926 case Builtin::BI__sync_swap_1: 927 case Builtin::BI__sync_swap_2: 928 case Builtin::BI__sync_swap_4: 929 case Builtin::BI__sync_swap_8: 930 case Builtin::BI__sync_swap_16: 931 return SemaBuiltinAtomicOverloaded(TheCallResult); 932 case Builtin::BI__builtin_nontemporal_load: 933 case Builtin::BI__builtin_nontemporal_store: 934 return SemaBuiltinNontemporalOverloaded(TheCallResult); 935 #define BUILTIN(ID, TYPE, ATTRS) 936 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 937 case Builtin::BI##ID: \ 938 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 939 #include "clang/Basic/Builtins.def" 940 case Builtin::BI__builtin_annotation: 941 if (SemaBuiltinAnnotation(*this, TheCall)) 942 return ExprError(); 943 break; 944 case Builtin::BI__builtin_addressof: 945 if (SemaBuiltinAddressof(*this, TheCall)) 946 return ExprError(); 947 break; 948 case Builtin::BI__builtin_add_overflow: 949 case Builtin::BI__builtin_sub_overflow: 950 case Builtin::BI__builtin_mul_overflow: 951 if (SemaBuiltinOverflow(*this, TheCall)) 952 return ExprError(); 953 break; 954 case Builtin::BI__builtin_operator_new: 955 case Builtin::BI__builtin_operator_delete: 956 if (!getLangOpts().CPlusPlus) { 957 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 958 << (BuiltinID == Builtin::BI__builtin_operator_new 959 ? "__builtin_operator_new" 960 : "__builtin_operator_delete") 961 << "C++"; 962 return ExprError(); 963 } 964 // CodeGen assumes it can find the global new and delete to call, 965 // so ensure that they are declared. 966 DeclareGlobalNewDelete(); 967 break; 968 969 // check secure string manipulation functions where overflows 970 // are detectable at compile time 971 case Builtin::BI__builtin___memcpy_chk: 972 case Builtin::BI__builtin___memmove_chk: 973 case Builtin::BI__builtin___memset_chk: 974 case Builtin::BI__builtin___strlcat_chk: 975 case Builtin::BI__builtin___strlcpy_chk: 976 case Builtin::BI__builtin___strncat_chk: 977 case Builtin::BI__builtin___strncpy_chk: 978 case Builtin::BI__builtin___stpncpy_chk: 979 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 980 break; 981 case Builtin::BI__builtin___memccpy_chk: 982 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 983 break; 984 case Builtin::BI__builtin___snprintf_chk: 985 case Builtin::BI__builtin___vsnprintf_chk: 986 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 987 break; 988 case Builtin::BI__builtin_call_with_static_chain: 989 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 990 return ExprError(); 991 break; 992 case Builtin::BI__exception_code: 993 case Builtin::BI_exception_code: 994 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 995 diag::err_seh___except_block)) 996 return ExprError(); 997 break; 998 case Builtin::BI__exception_info: 999 case Builtin::BI_exception_info: 1000 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1001 diag::err_seh___except_filter)) 1002 return ExprError(); 1003 break; 1004 case Builtin::BI__GetExceptionInfo: 1005 if (checkArgCount(*this, TheCall, 1)) 1006 return ExprError(); 1007 1008 if (CheckCXXThrowOperand( 1009 TheCall->getLocStart(), 1010 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1011 TheCall)) 1012 return ExprError(); 1013 1014 TheCall->setType(Context.VoidPtrTy); 1015 break; 1016 // OpenCL v2.0, s6.13.16 - Pipe functions 1017 case Builtin::BIread_pipe: 1018 case Builtin::BIwrite_pipe: 1019 // Since those two functions are declared with var args, we need a semantic 1020 // check for the argument. 1021 if (SemaBuiltinRWPipe(*this, TheCall)) 1022 return ExprError(); 1023 TheCall->setType(Context.IntTy); 1024 break; 1025 case Builtin::BIreserve_read_pipe: 1026 case Builtin::BIreserve_write_pipe: 1027 case Builtin::BIwork_group_reserve_read_pipe: 1028 case Builtin::BIwork_group_reserve_write_pipe: 1029 case Builtin::BIsub_group_reserve_read_pipe: 1030 case Builtin::BIsub_group_reserve_write_pipe: 1031 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1032 return ExprError(); 1033 // Since return type of reserve_read/write_pipe built-in function is 1034 // reserve_id_t, which is not defined in the builtin def file , we used int 1035 // as return type and need to override the return type of these functions. 1036 TheCall->setType(Context.OCLReserveIDTy); 1037 break; 1038 case Builtin::BIcommit_read_pipe: 1039 case Builtin::BIcommit_write_pipe: 1040 case Builtin::BIwork_group_commit_read_pipe: 1041 case Builtin::BIwork_group_commit_write_pipe: 1042 case Builtin::BIsub_group_commit_read_pipe: 1043 case Builtin::BIsub_group_commit_write_pipe: 1044 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1045 return ExprError(); 1046 break; 1047 case Builtin::BIget_pipe_num_packets: 1048 case Builtin::BIget_pipe_max_packets: 1049 if (SemaBuiltinPipePackets(*this, TheCall)) 1050 return ExprError(); 1051 TheCall->setType(Context.UnsignedIntTy); 1052 break; 1053 case Builtin::BIto_global: 1054 case Builtin::BIto_local: 1055 case Builtin::BIto_private: 1056 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1057 return ExprError(); 1058 break; 1059 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1060 case Builtin::BIenqueue_kernel: 1061 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1062 return ExprError(); 1063 break; 1064 case Builtin::BIget_kernel_work_group_size: 1065 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1066 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1067 return ExprError(); 1068 } 1069 1070 // Since the target specific builtins for each arch overlap, only check those 1071 // of the arch we are compiling for. 1072 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1073 switch (Context.getTargetInfo().getTriple().getArch()) { 1074 case llvm::Triple::arm: 1075 case llvm::Triple::armeb: 1076 case llvm::Triple::thumb: 1077 case llvm::Triple::thumbeb: 1078 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1079 return ExprError(); 1080 break; 1081 case llvm::Triple::aarch64: 1082 case llvm::Triple::aarch64_be: 1083 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1084 return ExprError(); 1085 break; 1086 case llvm::Triple::mips: 1087 case llvm::Triple::mipsel: 1088 case llvm::Triple::mips64: 1089 case llvm::Triple::mips64el: 1090 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1091 return ExprError(); 1092 break; 1093 case llvm::Triple::systemz: 1094 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1095 return ExprError(); 1096 break; 1097 case llvm::Triple::x86: 1098 case llvm::Triple::x86_64: 1099 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1100 return ExprError(); 1101 break; 1102 case llvm::Triple::ppc: 1103 case llvm::Triple::ppc64: 1104 case llvm::Triple::ppc64le: 1105 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1106 return ExprError(); 1107 break; 1108 default: 1109 break; 1110 } 1111 } 1112 1113 return TheCallResult; 1114 } 1115 1116 // Get the valid immediate range for the specified NEON type code. 1117 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1118 NeonTypeFlags Type(t); 1119 int IsQuad = ForceQuad ? true : Type.isQuad(); 1120 switch (Type.getEltType()) { 1121 case NeonTypeFlags::Int8: 1122 case NeonTypeFlags::Poly8: 1123 return shift ? 7 : (8 << IsQuad) - 1; 1124 case NeonTypeFlags::Int16: 1125 case NeonTypeFlags::Poly16: 1126 return shift ? 15 : (4 << IsQuad) - 1; 1127 case NeonTypeFlags::Int32: 1128 return shift ? 31 : (2 << IsQuad) - 1; 1129 case NeonTypeFlags::Int64: 1130 case NeonTypeFlags::Poly64: 1131 return shift ? 63 : (1 << IsQuad) - 1; 1132 case NeonTypeFlags::Poly128: 1133 return shift ? 127 : (1 << IsQuad) - 1; 1134 case NeonTypeFlags::Float16: 1135 assert(!shift && "cannot shift float types!"); 1136 return (4 << IsQuad) - 1; 1137 case NeonTypeFlags::Float32: 1138 assert(!shift && "cannot shift float types!"); 1139 return (2 << IsQuad) - 1; 1140 case NeonTypeFlags::Float64: 1141 assert(!shift && "cannot shift float types!"); 1142 return (1 << IsQuad) - 1; 1143 } 1144 llvm_unreachable("Invalid NeonTypeFlag!"); 1145 } 1146 1147 /// getNeonEltType - Return the QualType corresponding to the elements of 1148 /// the vector type specified by the NeonTypeFlags. This is used to check 1149 /// the pointer arguments for Neon load/store intrinsics. 1150 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1151 bool IsPolyUnsigned, bool IsInt64Long) { 1152 switch (Flags.getEltType()) { 1153 case NeonTypeFlags::Int8: 1154 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1155 case NeonTypeFlags::Int16: 1156 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1157 case NeonTypeFlags::Int32: 1158 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1159 case NeonTypeFlags::Int64: 1160 if (IsInt64Long) 1161 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1162 else 1163 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1164 : Context.LongLongTy; 1165 case NeonTypeFlags::Poly8: 1166 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1167 case NeonTypeFlags::Poly16: 1168 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1169 case NeonTypeFlags::Poly64: 1170 if (IsInt64Long) 1171 return Context.UnsignedLongTy; 1172 else 1173 return Context.UnsignedLongLongTy; 1174 case NeonTypeFlags::Poly128: 1175 break; 1176 case NeonTypeFlags::Float16: 1177 return Context.HalfTy; 1178 case NeonTypeFlags::Float32: 1179 return Context.FloatTy; 1180 case NeonTypeFlags::Float64: 1181 return Context.DoubleTy; 1182 } 1183 llvm_unreachable("Invalid NeonTypeFlag!"); 1184 } 1185 1186 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1187 llvm::APSInt Result; 1188 uint64_t mask = 0; 1189 unsigned TV = 0; 1190 int PtrArgNum = -1; 1191 bool HasConstPtr = false; 1192 switch (BuiltinID) { 1193 #define GET_NEON_OVERLOAD_CHECK 1194 #include "clang/Basic/arm_neon.inc" 1195 #undef GET_NEON_OVERLOAD_CHECK 1196 } 1197 1198 // For NEON intrinsics which are overloaded on vector element type, validate 1199 // the immediate which specifies which variant to emit. 1200 unsigned ImmArg = TheCall->getNumArgs()-1; 1201 if (mask) { 1202 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1203 return true; 1204 1205 TV = Result.getLimitedValue(64); 1206 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1207 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1208 << TheCall->getArg(ImmArg)->getSourceRange(); 1209 } 1210 1211 if (PtrArgNum >= 0) { 1212 // Check that pointer arguments have the specified type. 1213 Expr *Arg = TheCall->getArg(PtrArgNum); 1214 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1215 Arg = ICE->getSubExpr(); 1216 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1217 QualType RHSTy = RHS.get()->getType(); 1218 1219 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1220 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64; 1221 bool IsInt64Long = 1222 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1223 QualType EltTy = 1224 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1225 if (HasConstPtr) 1226 EltTy = EltTy.withConst(); 1227 QualType LHSTy = Context.getPointerType(EltTy); 1228 AssignConvertType ConvTy; 1229 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1230 if (RHS.isInvalid()) 1231 return true; 1232 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1233 RHS.get(), AA_Assigning)) 1234 return true; 1235 } 1236 1237 // For NEON intrinsics which take an immediate value as part of the 1238 // instruction, range check them here. 1239 unsigned i = 0, l = 0, u = 0; 1240 switch (BuiltinID) { 1241 default: 1242 return false; 1243 #define GET_NEON_IMMEDIATE_CHECK 1244 #include "clang/Basic/arm_neon.inc" 1245 #undef GET_NEON_IMMEDIATE_CHECK 1246 } 1247 1248 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1249 } 1250 1251 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1252 unsigned MaxWidth) { 1253 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1254 BuiltinID == ARM::BI__builtin_arm_ldaex || 1255 BuiltinID == ARM::BI__builtin_arm_strex || 1256 BuiltinID == ARM::BI__builtin_arm_stlex || 1257 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1258 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1259 BuiltinID == AArch64::BI__builtin_arm_strex || 1260 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1261 "unexpected ARM builtin"); 1262 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1263 BuiltinID == ARM::BI__builtin_arm_ldaex || 1264 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1265 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1266 1267 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1268 1269 // Ensure that we have the proper number of arguments. 1270 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1271 return true; 1272 1273 // Inspect the pointer argument of the atomic builtin. This should always be 1274 // a pointer type, whose element is an integral scalar or pointer type. 1275 // Because it is a pointer type, we don't have to worry about any implicit 1276 // casts here. 1277 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1278 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1279 if (PointerArgRes.isInvalid()) 1280 return true; 1281 PointerArg = PointerArgRes.get(); 1282 1283 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1284 if (!pointerType) { 1285 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1286 << PointerArg->getType() << PointerArg->getSourceRange(); 1287 return true; 1288 } 1289 1290 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1291 // task is to insert the appropriate casts into the AST. First work out just 1292 // what the appropriate type is. 1293 QualType ValType = pointerType->getPointeeType(); 1294 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1295 if (IsLdrex) 1296 AddrType.addConst(); 1297 1298 // Issue a warning if the cast is dodgy. 1299 CastKind CastNeeded = CK_NoOp; 1300 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1301 CastNeeded = CK_BitCast; 1302 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1303 << PointerArg->getType() 1304 << Context.getPointerType(AddrType) 1305 << AA_Passing << PointerArg->getSourceRange(); 1306 } 1307 1308 // Finally, do the cast and replace the argument with the corrected version. 1309 AddrType = Context.getPointerType(AddrType); 1310 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1311 if (PointerArgRes.isInvalid()) 1312 return true; 1313 PointerArg = PointerArgRes.get(); 1314 1315 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1316 1317 // In general, we allow ints, floats and pointers to be loaded and stored. 1318 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1319 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1320 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1321 << PointerArg->getType() << PointerArg->getSourceRange(); 1322 return true; 1323 } 1324 1325 // But ARM doesn't have instructions to deal with 128-bit versions. 1326 if (Context.getTypeSize(ValType) > MaxWidth) { 1327 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1328 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1329 << PointerArg->getType() << PointerArg->getSourceRange(); 1330 return true; 1331 } 1332 1333 switch (ValType.getObjCLifetime()) { 1334 case Qualifiers::OCL_None: 1335 case Qualifiers::OCL_ExplicitNone: 1336 // okay 1337 break; 1338 1339 case Qualifiers::OCL_Weak: 1340 case Qualifiers::OCL_Strong: 1341 case Qualifiers::OCL_Autoreleasing: 1342 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1343 << ValType << PointerArg->getSourceRange(); 1344 return true; 1345 } 1346 1347 if (IsLdrex) { 1348 TheCall->setType(ValType); 1349 return false; 1350 } 1351 1352 // Initialize the argument to be stored. 1353 ExprResult ValArg = TheCall->getArg(0); 1354 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1355 Context, ValType, /*consume*/ false); 1356 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1357 if (ValArg.isInvalid()) 1358 return true; 1359 TheCall->setArg(0, ValArg.get()); 1360 1361 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1362 // but the custom checker bypasses all default analysis. 1363 TheCall->setType(Context.IntTy); 1364 return false; 1365 } 1366 1367 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1368 llvm::APSInt Result; 1369 1370 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1371 BuiltinID == ARM::BI__builtin_arm_ldaex || 1372 BuiltinID == ARM::BI__builtin_arm_strex || 1373 BuiltinID == ARM::BI__builtin_arm_stlex) { 1374 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1375 } 1376 1377 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1378 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1379 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1380 } 1381 1382 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1383 BuiltinID == ARM::BI__builtin_arm_wsr64) 1384 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1385 1386 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1387 BuiltinID == ARM::BI__builtin_arm_rsrp || 1388 BuiltinID == ARM::BI__builtin_arm_wsr || 1389 BuiltinID == ARM::BI__builtin_arm_wsrp) 1390 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1391 1392 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1393 return true; 1394 1395 // For intrinsics which take an immediate value as part of the instruction, 1396 // range check them here. 1397 unsigned i = 0, l = 0, u = 0; 1398 switch (BuiltinID) { 1399 default: return false; 1400 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1401 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1402 case ARM::BI__builtin_arm_vcvtr_f: 1403 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1404 case ARM::BI__builtin_arm_dmb: 1405 case ARM::BI__builtin_arm_dsb: 1406 case ARM::BI__builtin_arm_isb: 1407 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1408 } 1409 1410 // FIXME: VFP Intrinsics should error if VFP not present. 1411 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1412 } 1413 1414 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1415 CallExpr *TheCall) { 1416 llvm::APSInt Result; 1417 1418 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1419 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1420 BuiltinID == AArch64::BI__builtin_arm_strex || 1421 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1422 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1423 } 1424 1425 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1426 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1427 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1428 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1429 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1430 } 1431 1432 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1433 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1434 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1435 1436 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1437 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1438 BuiltinID == AArch64::BI__builtin_arm_wsr || 1439 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1440 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1441 1442 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1443 return true; 1444 1445 // For intrinsics which take an immediate value as part of the instruction, 1446 // range check them here. 1447 unsigned i = 0, l = 0, u = 0; 1448 switch (BuiltinID) { 1449 default: return false; 1450 case AArch64::BI__builtin_arm_dmb: 1451 case AArch64::BI__builtin_arm_dsb: 1452 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1453 } 1454 1455 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1456 } 1457 1458 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1459 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1460 // ordering for DSP is unspecified. MSA is ordered by the data format used 1461 // by the underlying instruction i.e., df/m, df/n and then by size. 1462 // 1463 // FIXME: The size tests here should instead be tablegen'd along with the 1464 // definitions from include/clang/Basic/BuiltinsMips.def. 1465 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1466 // be too. 1467 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1468 unsigned i = 0, l = 0, u = 0, m = 0; 1469 switch (BuiltinID) { 1470 default: return false; 1471 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1472 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1473 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1474 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1475 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1476 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1477 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1478 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1479 // df/m field. 1480 // These intrinsics take an unsigned 3 bit immediate. 1481 case Mips::BI__builtin_msa_bclri_b: 1482 case Mips::BI__builtin_msa_bnegi_b: 1483 case Mips::BI__builtin_msa_bseti_b: 1484 case Mips::BI__builtin_msa_sat_s_b: 1485 case Mips::BI__builtin_msa_sat_u_b: 1486 case Mips::BI__builtin_msa_slli_b: 1487 case Mips::BI__builtin_msa_srai_b: 1488 case Mips::BI__builtin_msa_srari_b: 1489 case Mips::BI__builtin_msa_srli_b: 1490 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1491 case Mips::BI__builtin_msa_binsli_b: 1492 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1493 // These intrinsics take an unsigned 4 bit immediate. 1494 case Mips::BI__builtin_msa_bclri_h: 1495 case Mips::BI__builtin_msa_bnegi_h: 1496 case Mips::BI__builtin_msa_bseti_h: 1497 case Mips::BI__builtin_msa_sat_s_h: 1498 case Mips::BI__builtin_msa_sat_u_h: 1499 case Mips::BI__builtin_msa_slli_h: 1500 case Mips::BI__builtin_msa_srai_h: 1501 case Mips::BI__builtin_msa_srari_h: 1502 case Mips::BI__builtin_msa_srli_h: 1503 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1504 case Mips::BI__builtin_msa_binsli_h: 1505 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1506 // These intrinsics take an unsigned 5 bit immedate. 1507 // The first block of intrinsics actually have an unsigned 5 bit field, 1508 // not a df/n field. 1509 case Mips::BI__builtin_msa_clei_u_b: 1510 case Mips::BI__builtin_msa_clei_u_h: 1511 case Mips::BI__builtin_msa_clei_u_w: 1512 case Mips::BI__builtin_msa_clei_u_d: 1513 case Mips::BI__builtin_msa_clti_u_b: 1514 case Mips::BI__builtin_msa_clti_u_h: 1515 case Mips::BI__builtin_msa_clti_u_w: 1516 case Mips::BI__builtin_msa_clti_u_d: 1517 case Mips::BI__builtin_msa_maxi_u_b: 1518 case Mips::BI__builtin_msa_maxi_u_h: 1519 case Mips::BI__builtin_msa_maxi_u_w: 1520 case Mips::BI__builtin_msa_maxi_u_d: 1521 case Mips::BI__builtin_msa_mini_u_b: 1522 case Mips::BI__builtin_msa_mini_u_h: 1523 case Mips::BI__builtin_msa_mini_u_w: 1524 case Mips::BI__builtin_msa_mini_u_d: 1525 case Mips::BI__builtin_msa_addvi_b: 1526 case Mips::BI__builtin_msa_addvi_h: 1527 case Mips::BI__builtin_msa_addvi_w: 1528 case Mips::BI__builtin_msa_addvi_d: 1529 case Mips::BI__builtin_msa_bclri_w: 1530 case Mips::BI__builtin_msa_bnegi_w: 1531 case Mips::BI__builtin_msa_bseti_w: 1532 case Mips::BI__builtin_msa_sat_s_w: 1533 case Mips::BI__builtin_msa_sat_u_w: 1534 case Mips::BI__builtin_msa_slli_w: 1535 case Mips::BI__builtin_msa_srai_w: 1536 case Mips::BI__builtin_msa_srari_w: 1537 case Mips::BI__builtin_msa_srli_w: 1538 case Mips::BI__builtin_msa_srlri_w: 1539 case Mips::BI__builtin_msa_subvi_b: 1540 case Mips::BI__builtin_msa_subvi_h: 1541 case Mips::BI__builtin_msa_subvi_w: 1542 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1543 case Mips::BI__builtin_msa_binsli_w: 1544 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1545 // These intrinsics take an unsigned 6 bit immediate. 1546 case Mips::BI__builtin_msa_bclri_d: 1547 case Mips::BI__builtin_msa_bnegi_d: 1548 case Mips::BI__builtin_msa_bseti_d: 1549 case Mips::BI__builtin_msa_sat_s_d: 1550 case Mips::BI__builtin_msa_sat_u_d: 1551 case Mips::BI__builtin_msa_slli_d: 1552 case Mips::BI__builtin_msa_srai_d: 1553 case Mips::BI__builtin_msa_srari_d: 1554 case Mips::BI__builtin_msa_srli_d: 1555 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1556 case Mips::BI__builtin_msa_binsli_d: 1557 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1558 // These intrinsics take a signed 5 bit immediate. 1559 case Mips::BI__builtin_msa_ceqi_b: 1560 case Mips::BI__builtin_msa_ceqi_h: 1561 case Mips::BI__builtin_msa_ceqi_w: 1562 case Mips::BI__builtin_msa_ceqi_d: 1563 case Mips::BI__builtin_msa_clti_s_b: 1564 case Mips::BI__builtin_msa_clti_s_h: 1565 case Mips::BI__builtin_msa_clti_s_w: 1566 case Mips::BI__builtin_msa_clti_s_d: 1567 case Mips::BI__builtin_msa_clei_s_b: 1568 case Mips::BI__builtin_msa_clei_s_h: 1569 case Mips::BI__builtin_msa_clei_s_w: 1570 case Mips::BI__builtin_msa_clei_s_d: 1571 case Mips::BI__builtin_msa_maxi_s_b: 1572 case Mips::BI__builtin_msa_maxi_s_h: 1573 case Mips::BI__builtin_msa_maxi_s_w: 1574 case Mips::BI__builtin_msa_maxi_s_d: 1575 case Mips::BI__builtin_msa_mini_s_b: 1576 case Mips::BI__builtin_msa_mini_s_h: 1577 case Mips::BI__builtin_msa_mini_s_w: 1578 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1579 // These intrinsics take an unsigned 8 bit immediate. 1580 case Mips::BI__builtin_msa_andi_b: 1581 case Mips::BI__builtin_msa_nori_b: 1582 case Mips::BI__builtin_msa_ori_b: 1583 case Mips::BI__builtin_msa_shf_b: 1584 case Mips::BI__builtin_msa_shf_h: 1585 case Mips::BI__builtin_msa_shf_w: 1586 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1587 case Mips::BI__builtin_msa_bseli_b: 1588 case Mips::BI__builtin_msa_bmnzi_b: 1589 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1590 // df/n format 1591 // These intrinsics take an unsigned 4 bit immediate. 1592 case Mips::BI__builtin_msa_copy_s_b: 1593 case Mips::BI__builtin_msa_copy_u_b: 1594 case Mips::BI__builtin_msa_insve_b: 1595 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1596 case Mips::BI__builtin_msa_sld_b: 1597 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1598 // These intrinsics take an unsigned 3 bit immediate. 1599 case Mips::BI__builtin_msa_copy_s_h: 1600 case Mips::BI__builtin_msa_copy_u_h: 1601 case Mips::BI__builtin_msa_insve_h: 1602 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1603 case Mips::BI__builtin_msa_sld_h: 1604 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1605 // These intrinsics take an unsigned 2 bit immediate. 1606 case Mips::BI__builtin_msa_copy_s_w: 1607 case Mips::BI__builtin_msa_copy_u_w: 1608 case Mips::BI__builtin_msa_insve_w: 1609 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1610 case Mips::BI__builtin_msa_sld_w: 1611 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1612 // These intrinsics take an unsigned 1 bit immediate. 1613 case Mips::BI__builtin_msa_copy_s_d: 1614 case Mips::BI__builtin_msa_copy_u_d: 1615 case Mips::BI__builtin_msa_insve_d: 1616 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1617 case Mips::BI__builtin_msa_sld_d: 1618 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1619 // Memory offsets and immediate loads. 1620 // These intrinsics take a signed 10 bit immediate. 1621 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break; 1622 case Mips::BI__builtin_msa_ldi_h: 1623 case Mips::BI__builtin_msa_ldi_w: 1624 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1625 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1626 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1627 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1628 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1629 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1630 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1631 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1632 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1633 } 1634 1635 if (!m) 1636 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1637 1638 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1639 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1640 } 1641 1642 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1643 unsigned i = 0, l = 0, u = 0; 1644 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1645 BuiltinID == PPC::BI__builtin_divdeu || 1646 BuiltinID == PPC::BI__builtin_bpermd; 1647 bool IsTarget64Bit = Context.getTargetInfo() 1648 .getTypeWidth(Context 1649 .getTargetInfo() 1650 .getIntPtrType()) == 64; 1651 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1652 BuiltinID == PPC::BI__builtin_divweu || 1653 BuiltinID == PPC::BI__builtin_divde || 1654 BuiltinID == PPC::BI__builtin_divdeu; 1655 1656 if (Is64BitBltin && !IsTarget64Bit) 1657 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1658 << TheCall->getSourceRange(); 1659 1660 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1661 (BuiltinID == PPC::BI__builtin_bpermd && 1662 !Context.getTargetInfo().hasFeature("bpermd"))) 1663 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1664 << TheCall->getSourceRange(); 1665 1666 switch (BuiltinID) { 1667 default: return false; 1668 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1669 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1670 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1671 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1672 case PPC::BI__builtin_tbegin: 1673 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1674 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1675 case PPC::BI__builtin_tabortwc: 1676 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1677 case PPC::BI__builtin_tabortwci: 1678 case PPC::BI__builtin_tabortdci: 1679 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1680 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1681 } 1682 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1683 } 1684 1685 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1686 CallExpr *TheCall) { 1687 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1688 Expr *Arg = TheCall->getArg(0); 1689 llvm::APSInt AbortCode(32); 1690 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1691 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1692 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1693 << Arg->getSourceRange(); 1694 } 1695 1696 // For intrinsics which take an immediate value as part of the instruction, 1697 // range check them here. 1698 unsigned i = 0, l = 0, u = 0; 1699 switch (BuiltinID) { 1700 default: return false; 1701 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1702 case SystemZ::BI__builtin_s390_verimb: 1703 case SystemZ::BI__builtin_s390_verimh: 1704 case SystemZ::BI__builtin_s390_verimf: 1705 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1706 case SystemZ::BI__builtin_s390_vfaeb: 1707 case SystemZ::BI__builtin_s390_vfaeh: 1708 case SystemZ::BI__builtin_s390_vfaef: 1709 case SystemZ::BI__builtin_s390_vfaebs: 1710 case SystemZ::BI__builtin_s390_vfaehs: 1711 case SystemZ::BI__builtin_s390_vfaefs: 1712 case SystemZ::BI__builtin_s390_vfaezb: 1713 case SystemZ::BI__builtin_s390_vfaezh: 1714 case SystemZ::BI__builtin_s390_vfaezf: 1715 case SystemZ::BI__builtin_s390_vfaezbs: 1716 case SystemZ::BI__builtin_s390_vfaezhs: 1717 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1718 case SystemZ::BI__builtin_s390_vfidb: 1719 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1720 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1721 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1722 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1723 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1724 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1725 case SystemZ::BI__builtin_s390_vstrcb: 1726 case SystemZ::BI__builtin_s390_vstrch: 1727 case SystemZ::BI__builtin_s390_vstrcf: 1728 case SystemZ::BI__builtin_s390_vstrczb: 1729 case SystemZ::BI__builtin_s390_vstrczh: 1730 case SystemZ::BI__builtin_s390_vstrczf: 1731 case SystemZ::BI__builtin_s390_vstrcbs: 1732 case SystemZ::BI__builtin_s390_vstrchs: 1733 case SystemZ::BI__builtin_s390_vstrcfs: 1734 case SystemZ::BI__builtin_s390_vstrczbs: 1735 case SystemZ::BI__builtin_s390_vstrczhs: 1736 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1737 } 1738 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1739 } 1740 1741 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1742 /// This checks that the target supports __builtin_cpu_supports and 1743 /// that the string argument is constant and valid. 1744 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1745 Expr *Arg = TheCall->getArg(0); 1746 1747 // Check if the argument is a string literal. 1748 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1749 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1750 << Arg->getSourceRange(); 1751 1752 // Check the contents of the string. 1753 StringRef Feature = 1754 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1755 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1756 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1757 << Arg->getSourceRange(); 1758 return false; 1759 } 1760 1761 // Check if the rounding mode is legal. 1762 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1763 // Indicates if this instruction has rounding control or just SAE. 1764 bool HasRC = false; 1765 1766 unsigned ArgNum = 0; 1767 switch (BuiltinID) { 1768 default: 1769 return false; 1770 case X86::BI__builtin_ia32_vcvttsd2si32: 1771 case X86::BI__builtin_ia32_vcvttsd2si64: 1772 case X86::BI__builtin_ia32_vcvttsd2usi32: 1773 case X86::BI__builtin_ia32_vcvttsd2usi64: 1774 case X86::BI__builtin_ia32_vcvttss2si32: 1775 case X86::BI__builtin_ia32_vcvttss2si64: 1776 case X86::BI__builtin_ia32_vcvttss2usi32: 1777 case X86::BI__builtin_ia32_vcvttss2usi64: 1778 ArgNum = 1; 1779 break; 1780 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1781 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1782 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1783 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1784 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1785 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1786 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1787 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1788 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1789 case X86::BI__builtin_ia32_exp2pd_mask: 1790 case X86::BI__builtin_ia32_exp2ps_mask: 1791 case X86::BI__builtin_ia32_getexppd512_mask: 1792 case X86::BI__builtin_ia32_getexpps512_mask: 1793 case X86::BI__builtin_ia32_rcp28pd_mask: 1794 case X86::BI__builtin_ia32_rcp28ps_mask: 1795 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1796 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1797 case X86::BI__builtin_ia32_vcomisd: 1798 case X86::BI__builtin_ia32_vcomiss: 1799 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1800 ArgNum = 3; 1801 break; 1802 case X86::BI__builtin_ia32_cmppd512_mask: 1803 case X86::BI__builtin_ia32_cmpps512_mask: 1804 case X86::BI__builtin_ia32_cmpsd_mask: 1805 case X86::BI__builtin_ia32_cmpss_mask: 1806 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1807 case X86::BI__builtin_ia32_getexpss128_round_mask: 1808 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1809 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1810 case X86::BI__builtin_ia32_reducepd512_mask: 1811 case X86::BI__builtin_ia32_reduceps512_mask: 1812 case X86::BI__builtin_ia32_rndscalepd_mask: 1813 case X86::BI__builtin_ia32_rndscaleps_mask: 1814 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1815 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1816 ArgNum = 4; 1817 break; 1818 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1819 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1820 case X86::BI__builtin_ia32_fixupimmps512_mask: 1821 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1822 case X86::BI__builtin_ia32_fixupimmsd_mask: 1823 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1824 case X86::BI__builtin_ia32_fixupimmss_mask: 1825 case X86::BI__builtin_ia32_fixupimmss_maskz: 1826 case X86::BI__builtin_ia32_rangepd512_mask: 1827 case X86::BI__builtin_ia32_rangeps512_mask: 1828 case X86::BI__builtin_ia32_rangesd128_round_mask: 1829 case X86::BI__builtin_ia32_rangess128_round_mask: 1830 case X86::BI__builtin_ia32_reducesd_mask: 1831 case X86::BI__builtin_ia32_reducess_mask: 1832 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1833 case X86::BI__builtin_ia32_rndscaless_round_mask: 1834 ArgNum = 5; 1835 break; 1836 case X86::BI__builtin_ia32_vcvtsd2si64: 1837 case X86::BI__builtin_ia32_vcvtsd2si32: 1838 case X86::BI__builtin_ia32_vcvtsd2usi32: 1839 case X86::BI__builtin_ia32_vcvtsd2usi64: 1840 case X86::BI__builtin_ia32_vcvtss2si32: 1841 case X86::BI__builtin_ia32_vcvtss2si64: 1842 case X86::BI__builtin_ia32_vcvtss2usi32: 1843 case X86::BI__builtin_ia32_vcvtss2usi64: 1844 ArgNum = 1; 1845 HasRC = true; 1846 break; 1847 case X86::BI__builtin_ia32_cvtusi2sd64: 1848 case X86::BI__builtin_ia32_cvtusi2ss32: 1849 case X86::BI__builtin_ia32_cvtusi2ss64: 1850 ArgNum = 2; 1851 HasRC = true; 1852 break; 1853 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1854 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1855 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1856 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1857 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1858 case X86::BI__builtin_ia32_cvtps2qq512_mask: 1859 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 1860 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 1861 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 1862 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 1863 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 1864 ArgNum = 3; 1865 HasRC = true; 1866 break; 1867 case X86::BI__builtin_ia32_addpd512_mask: 1868 case X86::BI__builtin_ia32_addps512_mask: 1869 case X86::BI__builtin_ia32_divpd512_mask: 1870 case X86::BI__builtin_ia32_divps512_mask: 1871 case X86::BI__builtin_ia32_mulpd512_mask: 1872 case X86::BI__builtin_ia32_mulps512_mask: 1873 case X86::BI__builtin_ia32_subpd512_mask: 1874 case X86::BI__builtin_ia32_subps512_mask: 1875 case X86::BI__builtin_ia32_addss_round_mask: 1876 case X86::BI__builtin_ia32_addsd_round_mask: 1877 case X86::BI__builtin_ia32_divss_round_mask: 1878 case X86::BI__builtin_ia32_divsd_round_mask: 1879 case X86::BI__builtin_ia32_mulss_round_mask: 1880 case X86::BI__builtin_ia32_mulsd_round_mask: 1881 case X86::BI__builtin_ia32_subss_round_mask: 1882 case X86::BI__builtin_ia32_subsd_round_mask: 1883 case X86::BI__builtin_ia32_scalefpd512_mask: 1884 case X86::BI__builtin_ia32_scalefps512_mask: 1885 case X86::BI__builtin_ia32_scalefsd_round_mask: 1886 case X86::BI__builtin_ia32_scalefss_round_mask: 1887 case X86::BI__builtin_ia32_getmantpd512_mask: 1888 case X86::BI__builtin_ia32_getmantps512_mask: 1889 case X86::BI__builtin_ia32_vfmaddpd512_mask: 1890 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 1891 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 1892 case X86::BI__builtin_ia32_vfmaddps512_mask: 1893 case X86::BI__builtin_ia32_vfmaddps512_mask3: 1894 case X86::BI__builtin_ia32_vfmaddps512_maskz: 1895 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 1896 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 1897 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 1898 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 1899 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 1900 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 1901 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 1902 case X86::BI__builtin_ia32_vfmsubps512_mask3: 1903 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 1904 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 1905 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 1906 case X86::BI__builtin_ia32_vfnmaddps512_mask: 1907 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 1908 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 1909 case X86::BI__builtin_ia32_vfnmsubps512_mask: 1910 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 1911 case X86::BI__builtin_ia32_vfmaddsd3_mask: 1912 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 1913 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 1914 case X86::BI__builtin_ia32_vfmaddss3_mask: 1915 case X86::BI__builtin_ia32_vfmaddss3_maskz: 1916 case X86::BI__builtin_ia32_vfmaddss3_mask3: 1917 ArgNum = 4; 1918 HasRC = true; 1919 break; 1920 case X86::BI__builtin_ia32_getmantsd_round_mask: 1921 case X86::BI__builtin_ia32_getmantss_round_mask: 1922 ArgNum = 5; 1923 HasRC = true; 1924 break; 1925 } 1926 1927 llvm::APSInt Result; 1928 1929 // We can't check the value of a dependent argument. 1930 Expr *Arg = TheCall->getArg(ArgNum); 1931 if (Arg->isTypeDependent() || Arg->isValueDependent()) 1932 return false; 1933 1934 // Check constant-ness first. 1935 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 1936 return true; 1937 1938 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 1939 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 1940 // combined with ROUND_NO_EXC. 1941 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 1942 Result == 8/*ROUND_NO_EXC*/ || 1943 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 1944 return false; 1945 1946 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 1947 << Arg->getSourceRange(); 1948 } 1949 1950 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1951 if (BuiltinID == X86::BI__builtin_cpu_supports) 1952 return SemaBuiltinCpuSupports(*this, TheCall); 1953 1954 if (BuiltinID == X86::BI__builtin_ms_va_start) 1955 return SemaBuiltinMSVAStart(TheCall); 1956 1957 // If the intrinsic has rounding or SAE make sure its valid. 1958 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 1959 return true; 1960 1961 // For intrinsics which take an immediate value as part of the instruction, 1962 // range check them here. 1963 int i = 0, l = 0, u = 0; 1964 switch (BuiltinID) { 1965 default: 1966 return false; 1967 case X86::BI__builtin_ia32_extractf64x4_mask: 1968 case X86::BI__builtin_ia32_extracti64x4_mask: 1969 case X86::BI__builtin_ia32_extractf32x8_mask: 1970 case X86::BI__builtin_ia32_extracti32x8_mask: 1971 case X86::BI__builtin_ia32_extractf64x2_256_mask: 1972 case X86::BI__builtin_ia32_extracti64x2_256_mask: 1973 case X86::BI__builtin_ia32_extractf32x4_256_mask: 1974 case X86::BI__builtin_ia32_extracti32x4_256_mask: 1975 i = 1; l = 0; u = 1; 1976 break; 1977 case X86::BI_mm_prefetch: 1978 case X86::BI__builtin_ia32_extractf32x4_mask: 1979 case X86::BI__builtin_ia32_extracti32x4_mask: 1980 case X86::BI__builtin_ia32_extractf64x2_512_mask: 1981 case X86::BI__builtin_ia32_extracti64x2_512_mask: 1982 i = 1; l = 0; u = 3; 1983 break; 1984 case X86::BI__builtin_ia32_insertf32x8_mask: 1985 case X86::BI__builtin_ia32_inserti32x8_mask: 1986 case X86::BI__builtin_ia32_insertf64x4_mask: 1987 case X86::BI__builtin_ia32_inserti64x4_mask: 1988 case X86::BI__builtin_ia32_insertf64x2_256_mask: 1989 case X86::BI__builtin_ia32_inserti64x2_256_mask: 1990 case X86::BI__builtin_ia32_insertf32x4_256_mask: 1991 case X86::BI__builtin_ia32_inserti32x4_256_mask: 1992 i = 2; l = 0; u = 1; 1993 break; 1994 case X86::BI__builtin_ia32_sha1rnds4: 1995 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 1996 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 1997 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 1998 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 1999 case X86::BI__builtin_ia32_insertf64x2_512_mask: 2000 case X86::BI__builtin_ia32_inserti64x2_512_mask: 2001 case X86::BI__builtin_ia32_insertf32x4_mask: 2002 case X86::BI__builtin_ia32_inserti32x4_mask: 2003 i = 2; l = 0; u = 3; 2004 break; 2005 case X86::BI__builtin_ia32_vpermil2pd: 2006 case X86::BI__builtin_ia32_vpermil2pd256: 2007 case X86::BI__builtin_ia32_vpermil2ps: 2008 case X86::BI__builtin_ia32_vpermil2ps256: 2009 i = 3; l = 0; u = 3; 2010 break; 2011 case X86::BI__builtin_ia32_cmpb128_mask: 2012 case X86::BI__builtin_ia32_cmpw128_mask: 2013 case X86::BI__builtin_ia32_cmpd128_mask: 2014 case X86::BI__builtin_ia32_cmpq128_mask: 2015 case X86::BI__builtin_ia32_cmpb256_mask: 2016 case X86::BI__builtin_ia32_cmpw256_mask: 2017 case X86::BI__builtin_ia32_cmpd256_mask: 2018 case X86::BI__builtin_ia32_cmpq256_mask: 2019 case X86::BI__builtin_ia32_cmpb512_mask: 2020 case X86::BI__builtin_ia32_cmpw512_mask: 2021 case X86::BI__builtin_ia32_cmpd512_mask: 2022 case X86::BI__builtin_ia32_cmpq512_mask: 2023 case X86::BI__builtin_ia32_ucmpb128_mask: 2024 case X86::BI__builtin_ia32_ucmpw128_mask: 2025 case X86::BI__builtin_ia32_ucmpd128_mask: 2026 case X86::BI__builtin_ia32_ucmpq128_mask: 2027 case X86::BI__builtin_ia32_ucmpb256_mask: 2028 case X86::BI__builtin_ia32_ucmpw256_mask: 2029 case X86::BI__builtin_ia32_ucmpd256_mask: 2030 case X86::BI__builtin_ia32_ucmpq256_mask: 2031 case X86::BI__builtin_ia32_ucmpb512_mask: 2032 case X86::BI__builtin_ia32_ucmpw512_mask: 2033 case X86::BI__builtin_ia32_ucmpd512_mask: 2034 case X86::BI__builtin_ia32_ucmpq512_mask: 2035 case X86::BI__builtin_ia32_vpcomub: 2036 case X86::BI__builtin_ia32_vpcomuw: 2037 case X86::BI__builtin_ia32_vpcomud: 2038 case X86::BI__builtin_ia32_vpcomuq: 2039 case X86::BI__builtin_ia32_vpcomb: 2040 case X86::BI__builtin_ia32_vpcomw: 2041 case X86::BI__builtin_ia32_vpcomd: 2042 case X86::BI__builtin_ia32_vpcomq: 2043 i = 2; l = 0; u = 7; 2044 break; 2045 case X86::BI__builtin_ia32_roundps: 2046 case X86::BI__builtin_ia32_roundpd: 2047 case X86::BI__builtin_ia32_roundps256: 2048 case X86::BI__builtin_ia32_roundpd256: 2049 i = 1; l = 0; u = 15; 2050 break; 2051 case X86::BI__builtin_ia32_roundss: 2052 case X86::BI__builtin_ia32_roundsd: 2053 case X86::BI__builtin_ia32_rangepd128_mask: 2054 case X86::BI__builtin_ia32_rangepd256_mask: 2055 case X86::BI__builtin_ia32_rangepd512_mask: 2056 case X86::BI__builtin_ia32_rangeps128_mask: 2057 case X86::BI__builtin_ia32_rangeps256_mask: 2058 case X86::BI__builtin_ia32_rangeps512_mask: 2059 case X86::BI__builtin_ia32_getmantsd_round_mask: 2060 case X86::BI__builtin_ia32_getmantss_round_mask: 2061 i = 2; l = 0; u = 15; 2062 break; 2063 case X86::BI__builtin_ia32_cmpps: 2064 case X86::BI__builtin_ia32_cmpss: 2065 case X86::BI__builtin_ia32_cmppd: 2066 case X86::BI__builtin_ia32_cmpsd: 2067 case X86::BI__builtin_ia32_cmpps256: 2068 case X86::BI__builtin_ia32_cmppd256: 2069 case X86::BI__builtin_ia32_cmpps128_mask: 2070 case X86::BI__builtin_ia32_cmppd128_mask: 2071 case X86::BI__builtin_ia32_cmpps256_mask: 2072 case X86::BI__builtin_ia32_cmppd256_mask: 2073 case X86::BI__builtin_ia32_cmpps512_mask: 2074 case X86::BI__builtin_ia32_cmppd512_mask: 2075 case X86::BI__builtin_ia32_cmpsd_mask: 2076 case X86::BI__builtin_ia32_cmpss_mask: 2077 i = 2; l = 0; u = 31; 2078 break; 2079 case X86::BI__builtin_ia32_xabort: 2080 i = 0; l = -128; u = 255; 2081 break; 2082 case X86::BI__builtin_ia32_pshufw: 2083 case X86::BI__builtin_ia32_aeskeygenassist128: 2084 i = 1; l = -128; u = 255; 2085 break; 2086 case X86::BI__builtin_ia32_vcvtps2ph: 2087 case X86::BI__builtin_ia32_vcvtps2ph256: 2088 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2089 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2090 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2091 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2092 case X86::BI__builtin_ia32_rndscaleps_mask: 2093 case X86::BI__builtin_ia32_rndscalepd_mask: 2094 case X86::BI__builtin_ia32_reducepd128_mask: 2095 case X86::BI__builtin_ia32_reducepd256_mask: 2096 case X86::BI__builtin_ia32_reducepd512_mask: 2097 case X86::BI__builtin_ia32_reduceps128_mask: 2098 case X86::BI__builtin_ia32_reduceps256_mask: 2099 case X86::BI__builtin_ia32_reduceps512_mask: 2100 case X86::BI__builtin_ia32_prold512_mask: 2101 case X86::BI__builtin_ia32_prolq512_mask: 2102 case X86::BI__builtin_ia32_prold128_mask: 2103 case X86::BI__builtin_ia32_prold256_mask: 2104 case X86::BI__builtin_ia32_prolq128_mask: 2105 case X86::BI__builtin_ia32_prolq256_mask: 2106 case X86::BI__builtin_ia32_prord128_mask: 2107 case X86::BI__builtin_ia32_prord256_mask: 2108 case X86::BI__builtin_ia32_prorq128_mask: 2109 case X86::BI__builtin_ia32_prorq256_mask: 2110 case X86::BI__builtin_ia32_psllwi512_mask: 2111 case X86::BI__builtin_ia32_psllwi128_mask: 2112 case X86::BI__builtin_ia32_psllwi256_mask: 2113 case X86::BI__builtin_ia32_psrldi128_mask: 2114 case X86::BI__builtin_ia32_psrldi256_mask: 2115 case X86::BI__builtin_ia32_psrldi512_mask: 2116 case X86::BI__builtin_ia32_psrlqi128_mask: 2117 case X86::BI__builtin_ia32_psrlqi256_mask: 2118 case X86::BI__builtin_ia32_psrlqi512_mask: 2119 case X86::BI__builtin_ia32_psrawi512_mask: 2120 case X86::BI__builtin_ia32_psrawi128_mask: 2121 case X86::BI__builtin_ia32_psrawi256_mask: 2122 case X86::BI__builtin_ia32_psrlwi512_mask: 2123 case X86::BI__builtin_ia32_psrlwi128_mask: 2124 case X86::BI__builtin_ia32_psrlwi256_mask: 2125 case X86::BI__builtin_ia32_psradi128_mask: 2126 case X86::BI__builtin_ia32_psradi256_mask: 2127 case X86::BI__builtin_ia32_psradi512_mask: 2128 case X86::BI__builtin_ia32_psraqi128_mask: 2129 case X86::BI__builtin_ia32_psraqi256_mask: 2130 case X86::BI__builtin_ia32_psraqi512_mask: 2131 case X86::BI__builtin_ia32_pslldi128_mask: 2132 case X86::BI__builtin_ia32_pslldi256_mask: 2133 case X86::BI__builtin_ia32_pslldi512_mask: 2134 case X86::BI__builtin_ia32_psllqi128_mask: 2135 case X86::BI__builtin_ia32_psllqi256_mask: 2136 case X86::BI__builtin_ia32_psllqi512_mask: 2137 case X86::BI__builtin_ia32_fpclasspd128_mask: 2138 case X86::BI__builtin_ia32_fpclasspd256_mask: 2139 case X86::BI__builtin_ia32_fpclassps128_mask: 2140 case X86::BI__builtin_ia32_fpclassps256_mask: 2141 case X86::BI__builtin_ia32_fpclassps512_mask: 2142 case X86::BI__builtin_ia32_fpclasspd512_mask: 2143 case X86::BI__builtin_ia32_fpclasssd_mask: 2144 case X86::BI__builtin_ia32_fpclassss_mask: 2145 i = 1; l = 0; u = 255; 2146 break; 2147 case X86::BI__builtin_ia32_palignr: 2148 case X86::BI__builtin_ia32_insertps128: 2149 case X86::BI__builtin_ia32_dpps: 2150 case X86::BI__builtin_ia32_dppd: 2151 case X86::BI__builtin_ia32_dpps256: 2152 case X86::BI__builtin_ia32_mpsadbw128: 2153 case X86::BI__builtin_ia32_mpsadbw256: 2154 case X86::BI__builtin_ia32_pcmpistrm128: 2155 case X86::BI__builtin_ia32_pcmpistri128: 2156 case X86::BI__builtin_ia32_pcmpistria128: 2157 case X86::BI__builtin_ia32_pcmpistric128: 2158 case X86::BI__builtin_ia32_pcmpistrio128: 2159 case X86::BI__builtin_ia32_pcmpistris128: 2160 case X86::BI__builtin_ia32_pcmpistriz128: 2161 case X86::BI__builtin_ia32_pclmulqdq128: 2162 case X86::BI__builtin_ia32_vperm2f128_pd256: 2163 case X86::BI__builtin_ia32_vperm2f128_ps256: 2164 case X86::BI__builtin_ia32_vperm2f128_si256: 2165 case X86::BI__builtin_ia32_permti256: 2166 i = 2; l = -128; u = 255; 2167 break; 2168 case X86::BI__builtin_ia32_palignr128: 2169 case X86::BI__builtin_ia32_palignr256: 2170 case X86::BI__builtin_ia32_palignr128_mask: 2171 case X86::BI__builtin_ia32_palignr256_mask: 2172 case X86::BI__builtin_ia32_palignr512_mask: 2173 case X86::BI__builtin_ia32_alignq512_mask: 2174 case X86::BI__builtin_ia32_alignd512_mask: 2175 case X86::BI__builtin_ia32_alignd128_mask: 2176 case X86::BI__builtin_ia32_alignd256_mask: 2177 case X86::BI__builtin_ia32_alignq128_mask: 2178 case X86::BI__builtin_ia32_alignq256_mask: 2179 case X86::BI__builtin_ia32_vcomisd: 2180 case X86::BI__builtin_ia32_vcomiss: 2181 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2182 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2183 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2184 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2185 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2186 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2187 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2188 i = 2; l = 0; u = 255; 2189 break; 2190 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2191 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2192 case X86::BI__builtin_ia32_fixupimmps512_mask: 2193 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2194 case X86::BI__builtin_ia32_fixupimmsd_mask: 2195 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2196 case X86::BI__builtin_ia32_fixupimmss_mask: 2197 case X86::BI__builtin_ia32_fixupimmss_maskz: 2198 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2199 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2200 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2201 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2202 case X86::BI__builtin_ia32_fixupimmps128_mask: 2203 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2204 case X86::BI__builtin_ia32_fixupimmps256_mask: 2205 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2206 case X86::BI__builtin_ia32_pternlogd512_mask: 2207 case X86::BI__builtin_ia32_pternlogd512_maskz: 2208 case X86::BI__builtin_ia32_pternlogq512_mask: 2209 case X86::BI__builtin_ia32_pternlogq512_maskz: 2210 case X86::BI__builtin_ia32_pternlogd128_mask: 2211 case X86::BI__builtin_ia32_pternlogd128_maskz: 2212 case X86::BI__builtin_ia32_pternlogd256_mask: 2213 case X86::BI__builtin_ia32_pternlogd256_maskz: 2214 case X86::BI__builtin_ia32_pternlogq128_mask: 2215 case X86::BI__builtin_ia32_pternlogq128_maskz: 2216 case X86::BI__builtin_ia32_pternlogq256_mask: 2217 case X86::BI__builtin_ia32_pternlogq256_maskz: 2218 i = 3; l = 0; u = 255; 2219 break; 2220 case X86::BI__builtin_ia32_pcmpestrm128: 2221 case X86::BI__builtin_ia32_pcmpestri128: 2222 case X86::BI__builtin_ia32_pcmpestria128: 2223 case X86::BI__builtin_ia32_pcmpestric128: 2224 case X86::BI__builtin_ia32_pcmpestrio128: 2225 case X86::BI__builtin_ia32_pcmpestris128: 2226 case X86::BI__builtin_ia32_pcmpestriz128: 2227 i = 4; l = -128; u = 255; 2228 break; 2229 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2230 case X86::BI__builtin_ia32_rndscaless_round_mask: 2231 i = 4; l = 0; u = 255; 2232 break; 2233 } 2234 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2235 } 2236 2237 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2238 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2239 /// Returns true when the format fits the function and the FormatStringInfo has 2240 /// been populated. 2241 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2242 FormatStringInfo *FSI) { 2243 FSI->HasVAListArg = Format->getFirstArg() == 0; 2244 FSI->FormatIdx = Format->getFormatIdx() - 1; 2245 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2246 2247 // The way the format attribute works in GCC, the implicit this argument 2248 // of member functions is counted. However, it doesn't appear in our own 2249 // lists, so decrement format_idx in that case. 2250 if (IsCXXMember) { 2251 if(FSI->FormatIdx == 0) 2252 return false; 2253 --FSI->FormatIdx; 2254 if (FSI->FirstDataArg != 0) 2255 --FSI->FirstDataArg; 2256 } 2257 return true; 2258 } 2259 2260 /// Checks if a the given expression evaluates to null. 2261 /// 2262 /// \brief Returns true if the value evaluates to null. 2263 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2264 // If the expression has non-null type, it doesn't evaluate to null. 2265 if (auto nullability 2266 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2267 if (*nullability == NullabilityKind::NonNull) 2268 return false; 2269 } 2270 2271 // As a special case, transparent unions initialized with zero are 2272 // considered null for the purposes of the nonnull attribute. 2273 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2274 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2275 if (const CompoundLiteralExpr *CLE = 2276 dyn_cast<CompoundLiteralExpr>(Expr)) 2277 if (const InitListExpr *ILE = 2278 dyn_cast<InitListExpr>(CLE->getInitializer())) 2279 Expr = ILE->getInit(0); 2280 } 2281 2282 bool Result; 2283 return (!Expr->isValueDependent() && 2284 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2285 !Result); 2286 } 2287 2288 static void CheckNonNullArgument(Sema &S, 2289 const Expr *ArgExpr, 2290 SourceLocation CallSiteLoc) { 2291 if (CheckNonNullExpr(S, ArgExpr)) 2292 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2293 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2294 } 2295 2296 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2297 FormatStringInfo FSI; 2298 if ((GetFormatStringType(Format) == FST_NSString) && 2299 getFormatStringInfo(Format, false, &FSI)) { 2300 Idx = FSI.FormatIdx; 2301 return true; 2302 } 2303 return false; 2304 } 2305 /// \brief Diagnose use of %s directive in an NSString which is being passed 2306 /// as formatting string to formatting method. 2307 static void 2308 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2309 const NamedDecl *FDecl, 2310 Expr **Args, 2311 unsigned NumArgs) { 2312 unsigned Idx = 0; 2313 bool Format = false; 2314 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2315 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2316 Idx = 2; 2317 Format = true; 2318 } 2319 else 2320 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2321 if (S.GetFormatNSStringIdx(I, Idx)) { 2322 Format = true; 2323 break; 2324 } 2325 } 2326 if (!Format || NumArgs <= Idx) 2327 return; 2328 const Expr *FormatExpr = Args[Idx]; 2329 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2330 FormatExpr = CSCE->getSubExpr(); 2331 const StringLiteral *FormatString; 2332 if (const ObjCStringLiteral *OSL = 2333 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2334 FormatString = OSL->getString(); 2335 else 2336 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2337 if (!FormatString) 2338 return; 2339 if (S.FormatStringHasSArg(FormatString)) { 2340 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2341 << "%s" << 1 << 1; 2342 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2343 << FDecl->getDeclName(); 2344 } 2345 } 2346 2347 /// Determine whether the given type has a non-null nullability annotation. 2348 static bool isNonNullType(ASTContext &ctx, QualType type) { 2349 if (auto nullability = type->getNullability(ctx)) 2350 return *nullability == NullabilityKind::NonNull; 2351 2352 return false; 2353 } 2354 2355 static void CheckNonNullArguments(Sema &S, 2356 const NamedDecl *FDecl, 2357 const FunctionProtoType *Proto, 2358 ArrayRef<const Expr *> Args, 2359 SourceLocation CallSiteLoc) { 2360 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2361 2362 // Check the attributes attached to the method/function itself. 2363 llvm::SmallBitVector NonNullArgs; 2364 if (FDecl) { 2365 // Handle the nonnull attribute on the function/method declaration itself. 2366 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2367 if (!NonNull->args_size()) { 2368 // Easy case: all pointer arguments are nonnull. 2369 for (const auto *Arg : Args) 2370 if (S.isValidPointerAttrType(Arg->getType())) 2371 CheckNonNullArgument(S, Arg, CallSiteLoc); 2372 return; 2373 } 2374 2375 for (unsigned Val : NonNull->args()) { 2376 if (Val >= Args.size()) 2377 continue; 2378 if (NonNullArgs.empty()) 2379 NonNullArgs.resize(Args.size()); 2380 NonNullArgs.set(Val); 2381 } 2382 } 2383 } 2384 2385 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2386 // Handle the nonnull attribute on the parameters of the 2387 // function/method. 2388 ArrayRef<ParmVarDecl*> parms; 2389 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2390 parms = FD->parameters(); 2391 else 2392 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2393 2394 unsigned ParamIndex = 0; 2395 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2396 I != E; ++I, ++ParamIndex) { 2397 const ParmVarDecl *PVD = *I; 2398 if (PVD->hasAttr<NonNullAttr>() || 2399 isNonNullType(S.Context, PVD->getType())) { 2400 if (NonNullArgs.empty()) 2401 NonNullArgs.resize(Args.size()); 2402 2403 NonNullArgs.set(ParamIndex); 2404 } 2405 } 2406 } else { 2407 // If we have a non-function, non-method declaration but no 2408 // function prototype, try to dig out the function prototype. 2409 if (!Proto) { 2410 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2411 QualType type = VD->getType().getNonReferenceType(); 2412 if (auto pointerType = type->getAs<PointerType>()) 2413 type = pointerType->getPointeeType(); 2414 else if (auto blockType = type->getAs<BlockPointerType>()) 2415 type = blockType->getPointeeType(); 2416 // FIXME: data member pointers? 2417 2418 // Dig out the function prototype, if there is one. 2419 Proto = type->getAs<FunctionProtoType>(); 2420 } 2421 } 2422 2423 // Fill in non-null argument information from the nullability 2424 // information on the parameter types (if we have them). 2425 if (Proto) { 2426 unsigned Index = 0; 2427 for (auto paramType : Proto->getParamTypes()) { 2428 if (isNonNullType(S.Context, paramType)) { 2429 if (NonNullArgs.empty()) 2430 NonNullArgs.resize(Args.size()); 2431 2432 NonNullArgs.set(Index); 2433 } 2434 2435 ++Index; 2436 } 2437 } 2438 } 2439 2440 // Check for non-null arguments. 2441 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2442 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2443 if (NonNullArgs[ArgIndex]) 2444 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2445 } 2446 } 2447 2448 /// Handles the checks for format strings, non-POD arguments to vararg 2449 /// functions, and NULL arguments passed to non-NULL parameters. 2450 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2451 ArrayRef<const Expr *> Args, bool IsMemberFunction, 2452 SourceLocation Loc, SourceRange Range, 2453 VariadicCallType CallType) { 2454 // FIXME: We should check as much as we can in the template definition. 2455 if (CurContext->isDependentContext()) 2456 return; 2457 2458 // Printf and scanf checking. 2459 llvm::SmallBitVector CheckedVarArgs; 2460 if (FDecl) { 2461 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2462 // Only create vector if there are format attributes. 2463 CheckedVarArgs.resize(Args.size()); 2464 2465 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2466 CheckedVarArgs); 2467 } 2468 } 2469 2470 // Refuse POD arguments that weren't caught by the format string 2471 // checks above. 2472 if (CallType != VariadicDoesNotApply) { 2473 unsigned NumParams = Proto ? Proto->getNumParams() 2474 : FDecl && isa<FunctionDecl>(FDecl) 2475 ? cast<FunctionDecl>(FDecl)->getNumParams() 2476 : FDecl && isa<ObjCMethodDecl>(FDecl) 2477 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2478 : 0; 2479 2480 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2481 // Args[ArgIdx] can be null in malformed code. 2482 if (const Expr *Arg = Args[ArgIdx]) { 2483 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2484 checkVariadicArgument(Arg, CallType); 2485 } 2486 } 2487 } 2488 2489 if (FDecl || Proto) { 2490 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2491 2492 // Type safety checking. 2493 if (FDecl) { 2494 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2495 CheckArgumentWithTypeTag(I, Args.data()); 2496 } 2497 } 2498 } 2499 2500 /// CheckConstructorCall - Check a constructor call for correctness and safety 2501 /// properties not enforced by the C type system. 2502 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2503 ArrayRef<const Expr *> Args, 2504 const FunctionProtoType *Proto, 2505 SourceLocation Loc) { 2506 VariadicCallType CallType = 2507 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2508 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(), 2509 CallType); 2510 } 2511 2512 /// CheckFunctionCall - Check a direct function call for various correctness 2513 /// and safety properties not strictly enforced by the C type system. 2514 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2515 const FunctionProtoType *Proto) { 2516 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2517 isa<CXXMethodDecl>(FDecl); 2518 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2519 IsMemberOperatorCall; 2520 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2521 TheCall->getCallee()); 2522 Expr** Args = TheCall->getArgs(); 2523 unsigned NumArgs = TheCall->getNumArgs(); 2524 if (IsMemberOperatorCall) { 2525 // If this is a call to a member operator, hide the first argument 2526 // from checkCall. 2527 // FIXME: Our choice of AST representation here is less than ideal. 2528 ++Args; 2529 --NumArgs; 2530 } 2531 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs), 2532 IsMemberFunction, TheCall->getRParenLoc(), 2533 TheCall->getCallee()->getSourceRange(), CallType); 2534 2535 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2536 // None of the checks below are needed for functions that don't have 2537 // simple names (e.g., C++ conversion functions). 2538 if (!FnInfo) 2539 return false; 2540 2541 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo); 2542 if (getLangOpts().ObjC1) 2543 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2544 2545 unsigned CMId = FDecl->getMemoryFunctionKind(); 2546 if (CMId == 0) 2547 return false; 2548 2549 // Handle memory setting and copying functions. 2550 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2551 CheckStrlcpycatArguments(TheCall, FnInfo); 2552 else if (CMId == Builtin::BIstrncat) 2553 CheckStrncatArguments(TheCall, FnInfo); 2554 else 2555 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2556 2557 return false; 2558 } 2559 2560 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2561 ArrayRef<const Expr *> Args) { 2562 VariadicCallType CallType = 2563 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2564 2565 checkCall(Method, nullptr, Args, 2566 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2567 CallType); 2568 2569 return false; 2570 } 2571 2572 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2573 const FunctionProtoType *Proto) { 2574 QualType Ty; 2575 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2576 Ty = V->getType().getNonReferenceType(); 2577 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2578 Ty = F->getType().getNonReferenceType(); 2579 else 2580 return false; 2581 2582 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2583 !Ty->isFunctionProtoType()) 2584 return false; 2585 2586 VariadicCallType CallType; 2587 if (!Proto || !Proto->isVariadic()) { 2588 CallType = VariadicDoesNotApply; 2589 } else if (Ty->isBlockPointerType()) { 2590 CallType = VariadicBlock; 2591 } else { // Ty->isFunctionPointerType() 2592 CallType = VariadicFunction; 2593 } 2594 2595 checkCall(NDecl, Proto, 2596 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2597 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2598 TheCall->getCallee()->getSourceRange(), CallType); 2599 2600 return false; 2601 } 2602 2603 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2604 /// such as function pointers returned from functions. 2605 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2606 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2607 TheCall->getCallee()); 2608 checkCall(/*FDecl=*/nullptr, Proto, 2609 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2610 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2611 TheCall->getCallee()->getSourceRange(), CallType); 2612 2613 return false; 2614 } 2615 2616 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2617 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2618 return false; 2619 2620 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2621 switch (Op) { 2622 case AtomicExpr::AO__c11_atomic_init: 2623 llvm_unreachable("There is no ordering argument for an init"); 2624 2625 case AtomicExpr::AO__c11_atomic_load: 2626 case AtomicExpr::AO__atomic_load_n: 2627 case AtomicExpr::AO__atomic_load: 2628 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2629 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2630 2631 case AtomicExpr::AO__c11_atomic_store: 2632 case AtomicExpr::AO__atomic_store: 2633 case AtomicExpr::AO__atomic_store_n: 2634 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2635 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2636 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2637 2638 default: 2639 return true; 2640 } 2641 } 2642 2643 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2644 AtomicExpr::AtomicOp Op) { 2645 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2646 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2647 2648 // All these operations take one of the following forms: 2649 enum { 2650 // C __c11_atomic_init(A *, C) 2651 Init, 2652 // C __c11_atomic_load(A *, int) 2653 Load, 2654 // void __atomic_load(A *, CP, int) 2655 LoadCopy, 2656 // void __atomic_store(A *, CP, int) 2657 Copy, 2658 // C __c11_atomic_add(A *, M, int) 2659 Arithmetic, 2660 // C __atomic_exchange_n(A *, CP, int) 2661 Xchg, 2662 // void __atomic_exchange(A *, C *, CP, int) 2663 GNUXchg, 2664 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2665 C11CmpXchg, 2666 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2667 GNUCmpXchg 2668 } Form = Init; 2669 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2670 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2671 // where: 2672 // C is an appropriate type, 2673 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2674 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2675 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2676 // the int parameters are for orderings. 2677 2678 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2679 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2680 AtomicExpr::AO__atomic_load, 2681 "need to update code for modified C11 atomics"); 2682 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 2683 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 2684 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2685 Op == AtomicExpr::AO__atomic_store_n || 2686 Op == AtomicExpr::AO__atomic_exchange_n || 2687 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2688 bool IsAddSub = false; 2689 2690 switch (Op) { 2691 case AtomicExpr::AO__c11_atomic_init: 2692 Form = Init; 2693 break; 2694 2695 case AtomicExpr::AO__c11_atomic_load: 2696 case AtomicExpr::AO__atomic_load_n: 2697 Form = Load; 2698 break; 2699 2700 case AtomicExpr::AO__atomic_load: 2701 Form = LoadCopy; 2702 break; 2703 2704 case AtomicExpr::AO__c11_atomic_store: 2705 case AtomicExpr::AO__atomic_store: 2706 case AtomicExpr::AO__atomic_store_n: 2707 Form = Copy; 2708 break; 2709 2710 case AtomicExpr::AO__c11_atomic_fetch_add: 2711 case AtomicExpr::AO__c11_atomic_fetch_sub: 2712 case AtomicExpr::AO__atomic_fetch_add: 2713 case AtomicExpr::AO__atomic_fetch_sub: 2714 case AtomicExpr::AO__atomic_add_fetch: 2715 case AtomicExpr::AO__atomic_sub_fetch: 2716 IsAddSub = true; 2717 // Fall through. 2718 case AtomicExpr::AO__c11_atomic_fetch_and: 2719 case AtomicExpr::AO__c11_atomic_fetch_or: 2720 case AtomicExpr::AO__c11_atomic_fetch_xor: 2721 case AtomicExpr::AO__atomic_fetch_and: 2722 case AtomicExpr::AO__atomic_fetch_or: 2723 case AtomicExpr::AO__atomic_fetch_xor: 2724 case AtomicExpr::AO__atomic_fetch_nand: 2725 case AtomicExpr::AO__atomic_and_fetch: 2726 case AtomicExpr::AO__atomic_or_fetch: 2727 case AtomicExpr::AO__atomic_xor_fetch: 2728 case AtomicExpr::AO__atomic_nand_fetch: 2729 Form = Arithmetic; 2730 break; 2731 2732 case AtomicExpr::AO__c11_atomic_exchange: 2733 case AtomicExpr::AO__atomic_exchange_n: 2734 Form = Xchg; 2735 break; 2736 2737 case AtomicExpr::AO__atomic_exchange: 2738 Form = GNUXchg; 2739 break; 2740 2741 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2742 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2743 Form = C11CmpXchg; 2744 break; 2745 2746 case AtomicExpr::AO__atomic_compare_exchange: 2747 case AtomicExpr::AO__atomic_compare_exchange_n: 2748 Form = GNUCmpXchg; 2749 break; 2750 } 2751 2752 // Check we have the right number of arguments. 2753 if (TheCall->getNumArgs() < NumArgs[Form]) { 2754 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2755 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2756 << TheCall->getCallee()->getSourceRange(); 2757 return ExprError(); 2758 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 2759 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 2760 diag::err_typecheck_call_too_many_args) 2761 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2762 << TheCall->getCallee()->getSourceRange(); 2763 return ExprError(); 2764 } 2765 2766 // Inspect the first argument of the atomic operation. 2767 Expr *Ptr = TheCall->getArg(0); 2768 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2769 if (ConvertedPtr.isInvalid()) 2770 return ExprError(); 2771 2772 Ptr = ConvertedPtr.get(); 2773 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2774 if (!pointerType) { 2775 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2776 << Ptr->getType() << Ptr->getSourceRange(); 2777 return ExprError(); 2778 } 2779 2780 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2781 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2782 QualType ValType = AtomTy; // 'C' 2783 if (IsC11) { 2784 if (!AtomTy->isAtomicType()) { 2785 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 2786 << Ptr->getType() << Ptr->getSourceRange(); 2787 return ExprError(); 2788 } 2789 if (AtomTy.isConstQualified()) { 2790 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 2791 << Ptr->getType() << Ptr->getSourceRange(); 2792 return ExprError(); 2793 } 2794 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 2795 } else if (Form != Load && Form != LoadCopy) { 2796 if (ValType.isConstQualified()) { 2797 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 2798 << Ptr->getType() << Ptr->getSourceRange(); 2799 return ExprError(); 2800 } 2801 } 2802 2803 // For an arithmetic operation, the implied arithmetic must be well-formed. 2804 if (Form == Arithmetic) { 2805 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 2806 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 2807 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2808 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2809 return ExprError(); 2810 } 2811 if (!IsAddSub && !ValType->isIntegerType()) { 2812 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 2813 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2814 return ExprError(); 2815 } 2816 if (IsC11 && ValType->isPointerType() && 2817 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 2818 diag::err_incomplete_type)) { 2819 return ExprError(); 2820 } 2821 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 2822 // For __atomic_*_n operations, the value type must be a scalar integral or 2823 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 2824 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2825 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2826 return ExprError(); 2827 } 2828 2829 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 2830 !AtomTy->isScalarType()) { 2831 // For GNU atomics, require a trivially-copyable type. This is not part of 2832 // the GNU atomics specification, but we enforce it for sanity. 2833 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 2834 << Ptr->getType() << Ptr->getSourceRange(); 2835 return ExprError(); 2836 } 2837 2838 switch (ValType.getObjCLifetime()) { 2839 case Qualifiers::OCL_None: 2840 case Qualifiers::OCL_ExplicitNone: 2841 // okay 2842 break; 2843 2844 case Qualifiers::OCL_Weak: 2845 case Qualifiers::OCL_Strong: 2846 case Qualifiers::OCL_Autoreleasing: 2847 // FIXME: Can this happen? By this point, ValType should be known 2848 // to be trivially copyable. 2849 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 2850 << ValType << Ptr->getSourceRange(); 2851 return ExprError(); 2852 } 2853 2854 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 2855 // volatile-ness of the pointee-type inject itself into the result or the 2856 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 2857 ValType.removeLocalVolatile(); 2858 ValType.removeLocalConst(); 2859 QualType ResultType = ValType; 2860 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init) 2861 ResultType = Context.VoidTy; 2862 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 2863 ResultType = Context.BoolTy; 2864 2865 // The type of a parameter passed 'by value'. In the GNU atomics, such 2866 // arguments are actually passed as pointers. 2867 QualType ByValType = ValType; // 'CP' 2868 if (!IsC11 && !IsN) 2869 ByValType = Ptr->getType(); 2870 2871 // The first argument --- the pointer --- has a fixed type; we 2872 // deduce the types of the rest of the arguments accordingly. Walk 2873 // the remaining arguments, converting them to the deduced value type. 2874 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 2875 QualType Ty; 2876 if (i < NumVals[Form] + 1) { 2877 switch (i) { 2878 case 1: 2879 // The second argument is the non-atomic operand. For arithmetic, this 2880 // is always passed by value, and for a compare_exchange it is always 2881 // passed by address. For the rest, GNU uses by-address and C11 uses 2882 // by-value. 2883 assert(Form != Load); 2884 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 2885 Ty = ValType; 2886 else if (Form == Copy || Form == Xchg) 2887 Ty = ByValType; 2888 else if (Form == Arithmetic) 2889 Ty = Context.getPointerDiffType(); 2890 else { 2891 Expr *ValArg = TheCall->getArg(i); 2892 unsigned AS = 0; 2893 // Keep address space of non-atomic pointer type. 2894 if (const PointerType *PtrTy = 2895 ValArg->getType()->getAs<PointerType>()) { 2896 AS = PtrTy->getPointeeType().getAddressSpace(); 2897 } 2898 Ty = Context.getPointerType( 2899 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 2900 } 2901 break; 2902 case 2: 2903 // The third argument to compare_exchange / GNU exchange is a 2904 // (pointer to a) desired value. 2905 Ty = ByValType; 2906 break; 2907 case 3: 2908 // The fourth argument to GNU compare_exchange is a 'weak' flag. 2909 Ty = Context.BoolTy; 2910 break; 2911 } 2912 } else { 2913 // The order(s) are always converted to int. 2914 Ty = Context.IntTy; 2915 } 2916 2917 InitializedEntity Entity = 2918 InitializedEntity::InitializeParameter(Context, Ty, false); 2919 ExprResult Arg = TheCall->getArg(i); 2920 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 2921 if (Arg.isInvalid()) 2922 return true; 2923 TheCall->setArg(i, Arg.get()); 2924 } 2925 2926 // Permute the arguments into a 'consistent' order. 2927 SmallVector<Expr*, 5> SubExprs; 2928 SubExprs.push_back(Ptr); 2929 switch (Form) { 2930 case Init: 2931 // Note, AtomicExpr::getVal1() has a special case for this atomic. 2932 SubExprs.push_back(TheCall->getArg(1)); // Val1 2933 break; 2934 case Load: 2935 SubExprs.push_back(TheCall->getArg(1)); // Order 2936 break; 2937 case LoadCopy: 2938 case Copy: 2939 case Arithmetic: 2940 case Xchg: 2941 SubExprs.push_back(TheCall->getArg(2)); // Order 2942 SubExprs.push_back(TheCall->getArg(1)); // Val1 2943 break; 2944 case GNUXchg: 2945 // Note, AtomicExpr::getVal2() has a special case for this atomic. 2946 SubExprs.push_back(TheCall->getArg(3)); // Order 2947 SubExprs.push_back(TheCall->getArg(1)); // Val1 2948 SubExprs.push_back(TheCall->getArg(2)); // Val2 2949 break; 2950 case C11CmpXchg: 2951 SubExprs.push_back(TheCall->getArg(3)); // Order 2952 SubExprs.push_back(TheCall->getArg(1)); // Val1 2953 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 2954 SubExprs.push_back(TheCall->getArg(2)); // Val2 2955 break; 2956 case GNUCmpXchg: 2957 SubExprs.push_back(TheCall->getArg(4)); // Order 2958 SubExprs.push_back(TheCall->getArg(1)); // Val1 2959 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 2960 SubExprs.push_back(TheCall->getArg(2)); // Val2 2961 SubExprs.push_back(TheCall->getArg(3)); // Weak 2962 break; 2963 } 2964 2965 if (SubExprs.size() >= 2 && Form != Init) { 2966 llvm::APSInt Result(32); 2967 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 2968 !isValidOrderingForOp(Result.getSExtValue(), Op)) 2969 Diag(SubExprs[1]->getLocStart(), 2970 diag::warn_atomic_op_has_invalid_memory_order) 2971 << SubExprs[1]->getSourceRange(); 2972 } 2973 2974 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 2975 SubExprs, ResultType, Op, 2976 TheCall->getRParenLoc()); 2977 2978 if ((Op == AtomicExpr::AO__c11_atomic_load || 2979 (Op == AtomicExpr::AO__c11_atomic_store)) && 2980 Context.AtomicUsesUnsupportedLibcall(AE)) 2981 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 2982 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 2983 2984 return AE; 2985 } 2986 2987 /// checkBuiltinArgument - Given a call to a builtin function, perform 2988 /// normal type-checking on the given argument, updating the call in 2989 /// place. This is useful when a builtin function requires custom 2990 /// type-checking for some of its arguments but not necessarily all of 2991 /// them. 2992 /// 2993 /// Returns true on error. 2994 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 2995 FunctionDecl *Fn = E->getDirectCallee(); 2996 assert(Fn && "builtin call without direct callee!"); 2997 2998 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 2999 InitializedEntity Entity = 3000 InitializedEntity::InitializeParameter(S.Context, Param); 3001 3002 ExprResult Arg = E->getArg(0); 3003 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3004 if (Arg.isInvalid()) 3005 return true; 3006 3007 E->setArg(ArgIndex, Arg.get()); 3008 return false; 3009 } 3010 3011 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3012 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3013 /// type of its first argument. The main ActOnCallExpr routines have already 3014 /// promoted the types of arguments because all of these calls are prototyped as 3015 /// void(...). 3016 /// 3017 /// This function goes through and does final semantic checking for these 3018 /// builtins, 3019 ExprResult 3020 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3021 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3022 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3023 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3024 3025 // Ensure that we have at least one argument to do type inference from. 3026 if (TheCall->getNumArgs() < 1) { 3027 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3028 << 0 << 1 << TheCall->getNumArgs() 3029 << TheCall->getCallee()->getSourceRange(); 3030 return ExprError(); 3031 } 3032 3033 // Inspect the first argument of the atomic builtin. This should always be 3034 // a pointer type, whose element is an integral scalar or pointer type. 3035 // Because it is a pointer type, we don't have to worry about any implicit 3036 // casts here. 3037 // FIXME: We don't allow floating point scalars as input. 3038 Expr *FirstArg = TheCall->getArg(0); 3039 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3040 if (FirstArgResult.isInvalid()) 3041 return ExprError(); 3042 FirstArg = FirstArgResult.get(); 3043 TheCall->setArg(0, FirstArg); 3044 3045 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3046 if (!pointerType) { 3047 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3048 << FirstArg->getType() << FirstArg->getSourceRange(); 3049 return ExprError(); 3050 } 3051 3052 QualType ValType = pointerType->getPointeeType(); 3053 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3054 !ValType->isBlockPointerType()) { 3055 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3056 << FirstArg->getType() << FirstArg->getSourceRange(); 3057 return ExprError(); 3058 } 3059 3060 switch (ValType.getObjCLifetime()) { 3061 case Qualifiers::OCL_None: 3062 case Qualifiers::OCL_ExplicitNone: 3063 // okay 3064 break; 3065 3066 case Qualifiers::OCL_Weak: 3067 case Qualifiers::OCL_Strong: 3068 case Qualifiers::OCL_Autoreleasing: 3069 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3070 << ValType << FirstArg->getSourceRange(); 3071 return ExprError(); 3072 } 3073 3074 // Strip any qualifiers off ValType. 3075 ValType = ValType.getUnqualifiedType(); 3076 3077 // The majority of builtins return a value, but a few have special return 3078 // types, so allow them to override appropriately below. 3079 QualType ResultType = ValType; 3080 3081 // We need to figure out which concrete builtin this maps onto. For example, 3082 // __sync_fetch_and_add with a 2 byte object turns into 3083 // __sync_fetch_and_add_2. 3084 #define BUILTIN_ROW(x) \ 3085 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3086 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3087 3088 static const unsigned BuiltinIndices[][5] = { 3089 BUILTIN_ROW(__sync_fetch_and_add), 3090 BUILTIN_ROW(__sync_fetch_and_sub), 3091 BUILTIN_ROW(__sync_fetch_and_or), 3092 BUILTIN_ROW(__sync_fetch_and_and), 3093 BUILTIN_ROW(__sync_fetch_and_xor), 3094 BUILTIN_ROW(__sync_fetch_and_nand), 3095 3096 BUILTIN_ROW(__sync_add_and_fetch), 3097 BUILTIN_ROW(__sync_sub_and_fetch), 3098 BUILTIN_ROW(__sync_and_and_fetch), 3099 BUILTIN_ROW(__sync_or_and_fetch), 3100 BUILTIN_ROW(__sync_xor_and_fetch), 3101 BUILTIN_ROW(__sync_nand_and_fetch), 3102 3103 BUILTIN_ROW(__sync_val_compare_and_swap), 3104 BUILTIN_ROW(__sync_bool_compare_and_swap), 3105 BUILTIN_ROW(__sync_lock_test_and_set), 3106 BUILTIN_ROW(__sync_lock_release), 3107 BUILTIN_ROW(__sync_swap) 3108 }; 3109 #undef BUILTIN_ROW 3110 3111 // Determine the index of the size. 3112 unsigned SizeIndex; 3113 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3114 case 1: SizeIndex = 0; break; 3115 case 2: SizeIndex = 1; break; 3116 case 4: SizeIndex = 2; break; 3117 case 8: SizeIndex = 3; break; 3118 case 16: SizeIndex = 4; break; 3119 default: 3120 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3121 << FirstArg->getType() << FirstArg->getSourceRange(); 3122 return ExprError(); 3123 } 3124 3125 // Each of these builtins has one pointer argument, followed by some number of 3126 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3127 // that we ignore. Find out which row of BuiltinIndices to read from as well 3128 // as the number of fixed args. 3129 unsigned BuiltinID = FDecl->getBuiltinID(); 3130 unsigned BuiltinIndex, NumFixed = 1; 3131 bool WarnAboutSemanticsChange = false; 3132 switch (BuiltinID) { 3133 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3134 case Builtin::BI__sync_fetch_and_add: 3135 case Builtin::BI__sync_fetch_and_add_1: 3136 case Builtin::BI__sync_fetch_and_add_2: 3137 case Builtin::BI__sync_fetch_and_add_4: 3138 case Builtin::BI__sync_fetch_and_add_8: 3139 case Builtin::BI__sync_fetch_and_add_16: 3140 BuiltinIndex = 0; 3141 break; 3142 3143 case Builtin::BI__sync_fetch_and_sub: 3144 case Builtin::BI__sync_fetch_and_sub_1: 3145 case Builtin::BI__sync_fetch_and_sub_2: 3146 case Builtin::BI__sync_fetch_and_sub_4: 3147 case Builtin::BI__sync_fetch_and_sub_8: 3148 case Builtin::BI__sync_fetch_and_sub_16: 3149 BuiltinIndex = 1; 3150 break; 3151 3152 case Builtin::BI__sync_fetch_and_or: 3153 case Builtin::BI__sync_fetch_and_or_1: 3154 case Builtin::BI__sync_fetch_and_or_2: 3155 case Builtin::BI__sync_fetch_and_or_4: 3156 case Builtin::BI__sync_fetch_and_or_8: 3157 case Builtin::BI__sync_fetch_and_or_16: 3158 BuiltinIndex = 2; 3159 break; 3160 3161 case Builtin::BI__sync_fetch_and_and: 3162 case Builtin::BI__sync_fetch_and_and_1: 3163 case Builtin::BI__sync_fetch_and_and_2: 3164 case Builtin::BI__sync_fetch_and_and_4: 3165 case Builtin::BI__sync_fetch_and_and_8: 3166 case Builtin::BI__sync_fetch_and_and_16: 3167 BuiltinIndex = 3; 3168 break; 3169 3170 case Builtin::BI__sync_fetch_and_xor: 3171 case Builtin::BI__sync_fetch_and_xor_1: 3172 case Builtin::BI__sync_fetch_and_xor_2: 3173 case Builtin::BI__sync_fetch_and_xor_4: 3174 case Builtin::BI__sync_fetch_and_xor_8: 3175 case Builtin::BI__sync_fetch_and_xor_16: 3176 BuiltinIndex = 4; 3177 break; 3178 3179 case Builtin::BI__sync_fetch_and_nand: 3180 case Builtin::BI__sync_fetch_and_nand_1: 3181 case Builtin::BI__sync_fetch_and_nand_2: 3182 case Builtin::BI__sync_fetch_and_nand_4: 3183 case Builtin::BI__sync_fetch_and_nand_8: 3184 case Builtin::BI__sync_fetch_and_nand_16: 3185 BuiltinIndex = 5; 3186 WarnAboutSemanticsChange = true; 3187 break; 3188 3189 case Builtin::BI__sync_add_and_fetch: 3190 case Builtin::BI__sync_add_and_fetch_1: 3191 case Builtin::BI__sync_add_and_fetch_2: 3192 case Builtin::BI__sync_add_and_fetch_4: 3193 case Builtin::BI__sync_add_and_fetch_8: 3194 case Builtin::BI__sync_add_and_fetch_16: 3195 BuiltinIndex = 6; 3196 break; 3197 3198 case Builtin::BI__sync_sub_and_fetch: 3199 case Builtin::BI__sync_sub_and_fetch_1: 3200 case Builtin::BI__sync_sub_and_fetch_2: 3201 case Builtin::BI__sync_sub_and_fetch_4: 3202 case Builtin::BI__sync_sub_and_fetch_8: 3203 case Builtin::BI__sync_sub_and_fetch_16: 3204 BuiltinIndex = 7; 3205 break; 3206 3207 case Builtin::BI__sync_and_and_fetch: 3208 case Builtin::BI__sync_and_and_fetch_1: 3209 case Builtin::BI__sync_and_and_fetch_2: 3210 case Builtin::BI__sync_and_and_fetch_4: 3211 case Builtin::BI__sync_and_and_fetch_8: 3212 case Builtin::BI__sync_and_and_fetch_16: 3213 BuiltinIndex = 8; 3214 break; 3215 3216 case Builtin::BI__sync_or_and_fetch: 3217 case Builtin::BI__sync_or_and_fetch_1: 3218 case Builtin::BI__sync_or_and_fetch_2: 3219 case Builtin::BI__sync_or_and_fetch_4: 3220 case Builtin::BI__sync_or_and_fetch_8: 3221 case Builtin::BI__sync_or_and_fetch_16: 3222 BuiltinIndex = 9; 3223 break; 3224 3225 case Builtin::BI__sync_xor_and_fetch: 3226 case Builtin::BI__sync_xor_and_fetch_1: 3227 case Builtin::BI__sync_xor_and_fetch_2: 3228 case Builtin::BI__sync_xor_and_fetch_4: 3229 case Builtin::BI__sync_xor_and_fetch_8: 3230 case Builtin::BI__sync_xor_and_fetch_16: 3231 BuiltinIndex = 10; 3232 break; 3233 3234 case Builtin::BI__sync_nand_and_fetch: 3235 case Builtin::BI__sync_nand_and_fetch_1: 3236 case Builtin::BI__sync_nand_and_fetch_2: 3237 case Builtin::BI__sync_nand_and_fetch_4: 3238 case Builtin::BI__sync_nand_and_fetch_8: 3239 case Builtin::BI__sync_nand_and_fetch_16: 3240 BuiltinIndex = 11; 3241 WarnAboutSemanticsChange = true; 3242 break; 3243 3244 case Builtin::BI__sync_val_compare_and_swap: 3245 case Builtin::BI__sync_val_compare_and_swap_1: 3246 case Builtin::BI__sync_val_compare_and_swap_2: 3247 case Builtin::BI__sync_val_compare_and_swap_4: 3248 case Builtin::BI__sync_val_compare_and_swap_8: 3249 case Builtin::BI__sync_val_compare_and_swap_16: 3250 BuiltinIndex = 12; 3251 NumFixed = 2; 3252 break; 3253 3254 case Builtin::BI__sync_bool_compare_and_swap: 3255 case Builtin::BI__sync_bool_compare_and_swap_1: 3256 case Builtin::BI__sync_bool_compare_and_swap_2: 3257 case Builtin::BI__sync_bool_compare_and_swap_4: 3258 case Builtin::BI__sync_bool_compare_and_swap_8: 3259 case Builtin::BI__sync_bool_compare_and_swap_16: 3260 BuiltinIndex = 13; 3261 NumFixed = 2; 3262 ResultType = Context.BoolTy; 3263 break; 3264 3265 case Builtin::BI__sync_lock_test_and_set: 3266 case Builtin::BI__sync_lock_test_and_set_1: 3267 case Builtin::BI__sync_lock_test_and_set_2: 3268 case Builtin::BI__sync_lock_test_and_set_4: 3269 case Builtin::BI__sync_lock_test_and_set_8: 3270 case Builtin::BI__sync_lock_test_and_set_16: 3271 BuiltinIndex = 14; 3272 break; 3273 3274 case Builtin::BI__sync_lock_release: 3275 case Builtin::BI__sync_lock_release_1: 3276 case Builtin::BI__sync_lock_release_2: 3277 case Builtin::BI__sync_lock_release_4: 3278 case Builtin::BI__sync_lock_release_8: 3279 case Builtin::BI__sync_lock_release_16: 3280 BuiltinIndex = 15; 3281 NumFixed = 0; 3282 ResultType = Context.VoidTy; 3283 break; 3284 3285 case Builtin::BI__sync_swap: 3286 case Builtin::BI__sync_swap_1: 3287 case Builtin::BI__sync_swap_2: 3288 case Builtin::BI__sync_swap_4: 3289 case Builtin::BI__sync_swap_8: 3290 case Builtin::BI__sync_swap_16: 3291 BuiltinIndex = 16; 3292 break; 3293 } 3294 3295 // Now that we know how many fixed arguments we expect, first check that we 3296 // have at least that many. 3297 if (TheCall->getNumArgs() < 1+NumFixed) { 3298 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3299 << 0 << 1+NumFixed << TheCall->getNumArgs() 3300 << TheCall->getCallee()->getSourceRange(); 3301 return ExprError(); 3302 } 3303 3304 if (WarnAboutSemanticsChange) { 3305 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3306 << TheCall->getCallee()->getSourceRange(); 3307 } 3308 3309 // Get the decl for the concrete builtin from this, we can tell what the 3310 // concrete integer type we should convert to is. 3311 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3312 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3313 FunctionDecl *NewBuiltinDecl; 3314 if (NewBuiltinID == BuiltinID) 3315 NewBuiltinDecl = FDecl; 3316 else { 3317 // Perform builtin lookup to avoid redeclaring it. 3318 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3319 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3320 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3321 assert(Res.getFoundDecl()); 3322 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3323 if (!NewBuiltinDecl) 3324 return ExprError(); 3325 } 3326 3327 // The first argument --- the pointer --- has a fixed type; we 3328 // deduce the types of the rest of the arguments accordingly. Walk 3329 // the remaining arguments, converting them to the deduced value type. 3330 for (unsigned i = 0; i != NumFixed; ++i) { 3331 ExprResult Arg = TheCall->getArg(i+1); 3332 3333 // GCC does an implicit conversion to the pointer or integer ValType. This 3334 // can fail in some cases (1i -> int**), check for this error case now. 3335 // Initialize the argument. 3336 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3337 ValType, /*consume*/ false); 3338 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3339 if (Arg.isInvalid()) 3340 return ExprError(); 3341 3342 // Okay, we have something that *can* be converted to the right type. Check 3343 // to see if there is a potentially weird extension going on here. This can 3344 // happen when you do an atomic operation on something like an char* and 3345 // pass in 42. The 42 gets converted to char. This is even more strange 3346 // for things like 45.123 -> char, etc. 3347 // FIXME: Do this check. 3348 TheCall->setArg(i+1, Arg.get()); 3349 } 3350 3351 ASTContext& Context = this->getASTContext(); 3352 3353 // Create a new DeclRefExpr to refer to the new decl. 3354 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3355 Context, 3356 DRE->getQualifierLoc(), 3357 SourceLocation(), 3358 NewBuiltinDecl, 3359 /*enclosing*/ false, 3360 DRE->getLocation(), 3361 Context.BuiltinFnTy, 3362 DRE->getValueKind()); 3363 3364 // Set the callee in the CallExpr. 3365 // FIXME: This loses syntactic information. 3366 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3367 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3368 CK_BuiltinFnToFnPtr); 3369 TheCall->setCallee(PromotedCall.get()); 3370 3371 // Change the result type of the call to match the original value type. This 3372 // is arbitrary, but the codegen for these builtins ins design to handle it 3373 // gracefully. 3374 TheCall->setType(ResultType); 3375 3376 return TheCallResult; 3377 } 3378 3379 /// SemaBuiltinNontemporalOverloaded - We have a call to 3380 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3381 /// overloaded function based on the pointer type of its last argument. 3382 /// 3383 /// This function goes through and does final semantic checking for these 3384 /// builtins. 3385 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3386 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3387 DeclRefExpr *DRE = 3388 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3389 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3390 unsigned BuiltinID = FDecl->getBuiltinID(); 3391 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3392 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3393 "Unexpected nontemporal load/store builtin!"); 3394 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3395 unsigned numArgs = isStore ? 2 : 1; 3396 3397 // Ensure that we have the proper number of arguments. 3398 if (checkArgCount(*this, TheCall, numArgs)) 3399 return ExprError(); 3400 3401 // Inspect the last argument of the nontemporal builtin. This should always 3402 // be a pointer type, from which we imply the type of the memory access. 3403 // Because it is a pointer type, we don't have to worry about any implicit 3404 // casts here. 3405 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3406 ExprResult PointerArgResult = 3407 DefaultFunctionArrayLvalueConversion(PointerArg); 3408 3409 if (PointerArgResult.isInvalid()) 3410 return ExprError(); 3411 PointerArg = PointerArgResult.get(); 3412 TheCall->setArg(numArgs - 1, PointerArg); 3413 3414 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3415 if (!pointerType) { 3416 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3417 << PointerArg->getType() << PointerArg->getSourceRange(); 3418 return ExprError(); 3419 } 3420 3421 QualType ValType = pointerType->getPointeeType(); 3422 3423 // Strip any qualifiers off ValType. 3424 ValType = ValType.getUnqualifiedType(); 3425 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3426 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3427 !ValType->isVectorType()) { 3428 Diag(DRE->getLocStart(), 3429 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3430 << PointerArg->getType() << PointerArg->getSourceRange(); 3431 return ExprError(); 3432 } 3433 3434 if (!isStore) { 3435 TheCall->setType(ValType); 3436 return TheCallResult; 3437 } 3438 3439 ExprResult ValArg = TheCall->getArg(0); 3440 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3441 Context, ValType, /*consume*/ false); 3442 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3443 if (ValArg.isInvalid()) 3444 return ExprError(); 3445 3446 TheCall->setArg(0, ValArg.get()); 3447 TheCall->setType(Context.VoidTy); 3448 return TheCallResult; 3449 } 3450 3451 /// CheckObjCString - Checks that the argument to the builtin 3452 /// CFString constructor is correct 3453 /// Note: It might also make sense to do the UTF-16 conversion here (would 3454 /// simplify the backend). 3455 bool Sema::CheckObjCString(Expr *Arg) { 3456 Arg = Arg->IgnoreParenCasts(); 3457 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3458 3459 if (!Literal || !Literal->isAscii()) { 3460 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3461 << Arg->getSourceRange(); 3462 return true; 3463 } 3464 3465 if (Literal->containsNonAsciiOrNull()) { 3466 StringRef String = Literal->getString(); 3467 unsigned NumBytes = String.size(); 3468 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3469 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3470 llvm::UTF16 *ToPtr = &ToBuf[0]; 3471 3472 llvm::ConversionResult Result = 3473 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3474 ToPtr + NumBytes, llvm::strictConversion); 3475 // Check for conversion failure. 3476 if (Result != llvm::conversionOK) 3477 Diag(Arg->getLocStart(), 3478 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3479 } 3480 return false; 3481 } 3482 3483 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3484 /// for validity. Emit an error and return true on failure; return false 3485 /// on success. 3486 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) { 3487 Expr *Fn = TheCall->getCallee(); 3488 if (TheCall->getNumArgs() > 2) { 3489 Diag(TheCall->getArg(2)->getLocStart(), 3490 diag::err_typecheck_call_too_many_args) 3491 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3492 << Fn->getSourceRange() 3493 << SourceRange(TheCall->getArg(2)->getLocStart(), 3494 (*(TheCall->arg_end()-1))->getLocEnd()); 3495 return true; 3496 } 3497 3498 if (TheCall->getNumArgs() < 2) { 3499 return Diag(TheCall->getLocEnd(), 3500 diag::err_typecheck_call_too_few_args_at_least) 3501 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3502 } 3503 3504 // Type-check the first argument normally. 3505 if (checkBuiltinArgument(*this, TheCall, 0)) 3506 return true; 3507 3508 // Determine whether the current function is variadic or not. 3509 BlockScopeInfo *CurBlock = getCurBlock(); 3510 bool isVariadic; 3511 if (CurBlock) 3512 isVariadic = CurBlock->TheDecl->isVariadic(); 3513 else if (FunctionDecl *FD = getCurFunctionDecl()) 3514 isVariadic = FD->isVariadic(); 3515 else 3516 isVariadic = getCurMethodDecl()->isVariadic(); 3517 3518 if (!isVariadic) { 3519 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3520 return true; 3521 } 3522 3523 // Verify that the second argument to the builtin is the last argument of the 3524 // current function or method. 3525 bool SecondArgIsLastNamedArgument = false; 3526 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3527 3528 // These are valid if SecondArgIsLastNamedArgument is false after the next 3529 // block. 3530 QualType Type; 3531 SourceLocation ParamLoc; 3532 bool IsCRegister = false; 3533 3534 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3535 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3536 // FIXME: This isn't correct for methods (results in bogus warning). 3537 // Get the last formal in the current function. 3538 const ParmVarDecl *LastArg; 3539 if (CurBlock) 3540 LastArg = CurBlock->TheDecl->parameters().back(); 3541 else if (FunctionDecl *FD = getCurFunctionDecl()) 3542 LastArg = FD->parameters().back(); 3543 else 3544 LastArg = getCurMethodDecl()->parameters().back(); 3545 SecondArgIsLastNamedArgument = PV == LastArg; 3546 3547 Type = PV->getType(); 3548 ParamLoc = PV->getLocation(); 3549 IsCRegister = 3550 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3551 } 3552 } 3553 3554 if (!SecondArgIsLastNamedArgument) 3555 Diag(TheCall->getArg(1)->getLocStart(), 3556 diag::warn_second_arg_of_va_start_not_last_named_param); 3557 else if (IsCRegister || Type->isReferenceType() || 3558 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3559 // Promotable integers are UB, but enumerations need a bit of 3560 // extra checking to see what their promotable type actually is. 3561 if (!Type->isPromotableIntegerType()) 3562 return false; 3563 if (!Type->isEnumeralType()) 3564 return true; 3565 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3566 return !(ED && 3567 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3568 }()) { 3569 unsigned Reason = 0; 3570 if (Type->isReferenceType()) Reason = 1; 3571 else if (IsCRegister) Reason = 2; 3572 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3573 Diag(ParamLoc, diag::note_parameter_type) << Type; 3574 } 3575 3576 TheCall->setType(Context.VoidTy); 3577 return false; 3578 } 3579 3580 /// Check the arguments to '__builtin_va_start' for validity, and that 3581 /// it was called from a function of the native ABI. 3582 /// Emit an error and return true on failure; return false on success. 3583 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 3584 // On x86-64 Unix, don't allow this in Win64 ABI functions. 3585 // On x64 Windows, don't allow this in System V ABI functions. 3586 // (Yes, that means there's no corresponding way to support variadic 3587 // System V ABI functions on Windows.) 3588 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) { 3589 unsigned OS = Context.getTargetInfo().getTriple().getOS(); 3590 clang::CallingConv CC = CC_C; 3591 if (const FunctionDecl *FD = getCurFunctionDecl()) 3592 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3593 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) || 3594 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64)) 3595 return Diag(TheCall->getCallee()->getLocStart(), 3596 diag::err_va_start_used_in_wrong_abi_function) 3597 << (OS != llvm::Triple::Win32); 3598 } 3599 return SemaBuiltinVAStartImpl(TheCall); 3600 } 3601 3602 /// Check the arguments to '__builtin_ms_va_start' for validity, and that 3603 /// it was called from a Win64 ABI function. 3604 /// Emit an error and return true on failure; return false on success. 3605 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) { 3606 // This only makes sense for x86-64. 3607 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3608 Expr *Callee = TheCall->getCallee(); 3609 if (TT.getArch() != llvm::Triple::x86_64) 3610 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt); 3611 // Don't allow this in System V ABI functions. 3612 clang::CallingConv CC = CC_C; 3613 if (const FunctionDecl *FD = getCurFunctionDecl()) 3614 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3615 if (CC == CC_X86_64SysV || 3616 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64)) 3617 return Diag(Callee->getLocStart(), 3618 diag::err_ms_va_start_used_in_sysv_function); 3619 return SemaBuiltinVAStartImpl(TheCall); 3620 } 3621 3622 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3623 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3624 // const char *named_addr); 3625 3626 Expr *Func = Call->getCallee(); 3627 3628 if (Call->getNumArgs() < 3) 3629 return Diag(Call->getLocEnd(), 3630 diag::err_typecheck_call_too_few_args_at_least) 3631 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3632 3633 // Determine whether the current function is variadic or not. 3634 bool IsVariadic; 3635 if (BlockScopeInfo *CurBlock = getCurBlock()) 3636 IsVariadic = CurBlock->TheDecl->isVariadic(); 3637 else if (FunctionDecl *FD = getCurFunctionDecl()) 3638 IsVariadic = FD->isVariadic(); 3639 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 3640 IsVariadic = MD->isVariadic(); 3641 else 3642 llvm_unreachable("unexpected statement type"); 3643 3644 if (!IsVariadic) { 3645 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3646 return true; 3647 } 3648 3649 // Type-check the first argument normally. 3650 if (checkBuiltinArgument(*this, Call, 0)) 3651 return true; 3652 3653 const struct { 3654 unsigned ArgNo; 3655 QualType Type; 3656 } ArgumentTypes[] = { 3657 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3658 { 2, Context.getSizeType() }, 3659 }; 3660 3661 for (const auto &AT : ArgumentTypes) { 3662 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3663 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3664 continue; 3665 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3666 << Arg->getType() << AT.Type << 1 /* different class */ 3667 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3668 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3669 } 3670 3671 return false; 3672 } 3673 3674 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3675 /// friends. This is declared to take (...), so we have to check everything. 3676 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3677 if (TheCall->getNumArgs() < 2) 3678 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3679 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3680 if (TheCall->getNumArgs() > 2) 3681 return Diag(TheCall->getArg(2)->getLocStart(), 3682 diag::err_typecheck_call_too_many_args) 3683 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3684 << SourceRange(TheCall->getArg(2)->getLocStart(), 3685 (*(TheCall->arg_end()-1))->getLocEnd()); 3686 3687 ExprResult OrigArg0 = TheCall->getArg(0); 3688 ExprResult OrigArg1 = TheCall->getArg(1); 3689 3690 // Do standard promotions between the two arguments, returning their common 3691 // type. 3692 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3693 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3694 return true; 3695 3696 // Make sure any conversions are pushed back into the call; this is 3697 // type safe since unordered compare builtins are declared as "_Bool 3698 // foo(...)". 3699 TheCall->setArg(0, OrigArg0.get()); 3700 TheCall->setArg(1, OrigArg1.get()); 3701 3702 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3703 return false; 3704 3705 // If the common type isn't a real floating type, then the arguments were 3706 // invalid for this operation. 3707 if (Res.isNull() || !Res->isRealFloatingType()) 3708 return Diag(OrigArg0.get()->getLocStart(), 3709 diag::err_typecheck_call_invalid_ordered_compare) 3710 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3711 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3712 3713 return false; 3714 } 3715 3716 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3717 /// __builtin_isnan and friends. This is declared to take (...), so we have 3718 /// to check everything. We expect the last argument to be a floating point 3719 /// value. 3720 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3721 if (TheCall->getNumArgs() < NumArgs) 3722 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3723 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3724 if (TheCall->getNumArgs() > NumArgs) 3725 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3726 diag::err_typecheck_call_too_many_args) 3727 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3728 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3729 (*(TheCall->arg_end()-1))->getLocEnd()); 3730 3731 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3732 3733 if (OrigArg->isTypeDependent()) 3734 return false; 3735 3736 // This operation requires a non-_Complex floating-point number. 3737 if (!OrigArg->getType()->isRealFloatingType()) 3738 return Diag(OrigArg->getLocStart(), 3739 diag::err_typecheck_call_invalid_unary_fp) 3740 << OrigArg->getType() << OrigArg->getSourceRange(); 3741 3742 // If this is an implicit conversion from float -> double, remove it. 3743 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 3744 Expr *CastArg = Cast->getSubExpr(); 3745 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 3746 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 3747 "promotion from float to double is the only expected cast here"); 3748 Cast->setSubExpr(nullptr); 3749 TheCall->setArg(NumArgs-1, CastArg); 3750 } 3751 } 3752 3753 return false; 3754 } 3755 3756 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 3757 // This is declared to take (...), so we have to check everything. 3758 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 3759 if (TheCall->getNumArgs() < 2) 3760 return ExprError(Diag(TheCall->getLocEnd(), 3761 diag::err_typecheck_call_too_few_args_at_least) 3762 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3763 << TheCall->getSourceRange()); 3764 3765 // Determine which of the following types of shufflevector we're checking: 3766 // 1) unary, vector mask: (lhs, mask) 3767 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 3768 QualType resType = TheCall->getArg(0)->getType(); 3769 unsigned numElements = 0; 3770 3771 if (!TheCall->getArg(0)->isTypeDependent() && 3772 !TheCall->getArg(1)->isTypeDependent()) { 3773 QualType LHSType = TheCall->getArg(0)->getType(); 3774 QualType RHSType = TheCall->getArg(1)->getType(); 3775 3776 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 3777 return ExprError(Diag(TheCall->getLocStart(), 3778 diag::err_shufflevector_non_vector) 3779 << SourceRange(TheCall->getArg(0)->getLocStart(), 3780 TheCall->getArg(1)->getLocEnd())); 3781 3782 numElements = LHSType->getAs<VectorType>()->getNumElements(); 3783 unsigned numResElements = TheCall->getNumArgs() - 2; 3784 3785 // Check to see if we have a call with 2 vector arguments, the unary shuffle 3786 // with mask. If so, verify that RHS is an integer vector type with the 3787 // same number of elts as lhs. 3788 if (TheCall->getNumArgs() == 2) { 3789 if (!RHSType->hasIntegerRepresentation() || 3790 RHSType->getAs<VectorType>()->getNumElements() != numElements) 3791 return ExprError(Diag(TheCall->getLocStart(), 3792 diag::err_shufflevector_incompatible_vector) 3793 << SourceRange(TheCall->getArg(1)->getLocStart(), 3794 TheCall->getArg(1)->getLocEnd())); 3795 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 3796 return ExprError(Diag(TheCall->getLocStart(), 3797 diag::err_shufflevector_incompatible_vector) 3798 << SourceRange(TheCall->getArg(0)->getLocStart(), 3799 TheCall->getArg(1)->getLocEnd())); 3800 } else if (numElements != numResElements) { 3801 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 3802 resType = Context.getVectorType(eltType, numResElements, 3803 VectorType::GenericVector); 3804 } 3805 } 3806 3807 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 3808 if (TheCall->getArg(i)->isTypeDependent() || 3809 TheCall->getArg(i)->isValueDependent()) 3810 continue; 3811 3812 llvm::APSInt Result(32); 3813 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 3814 return ExprError(Diag(TheCall->getLocStart(), 3815 diag::err_shufflevector_nonconstant_argument) 3816 << TheCall->getArg(i)->getSourceRange()); 3817 3818 // Allow -1 which will be translated to undef in the IR. 3819 if (Result.isSigned() && Result.isAllOnesValue()) 3820 continue; 3821 3822 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 3823 return ExprError(Diag(TheCall->getLocStart(), 3824 diag::err_shufflevector_argument_too_large) 3825 << TheCall->getArg(i)->getSourceRange()); 3826 } 3827 3828 SmallVector<Expr*, 32> exprs; 3829 3830 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 3831 exprs.push_back(TheCall->getArg(i)); 3832 TheCall->setArg(i, nullptr); 3833 } 3834 3835 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 3836 TheCall->getCallee()->getLocStart(), 3837 TheCall->getRParenLoc()); 3838 } 3839 3840 /// SemaConvertVectorExpr - Handle __builtin_convertvector 3841 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 3842 SourceLocation BuiltinLoc, 3843 SourceLocation RParenLoc) { 3844 ExprValueKind VK = VK_RValue; 3845 ExprObjectKind OK = OK_Ordinary; 3846 QualType DstTy = TInfo->getType(); 3847 QualType SrcTy = E->getType(); 3848 3849 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 3850 return ExprError(Diag(BuiltinLoc, 3851 diag::err_convertvector_non_vector) 3852 << E->getSourceRange()); 3853 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 3854 return ExprError(Diag(BuiltinLoc, 3855 diag::err_convertvector_non_vector_type)); 3856 3857 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 3858 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 3859 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 3860 if (SrcElts != DstElts) 3861 return ExprError(Diag(BuiltinLoc, 3862 diag::err_convertvector_incompatible_vector) 3863 << E->getSourceRange()); 3864 } 3865 3866 return new (Context) 3867 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 3868 } 3869 3870 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 3871 // This is declared to take (const void*, ...) and can take two 3872 // optional constant int args. 3873 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 3874 unsigned NumArgs = TheCall->getNumArgs(); 3875 3876 if (NumArgs > 3) 3877 return Diag(TheCall->getLocEnd(), 3878 diag::err_typecheck_call_too_many_args_at_most) 3879 << 0 /*function call*/ << 3 << NumArgs 3880 << TheCall->getSourceRange(); 3881 3882 // Argument 0 is checked for us and the remaining arguments must be 3883 // constant integers. 3884 for (unsigned i = 1; i != NumArgs; ++i) 3885 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 3886 return true; 3887 3888 return false; 3889 } 3890 3891 /// SemaBuiltinAssume - Handle __assume (MS Extension). 3892 // __assume does not evaluate its arguments, and should warn if its argument 3893 // has side effects. 3894 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 3895 Expr *Arg = TheCall->getArg(0); 3896 if (Arg->isInstantiationDependent()) return false; 3897 3898 if (Arg->HasSideEffects(Context)) 3899 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 3900 << Arg->getSourceRange() 3901 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 3902 3903 return false; 3904 } 3905 3906 /// Handle __builtin_assume_aligned. This is declared 3907 /// as (const void*, size_t, ...) and can take one optional constant int arg. 3908 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 3909 unsigned NumArgs = TheCall->getNumArgs(); 3910 3911 if (NumArgs > 3) 3912 return Diag(TheCall->getLocEnd(), 3913 diag::err_typecheck_call_too_many_args_at_most) 3914 << 0 /*function call*/ << 3 << NumArgs 3915 << TheCall->getSourceRange(); 3916 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 llvm::APSInt Result; 3923 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 3924 return true; 3925 3926 if (!Result.isPowerOf2()) 3927 return Diag(TheCall->getLocStart(), 3928 diag::err_alignment_not_power_of_two) 3929 << Arg->getSourceRange(); 3930 } 3931 3932 if (NumArgs > 2) { 3933 ExprResult Arg(TheCall->getArg(2)); 3934 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3935 Context.getSizeType(), false); 3936 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3937 if (Arg.isInvalid()) return true; 3938 TheCall->setArg(2, Arg.get()); 3939 } 3940 3941 return false; 3942 } 3943 3944 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 3945 /// TheCall is a constant expression. 3946 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 3947 llvm::APSInt &Result) { 3948 Expr *Arg = TheCall->getArg(ArgNum); 3949 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3950 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3951 3952 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 3953 3954 if (!Arg->isIntegerConstantExpr(Result, Context)) 3955 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 3956 << FDecl->getDeclName() << Arg->getSourceRange(); 3957 3958 return false; 3959 } 3960 3961 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 3962 /// TheCall is a constant expression in the range [Low, High]. 3963 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 3964 int Low, int High) { 3965 llvm::APSInt Result; 3966 3967 // We can't check the value of a dependent argument. 3968 Expr *Arg = TheCall->getArg(ArgNum); 3969 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3970 return false; 3971 3972 // Check constant-ness first. 3973 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3974 return true; 3975 3976 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 3977 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 3978 << Low << High << Arg->getSourceRange(); 3979 3980 return false; 3981 } 3982 3983 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 3984 /// TheCall is a constant expression is a multiple of Num.. 3985 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 3986 unsigned Num) { 3987 llvm::APSInt Result; 3988 3989 // We can't check the value of a dependent argument. 3990 Expr *Arg = TheCall->getArg(ArgNum); 3991 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3992 return false; 3993 3994 // Check constant-ness first. 3995 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3996 return true; 3997 3998 if (Result.getSExtValue() % Num != 0) 3999 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4000 << Num << Arg->getSourceRange(); 4001 4002 return false; 4003 } 4004 4005 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4006 /// TheCall is an ARM/AArch64 special register string literal. 4007 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4008 int ArgNum, unsigned ExpectedFieldNum, 4009 bool AllowName) { 4010 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4011 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4012 BuiltinID == ARM::BI__builtin_arm_rsr || 4013 BuiltinID == ARM::BI__builtin_arm_rsrp || 4014 BuiltinID == ARM::BI__builtin_arm_wsr || 4015 BuiltinID == ARM::BI__builtin_arm_wsrp; 4016 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4017 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4018 BuiltinID == AArch64::BI__builtin_arm_rsr || 4019 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4020 BuiltinID == AArch64::BI__builtin_arm_wsr || 4021 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4022 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4023 4024 // We can't check the value of a dependent argument. 4025 Expr *Arg = TheCall->getArg(ArgNum); 4026 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4027 return false; 4028 4029 // Check if the argument is a string literal. 4030 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4031 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4032 << Arg->getSourceRange(); 4033 4034 // Check the type of special register given. 4035 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4036 SmallVector<StringRef, 6> Fields; 4037 Reg.split(Fields, ":"); 4038 4039 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4040 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4041 << Arg->getSourceRange(); 4042 4043 // If the string is the name of a register then we cannot check that it is 4044 // valid here but if the string is of one the forms described in ACLE then we 4045 // can check that the supplied fields are integers and within the valid 4046 // ranges. 4047 if (Fields.size() > 1) { 4048 bool FiveFields = Fields.size() == 5; 4049 4050 bool ValidString = true; 4051 if (IsARMBuiltin) { 4052 ValidString &= Fields[0].startswith_lower("cp") || 4053 Fields[0].startswith_lower("p"); 4054 if (ValidString) 4055 Fields[0] = 4056 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4057 4058 ValidString &= Fields[2].startswith_lower("c"); 4059 if (ValidString) 4060 Fields[2] = Fields[2].drop_front(1); 4061 4062 if (FiveFields) { 4063 ValidString &= Fields[3].startswith_lower("c"); 4064 if (ValidString) 4065 Fields[3] = Fields[3].drop_front(1); 4066 } 4067 } 4068 4069 SmallVector<int, 5> Ranges; 4070 if (FiveFields) 4071 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15}); 4072 else 4073 Ranges.append({15, 7, 15}); 4074 4075 for (unsigned i=0; i<Fields.size(); ++i) { 4076 int IntField; 4077 ValidString &= !Fields[i].getAsInteger(10, IntField); 4078 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4079 } 4080 4081 if (!ValidString) 4082 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4083 << Arg->getSourceRange(); 4084 4085 } else if (IsAArch64Builtin && Fields.size() == 1) { 4086 // If the register name is one of those that appear in the condition below 4087 // and the special register builtin being used is one of the write builtins, 4088 // then we require that the argument provided for writing to the register 4089 // is an integer constant expression. This is because it will be lowered to 4090 // an MSR (immediate) instruction, so we need to know the immediate at 4091 // compile time. 4092 if (TheCall->getNumArgs() != 2) 4093 return false; 4094 4095 std::string RegLower = Reg.lower(); 4096 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4097 RegLower != "pan" && RegLower != "uao") 4098 return false; 4099 4100 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4101 } 4102 4103 return false; 4104 } 4105 4106 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4107 /// This checks that the target supports __builtin_longjmp and 4108 /// that val is a constant 1. 4109 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4110 if (!Context.getTargetInfo().hasSjLjLowering()) 4111 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4112 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4113 4114 Expr *Arg = TheCall->getArg(1); 4115 llvm::APSInt Result; 4116 4117 // TODO: This is less than ideal. Overload this to take a value. 4118 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4119 return true; 4120 4121 if (Result != 1) 4122 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4123 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4124 4125 return false; 4126 } 4127 4128 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4129 /// This checks that the target supports __builtin_setjmp. 4130 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4131 if (!Context.getTargetInfo().hasSjLjLowering()) 4132 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4133 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4134 return false; 4135 } 4136 4137 namespace { 4138 class UncoveredArgHandler { 4139 enum { Unknown = -1, AllCovered = -2 }; 4140 signed FirstUncoveredArg; 4141 SmallVector<const Expr *, 4> DiagnosticExprs; 4142 4143 public: 4144 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4145 4146 bool hasUncoveredArg() const { 4147 return (FirstUncoveredArg >= 0); 4148 } 4149 4150 unsigned getUncoveredArg() const { 4151 assert(hasUncoveredArg() && "no uncovered argument"); 4152 return FirstUncoveredArg; 4153 } 4154 4155 void setAllCovered() { 4156 // A string has been found with all arguments covered, so clear out 4157 // the diagnostics. 4158 DiagnosticExprs.clear(); 4159 FirstUncoveredArg = AllCovered; 4160 } 4161 4162 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4163 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4164 4165 // Don't update if a previous string covers all arguments. 4166 if (FirstUncoveredArg == AllCovered) 4167 return; 4168 4169 // UncoveredArgHandler tracks the highest uncovered argument index 4170 // and with it all the strings that match this index. 4171 if (NewFirstUncoveredArg == FirstUncoveredArg) 4172 DiagnosticExprs.push_back(StrExpr); 4173 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4174 DiagnosticExprs.clear(); 4175 DiagnosticExprs.push_back(StrExpr); 4176 FirstUncoveredArg = NewFirstUncoveredArg; 4177 } 4178 } 4179 4180 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4181 }; 4182 4183 enum StringLiteralCheckType { 4184 SLCT_NotALiteral, 4185 SLCT_UncheckedLiteral, 4186 SLCT_CheckedLiteral 4187 }; 4188 } // end anonymous namespace 4189 4190 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4191 BinaryOperatorKind BinOpKind, 4192 bool AddendIsRight) { 4193 unsigned BitWidth = Offset.getBitWidth(); 4194 unsigned AddendBitWidth = Addend.getBitWidth(); 4195 // There might be negative interim results. 4196 if (Addend.isUnsigned()) { 4197 Addend = Addend.zext(++AddendBitWidth); 4198 Addend.setIsSigned(true); 4199 } 4200 // Adjust the bit width of the APSInts. 4201 if (AddendBitWidth > BitWidth) { 4202 Offset = Offset.sext(AddendBitWidth); 4203 BitWidth = AddendBitWidth; 4204 } else if (BitWidth > AddendBitWidth) { 4205 Addend = Addend.sext(BitWidth); 4206 } 4207 4208 bool Ov = false; 4209 llvm::APSInt ResOffset = Offset; 4210 if (BinOpKind == BO_Add) 4211 ResOffset = Offset.sadd_ov(Addend, Ov); 4212 else { 4213 assert(AddendIsRight && BinOpKind == BO_Sub && 4214 "operator must be add or sub with addend on the right"); 4215 ResOffset = Offset.ssub_ov(Addend, Ov); 4216 } 4217 4218 // We add an offset to a pointer here so we should support an offset as big as 4219 // possible. 4220 if (Ov) { 4221 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4222 Offset = Offset.sext(2 * BitWidth); 4223 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4224 return; 4225 } 4226 4227 Offset = ResOffset; 4228 } 4229 4230 namespace { 4231 // This is a wrapper class around StringLiteral to support offsetted string 4232 // literals as format strings. It takes the offset into account when returning 4233 // the string and its length or the source locations to display notes correctly. 4234 class FormatStringLiteral { 4235 const StringLiteral *FExpr; 4236 int64_t Offset; 4237 4238 public: 4239 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4240 : FExpr(fexpr), Offset(Offset) {} 4241 4242 StringRef getString() const { 4243 return FExpr->getString().drop_front(Offset); 4244 } 4245 4246 unsigned getByteLength() const { 4247 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4248 } 4249 unsigned getLength() const { return FExpr->getLength() - Offset; } 4250 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4251 4252 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4253 4254 QualType getType() const { return FExpr->getType(); } 4255 4256 bool isAscii() const { return FExpr->isAscii(); } 4257 bool isWide() const { return FExpr->isWide(); } 4258 bool isUTF8() const { return FExpr->isUTF8(); } 4259 bool isUTF16() const { return FExpr->isUTF16(); } 4260 bool isUTF32() const { return FExpr->isUTF32(); } 4261 bool isPascal() const { return FExpr->isPascal(); } 4262 4263 SourceLocation getLocationOfByte( 4264 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4265 const TargetInfo &Target, unsigned *StartToken = nullptr, 4266 unsigned *StartTokenByteOffset = nullptr) const { 4267 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4268 StartToken, StartTokenByteOffset); 4269 } 4270 4271 SourceLocation getLocStart() const LLVM_READONLY { 4272 return FExpr->getLocStart().getLocWithOffset(Offset); 4273 } 4274 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4275 }; 4276 } // end anonymous namespace 4277 4278 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4279 const Expr *OrigFormatExpr, 4280 ArrayRef<const Expr *> Args, 4281 bool HasVAListArg, unsigned format_idx, 4282 unsigned firstDataArg, 4283 Sema::FormatStringType Type, 4284 bool inFunctionCall, 4285 Sema::VariadicCallType CallType, 4286 llvm::SmallBitVector &CheckedVarArgs, 4287 UncoveredArgHandler &UncoveredArg); 4288 4289 // Determine if an expression is a string literal or constant string. 4290 // If this function returns false on the arguments to a function expecting a 4291 // format string, we will usually need to emit a warning. 4292 // True string literals are then checked by CheckFormatString. 4293 static StringLiteralCheckType 4294 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4295 bool HasVAListArg, unsigned format_idx, 4296 unsigned firstDataArg, Sema::FormatStringType Type, 4297 Sema::VariadicCallType CallType, bool InFunctionCall, 4298 llvm::SmallBitVector &CheckedVarArgs, 4299 UncoveredArgHandler &UncoveredArg, 4300 llvm::APSInt Offset) { 4301 tryAgain: 4302 assert(Offset.isSigned() && "invalid offset"); 4303 4304 if (E->isTypeDependent() || E->isValueDependent()) 4305 return SLCT_NotALiteral; 4306 4307 E = E->IgnoreParenCasts(); 4308 4309 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4310 // Technically -Wformat-nonliteral does not warn about this case. 4311 // The behavior of printf and friends in this case is implementation 4312 // dependent. Ideally if the format string cannot be null then 4313 // it should have a 'nonnull' attribute in the function prototype. 4314 return SLCT_UncheckedLiteral; 4315 4316 switch (E->getStmtClass()) { 4317 case Stmt::BinaryConditionalOperatorClass: 4318 case Stmt::ConditionalOperatorClass: { 4319 // The expression is a literal if both sub-expressions were, and it was 4320 // completely checked only if both sub-expressions were checked. 4321 const AbstractConditionalOperator *C = 4322 cast<AbstractConditionalOperator>(E); 4323 4324 // Determine whether it is necessary to check both sub-expressions, for 4325 // example, because the condition expression is a constant that can be 4326 // evaluated at compile time. 4327 bool CheckLeft = true, CheckRight = true; 4328 4329 bool Cond; 4330 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4331 if (Cond) 4332 CheckRight = false; 4333 else 4334 CheckLeft = false; 4335 } 4336 4337 // We need to maintain the offsets for the right and the left hand side 4338 // separately to check if every possible indexed expression is a valid 4339 // string literal. They might have different offsets for different string 4340 // literals in the end. 4341 StringLiteralCheckType Left; 4342 if (!CheckLeft) 4343 Left = SLCT_UncheckedLiteral; 4344 else { 4345 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4346 HasVAListArg, format_idx, firstDataArg, 4347 Type, CallType, InFunctionCall, 4348 CheckedVarArgs, UncoveredArg, Offset); 4349 if (Left == SLCT_NotALiteral || !CheckRight) { 4350 return Left; 4351 } 4352 } 4353 4354 StringLiteralCheckType Right = 4355 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4356 HasVAListArg, format_idx, firstDataArg, 4357 Type, CallType, InFunctionCall, CheckedVarArgs, 4358 UncoveredArg, Offset); 4359 4360 return (CheckLeft && Left < Right) ? Left : Right; 4361 } 4362 4363 case Stmt::ImplicitCastExprClass: { 4364 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4365 goto tryAgain; 4366 } 4367 4368 case Stmt::OpaqueValueExprClass: 4369 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4370 E = src; 4371 goto tryAgain; 4372 } 4373 return SLCT_NotALiteral; 4374 4375 case Stmt::PredefinedExprClass: 4376 // While __func__, etc., are technically not string literals, they 4377 // cannot contain format specifiers and thus are not a security 4378 // liability. 4379 return SLCT_UncheckedLiteral; 4380 4381 case Stmt::DeclRefExprClass: { 4382 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4383 4384 // As an exception, do not flag errors for variables binding to 4385 // const string literals. 4386 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4387 bool isConstant = false; 4388 QualType T = DR->getType(); 4389 4390 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4391 isConstant = AT->getElementType().isConstant(S.Context); 4392 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4393 isConstant = T.isConstant(S.Context) && 4394 PT->getPointeeType().isConstant(S.Context); 4395 } else if (T->isObjCObjectPointerType()) { 4396 // In ObjC, there is usually no "const ObjectPointer" type, 4397 // so don't check if the pointee type is constant. 4398 isConstant = T.isConstant(S.Context); 4399 } 4400 4401 if (isConstant) { 4402 if (const Expr *Init = VD->getAnyInitializer()) { 4403 // Look through initializers like const char c[] = { "foo" } 4404 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4405 if (InitList->isStringLiteralInit()) 4406 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4407 } 4408 return checkFormatStringExpr(S, Init, Args, 4409 HasVAListArg, format_idx, 4410 firstDataArg, Type, CallType, 4411 /*InFunctionCall*/ false, CheckedVarArgs, 4412 UncoveredArg, Offset); 4413 } 4414 } 4415 4416 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4417 // special check to see if the format string is a function parameter 4418 // of the function calling the printf function. If the function 4419 // has an attribute indicating it is a printf-like function, then we 4420 // should suppress warnings concerning non-literals being used in a call 4421 // to a vprintf function. For example: 4422 // 4423 // void 4424 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4425 // va_list ap; 4426 // va_start(ap, fmt); 4427 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4428 // ... 4429 // } 4430 if (HasVAListArg) { 4431 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4432 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4433 int PVIndex = PV->getFunctionScopeIndex() + 1; 4434 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4435 // adjust for implicit parameter 4436 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4437 if (MD->isInstance()) 4438 ++PVIndex; 4439 // We also check if the formats are compatible. 4440 // We can't pass a 'scanf' string to a 'printf' function. 4441 if (PVIndex == PVFormat->getFormatIdx() && 4442 Type == S.GetFormatStringType(PVFormat)) 4443 return SLCT_UncheckedLiteral; 4444 } 4445 } 4446 } 4447 } 4448 } 4449 4450 return SLCT_NotALiteral; 4451 } 4452 4453 case Stmt::CallExprClass: 4454 case Stmt::CXXMemberCallExprClass: { 4455 const CallExpr *CE = cast<CallExpr>(E); 4456 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4457 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4458 unsigned ArgIndex = FA->getFormatIdx(); 4459 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4460 if (MD->isInstance()) 4461 --ArgIndex; 4462 const Expr *Arg = CE->getArg(ArgIndex - 1); 4463 4464 return checkFormatStringExpr(S, Arg, Args, 4465 HasVAListArg, format_idx, firstDataArg, 4466 Type, CallType, InFunctionCall, 4467 CheckedVarArgs, UncoveredArg, Offset); 4468 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4469 unsigned BuiltinID = FD->getBuiltinID(); 4470 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4471 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4472 const Expr *Arg = CE->getArg(0); 4473 return checkFormatStringExpr(S, Arg, Args, 4474 HasVAListArg, format_idx, 4475 firstDataArg, Type, CallType, 4476 InFunctionCall, CheckedVarArgs, 4477 UncoveredArg, Offset); 4478 } 4479 } 4480 } 4481 4482 return SLCT_NotALiteral; 4483 } 4484 case Stmt::ObjCStringLiteralClass: 4485 case Stmt::StringLiteralClass: { 4486 const StringLiteral *StrE = nullptr; 4487 4488 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4489 StrE = ObjCFExpr->getString(); 4490 else 4491 StrE = cast<StringLiteral>(E); 4492 4493 if (StrE) { 4494 if (Offset.isNegative() || Offset > StrE->getLength()) { 4495 // TODO: It would be better to have an explicit warning for out of 4496 // bounds literals. 4497 return SLCT_NotALiteral; 4498 } 4499 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4500 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4501 firstDataArg, Type, InFunctionCall, CallType, 4502 CheckedVarArgs, UncoveredArg); 4503 return SLCT_CheckedLiteral; 4504 } 4505 4506 return SLCT_NotALiteral; 4507 } 4508 case Stmt::BinaryOperatorClass: { 4509 llvm::APSInt LResult; 4510 llvm::APSInt RResult; 4511 4512 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 4513 4514 // A string literal + an int offset is still a string literal. 4515 if (BinOp->isAdditiveOp()) { 4516 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 4517 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 4518 4519 if (LIsInt != RIsInt) { 4520 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 4521 4522 if (LIsInt) { 4523 if (BinOpKind == BO_Add) { 4524 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 4525 E = BinOp->getRHS(); 4526 goto tryAgain; 4527 } 4528 } else { 4529 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 4530 E = BinOp->getLHS(); 4531 goto tryAgain; 4532 } 4533 } 4534 } 4535 4536 return SLCT_NotALiteral; 4537 } 4538 case Stmt::UnaryOperatorClass: { 4539 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 4540 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 4541 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 4542 llvm::APSInt IndexResult; 4543 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 4544 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 4545 E = ASE->getBase(); 4546 goto tryAgain; 4547 } 4548 } 4549 4550 return SLCT_NotALiteral; 4551 } 4552 4553 default: 4554 return SLCT_NotALiteral; 4555 } 4556 } 4557 4558 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 4559 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 4560 .Case("scanf", FST_Scanf) 4561 .Cases("printf", "printf0", FST_Printf) 4562 .Cases("NSString", "CFString", FST_NSString) 4563 .Case("strftime", FST_Strftime) 4564 .Case("strfmon", FST_Strfmon) 4565 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 4566 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 4567 .Case("os_trace", FST_OSTrace) 4568 .Default(FST_Unknown); 4569 } 4570 4571 /// CheckFormatArguments - Check calls to printf and scanf (and similar 4572 /// functions) for correct use of format strings. 4573 /// Returns true if a format string has been fully checked. 4574 bool Sema::CheckFormatArguments(const FormatAttr *Format, 4575 ArrayRef<const Expr *> Args, 4576 bool IsCXXMember, 4577 VariadicCallType CallType, 4578 SourceLocation Loc, SourceRange Range, 4579 llvm::SmallBitVector &CheckedVarArgs) { 4580 FormatStringInfo FSI; 4581 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 4582 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 4583 FSI.FirstDataArg, GetFormatStringType(Format), 4584 CallType, Loc, Range, CheckedVarArgs); 4585 return false; 4586 } 4587 4588 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 4589 bool HasVAListArg, unsigned format_idx, 4590 unsigned firstDataArg, FormatStringType Type, 4591 VariadicCallType CallType, 4592 SourceLocation Loc, SourceRange Range, 4593 llvm::SmallBitVector &CheckedVarArgs) { 4594 // CHECK: printf/scanf-like function is called with no format string. 4595 if (format_idx >= Args.size()) { 4596 Diag(Loc, diag::warn_missing_format_string) << Range; 4597 return false; 4598 } 4599 4600 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 4601 4602 // CHECK: format string is not a string literal. 4603 // 4604 // Dynamically generated format strings are difficult to 4605 // automatically vet at compile time. Requiring that format strings 4606 // are string literals: (1) permits the checking of format strings by 4607 // the compiler and thereby (2) can practically remove the source of 4608 // many format string exploits. 4609 4610 // Format string can be either ObjC string (e.g. @"%d") or 4611 // C string (e.g. "%d") 4612 // ObjC string uses the same format specifiers as C string, so we can use 4613 // the same format string checking logic for both ObjC and C strings. 4614 UncoveredArgHandler UncoveredArg; 4615 StringLiteralCheckType CT = 4616 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 4617 format_idx, firstDataArg, Type, CallType, 4618 /*IsFunctionCall*/ true, CheckedVarArgs, 4619 UncoveredArg, 4620 /*no string offset*/ llvm::APSInt(64, false) = 0); 4621 4622 // Generate a diagnostic where an uncovered argument is detected. 4623 if (UncoveredArg.hasUncoveredArg()) { 4624 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 4625 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 4626 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 4627 } 4628 4629 if (CT != SLCT_NotALiteral) 4630 // Literal format string found, check done! 4631 return CT == SLCT_CheckedLiteral; 4632 4633 // Strftime is particular as it always uses a single 'time' argument, 4634 // so it is safe to pass a non-literal string. 4635 if (Type == FST_Strftime) 4636 return false; 4637 4638 // Do not emit diag when the string param is a macro expansion and the 4639 // format is either NSString or CFString. This is a hack to prevent 4640 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 4641 // which are usually used in place of NS and CF string literals. 4642 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 4643 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 4644 return false; 4645 4646 // If there are no arguments specified, warn with -Wformat-security, otherwise 4647 // warn only with -Wformat-nonliteral. 4648 if (Args.size() == firstDataArg) { 4649 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 4650 << OrigFormatExpr->getSourceRange(); 4651 switch (Type) { 4652 default: 4653 break; 4654 case FST_Kprintf: 4655 case FST_FreeBSDKPrintf: 4656 case FST_Printf: 4657 Diag(FormatLoc, diag::note_format_security_fixit) 4658 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 4659 break; 4660 case FST_NSString: 4661 Diag(FormatLoc, diag::note_format_security_fixit) 4662 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 4663 break; 4664 } 4665 } else { 4666 Diag(FormatLoc, diag::warn_format_nonliteral) 4667 << OrigFormatExpr->getSourceRange(); 4668 } 4669 return false; 4670 } 4671 4672 namespace { 4673 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 4674 protected: 4675 Sema &S; 4676 const FormatStringLiteral *FExpr; 4677 const Expr *OrigFormatExpr; 4678 const unsigned FirstDataArg; 4679 const unsigned NumDataArgs; 4680 const char *Beg; // Start of format string. 4681 const bool HasVAListArg; 4682 ArrayRef<const Expr *> Args; 4683 unsigned FormatIdx; 4684 llvm::SmallBitVector CoveredArgs; 4685 bool usesPositionalArgs; 4686 bool atFirstArg; 4687 bool inFunctionCall; 4688 Sema::VariadicCallType CallType; 4689 llvm::SmallBitVector &CheckedVarArgs; 4690 UncoveredArgHandler &UncoveredArg; 4691 4692 public: 4693 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 4694 const Expr *origFormatExpr, unsigned firstDataArg, 4695 unsigned numDataArgs, const char *beg, bool hasVAListArg, 4696 ArrayRef<const Expr *> Args, 4697 unsigned formatIdx, bool inFunctionCall, 4698 Sema::VariadicCallType callType, 4699 llvm::SmallBitVector &CheckedVarArgs, 4700 UncoveredArgHandler &UncoveredArg) 4701 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 4702 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), 4703 Beg(beg), HasVAListArg(hasVAListArg), 4704 Args(Args), FormatIdx(formatIdx), 4705 usesPositionalArgs(false), atFirstArg(true), 4706 inFunctionCall(inFunctionCall), CallType(callType), 4707 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 4708 CoveredArgs.resize(numDataArgs); 4709 CoveredArgs.reset(); 4710 } 4711 4712 void DoneProcessing(); 4713 4714 void HandleIncompleteSpecifier(const char *startSpecifier, 4715 unsigned specifierLen) override; 4716 4717 void HandleInvalidLengthModifier( 4718 const analyze_format_string::FormatSpecifier &FS, 4719 const analyze_format_string::ConversionSpecifier &CS, 4720 const char *startSpecifier, unsigned specifierLen, 4721 unsigned DiagID); 4722 4723 void HandleNonStandardLengthModifier( 4724 const analyze_format_string::FormatSpecifier &FS, 4725 const char *startSpecifier, unsigned specifierLen); 4726 4727 void HandleNonStandardConversionSpecifier( 4728 const analyze_format_string::ConversionSpecifier &CS, 4729 const char *startSpecifier, unsigned specifierLen); 4730 4731 void HandlePosition(const char *startPos, unsigned posLen) override; 4732 4733 void HandleInvalidPosition(const char *startSpecifier, 4734 unsigned specifierLen, 4735 analyze_format_string::PositionContext p) override; 4736 4737 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 4738 4739 void HandleNullChar(const char *nullCharacter) override; 4740 4741 template <typename Range> 4742 static void 4743 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 4744 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 4745 bool IsStringLocation, Range StringRange, 4746 ArrayRef<FixItHint> Fixit = None); 4747 4748 protected: 4749 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 4750 const char *startSpec, 4751 unsigned specifierLen, 4752 const char *csStart, unsigned csLen); 4753 4754 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 4755 const char *startSpec, 4756 unsigned specifierLen); 4757 4758 SourceRange getFormatStringRange(); 4759 CharSourceRange getSpecifierRange(const char *startSpecifier, 4760 unsigned specifierLen); 4761 SourceLocation getLocationOfByte(const char *x); 4762 4763 const Expr *getDataArg(unsigned i) const; 4764 4765 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 4766 const analyze_format_string::ConversionSpecifier &CS, 4767 const char *startSpecifier, unsigned specifierLen, 4768 unsigned argIndex); 4769 4770 template <typename Range> 4771 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 4772 bool IsStringLocation, Range StringRange, 4773 ArrayRef<FixItHint> Fixit = None); 4774 }; 4775 } // end anonymous namespace 4776 4777 SourceRange CheckFormatHandler::getFormatStringRange() { 4778 return OrigFormatExpr->getSourceRange(); 4779 } 4780 4781 CharSourceRange CheckFormatHandler:: 4782 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 4783 SourceLocation Start = getLocationOfByte(startSpecifier); 4784 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 4785 4786 // Advance the end SourceLocation by one due to half-open ranges. 4787 End = End.getLocWithOffset(1); 4788 4789 return CharSourceRange::getCharRange(Start, End); 4790 } 4791 4792 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 4793 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 4794 S.getLangOpts(), S.Context.getTargetInfo()); 4795 } 4796 4797 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 4798 unsigned specifierLen){ 4799 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 4800 getLocationOfByte(startSpecifier), 4801 /*IsStringLocation*/true, 4802 getSpecifierRange(startSpecifier, specifierLen)); 4803 } 4804 4805 void CheckFormatHandler::HandleInvalidLengthModifier( 4806 const analyze_format_string::FormatSpecifier &FS, 4807 const analyze_format_string::ConversionSpecifier &CS, 4808 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 4809 using namespace analyze_format_string; 4810 4811 const LengthModifier &LM = FS.getLengthModifier(); 4812 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4813 4814 // See if we know how to fix this length modifier. 4815 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4816 if (FixedLM) { 4817 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4818 getLocationOfByte(LM.getStart()), 4819 /*IsStringLocation*/true, 4820 getSpecifierRange(startSpecifier, specifierLen)); 4821 4822 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4823 << FixedLM->toString() 4824 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4825 4826 } else { 4827 FixItHint Hint; 4828 if (DiagID == diag::warn_format_nonsensical_length) 4829 Hint = FixItHint::CreateRemoval(LMRange); 4830 4831 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4832 getLocationOfByte(LM.getStart()), 4833 /*IsStringLocation*/true, 4834 getSpecifierRange(startSpecifier, specifierLen), 4835 Hint); 4836 } 4837 } 4838 4839 void CheckFormatHandler::HandleNonStandardLengthModifier( 4840 const analyze_format_string::FormatSpecifier &FS, 4841 const char *startSpecifier, unsigned specifierLen) { 4842 using namespace analyze_format_string; 4843 4844 const LengthModifier &LM = FS.getLengthModifier(); 4845 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4846 4847 // See if we know how to fix this length modifier. 4848 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4849 if (FixedLM) { 4850 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4851 << LM.toString() << 0, 4852 getLocationOfByte(LM.getStart()), 4853 /*IsStringLocation*/true, 4854 getSpecifierRange(startSpecifier, specifierLen)); 4855 4856 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4857 << FixedLM->toString() 4858 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4859 4860 } else { 4861 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4862 << LM.toString() << 0, 4863 getLocationOfByte(LM.getStart()), 4864 /*IsStringLocation*/true, 4865 getSpecifierRange(startSpecifier, specifierLen)); 4866 } 4867 } 4868 4869 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 4870 const analyze_format_string::ConversionSpecifier &CS, 4871 const char *startSpecifier, unsigned specifierLen) { 4872 using namespace analyze_format_string; 4873 4874 // See if we know how to fix this conversion specifier. 4875 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 4876 if (FixedCS) { 4877 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4878 << CS.toString() << /*conversion specifier*/1, 4879 getLocationOfByte(CS.getStart()), 4880 /*IsStringLocation*/true, 4881 getSpecifierRange(startSpecifier, specifierLen)); 4882 4883 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 4884 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 4885 << FixedCS->toString() 4886 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 4887 } else { 4888 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4889 << CS.toString() << /*conversion specifier*/1, 4890 getLocationOfByte(CS.getStart()), 4891 /*IsStringLocation*/true, 4892 getSpecifierRange(startSpecifier, specifierLen)); 4893 } 4894 } 4895 4896 void CheckFormatHandler::HandlePosition(const char *startPos, 4897 unsigned posLen) { 4898 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 4899 getLocationOfByte(startPos), 4900 /*IsStringLocation*/true, 4901 getSpecifierRange(startPos, posLen)); 4902 } 4903 4904 void 4905 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 4906 analyze_format_string::PositionContext p) { 4907 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 4908 << (unsigned) p, 4909 getLocationOfByte(startPos), /*IsStringLocation*/true, 4910 getSpecifierRange(startPos, posLen)); 4911 } 4912 4913 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 4914 unsigned posLen) { 4915 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 4916 getLocationOfByte(startPos), 4917 /*IsStringLocation*/true, 4918 getSpecifierRange(startPos, posLen)); 4919 } 4920 4921 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 4922 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 4923 // The presence of a null character is likely an error. 4924 EmitFormatDiagnostic( 4925 S.PDiag(diag::warn_printf_format_string_contains_null_char), 4926 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 4927 getFormatStringRange()); 4928 } 4929 } 4930 4931 // Note that this may return NULL if there was an error parsing or building 4932 // one of the argument expressions. 4933 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 4934 return Args[FirstDataArg + i]; 4935 } 4936 4937 void CheckFormatHandler::DoneProcessing() { 4938 // Does the number of data arguments exceed the number of 4939 // format conversions in the format string? 4940 if (!HasVAListArg) { 4941 // Find any arguments that weren't covered. 4942 CoveredArgs.flip(); 4943 signed notCoveredArg = CoveredArgs.find_first(); 4944 if (notCoveredArg >= 0) { 4945 assert((unsigned)notCoveredArg < NumDataArgs); 4946 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 4947 } else { 4948 UncoveredArg.setAllCovered(); 4949 } 4950 } 4951 } 4952 4953 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 4954 const Expr *ArgExpr) { 4955 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 4956 "Invalid state"); 4957 4958 if (!ArgExpr) 4959 return; 4960 4961 SourceLocation Loc = ArgExpr->getLocStart(); 4962 4963 if (S.getSourceManager().isInSystemMacro(Loc)) 4964 return; 4965 4966 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 4967 for (auto E : DiagnosticExprs) 4968 PDiag << E->getSourceRange(); 4969 4970 CheckFormatHandler::EmitFormatDiagnostic( 4971 S, IsFunctionCall, DiagnosticExprs[0], 4972 PDiag, Loc, /*IsStringLocation*/false, 4973 DiagnosticExprs[0]->getSourceRange()); 4974 } 4975 4976 bool 4977 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 4978 SourceLocation Loc, 4979 const char *startSpec, 4980 unsigned specifierLen, 4981 const char *csStart, 4982 unsigned csLen) { 4983 bool keepGoing = true; 4984 if (argIndex < NumDataArgs) { 4985 // Consider the argument coverered, even though the specifier doesn't 4986 // make sense. 4987 CoveredArgs.set(argIndex); 4988 } 4989 else { 4990 // If argIndex exceeds the number of data arguments we 4991 // don't issue a warning because that is just a cascade of warnings (and 4992 // they may have intended '%%' anyway). We don't want to continue processing 4993 // the format string after this point, however, as we will like just get 4994 // gibberish when trying to match arguments. 4995 keepGoing = false; 4996 } 4997 4998 StringRef Specifier(csStart, csLen); 4999 5000 // If the specifier in non-printable, it could be the first byte of a UTF-8 5001 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5002 // hex value. 5003 std::string CodePointStr; 5004 if (!llvm::sys::locale::isPrint(*csStart)) { 5005 llvm::UTF32 CodePoint; 5006 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5007 const llvm::UTF8 *E = 5008 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5009 llvm::ConversionResult Result = 5010 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5011 5012 if (Result != llvm::conversionOK) { 5013 unsigned char FirstChar = *csStart; 5014 CodePoint = (llvm::UTF32)FirstChar; 5015 } 5016 5017 llvm::raw_string_ostream OS(CodePointStr); 5018 if (CodePoint < 256) 5019 OS << "\\x" << llvm::format("%02x", CodePoint); 5020 else if (CodePoint <= 0xFFFF) 5021 OS << "\\u" << llvm::format("%04x", CodePoint); 5022 else 5023 OS << "\\U" << llvm::format("%08x", CodePoint); 5024 OS.flush(); 5025 Specifier = CodePointStr; 5026 } 5027 5028 EmitFormatDiagnostic( 5029 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5030 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5031 5032 return keepGoing; 5033 } 5034 5035 void 5036 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5037 const char *startSpec, 5038 unsigned specifierLen) { 5039 EmitFormatDiagnostic( 5040 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5041 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5042 } 5043 5044 bool 5045 CheckFormatHandler::CheckNumArgs( 5046 const analyze_format_string::FormatSpecifier &FS, 5047 const analyze_format_string::ConversionSpecifier &CS, 5048 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5049 5050 if (argIndex >= NumDataArgs) { 5051 PartialDiagnostic PDiag = FS.usesPositionalArg() 5052 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5053 << (argIndex+1) << NumDataArgs) 5054 : S.PDiag(diag::warn_printf_insufficient_data_args); 5055 EmitFormatDiagnostic( 5056 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5057 getSpecifierRange(startSpecifier, specifierLen)); 5058 5059 // Since more arguments than conversion tokens are given, by extension 5060 // all arguments are covered, so mark this as so. 5061 UncoveredArg.setAllCovered(); 5062 return false; 5063 } 5064 return true; 5065 } 5066 5067 template<typename Range> 5068 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5069 SourceLocation Loc, 5070 bool IsStringLocation, 5071 Range StringRange, 5072 ArrayRef<FixItHint> FixIt) { 5073 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5074 Loc, IsStringLocation, StringRange, FixIt); 5075 } 5076 5077 /// \brief If the format string is not within the funcion call, emit a note 5078 /// so that the function call and string are in diagnostic messages. 5079 /// 5080 /// \param InFunctionCall if true, the format string is within the function 5081 /// call and only one diagnostic message will be produced. Otherwise, an 5082 /// extra note will be emitted pointing to location of the format string. 5083 /// 5084 /// \param ArgumentExpr the expression that is passed as the format string 5085 /// argument in the function call. Used for getting locations when two 5086 /// diagnostics are emitted. 5087 /// 5088 /// \param PDiag the callee should already have provided any strings for the 5089 /// diagnostic message. This function only adds locations and fixits 5090 /// to diagnostics. 5091 /// 5092 /// \param Loc primary location for diagnostic. If two diagnostics are 5093 /// required, one will be at Loc and a new SourceLocation will be created for 5094 /// the other one. 5095 /// 5096 /// \param IsStringLocation if true, Loc points to the format string should be 5097 /// used for the note. Otherwise, Loc points to the argument list and will 5098 /// be used with PDiag. 5099 /// 5100 /// \param StringRange some or all of the string to highlight. This is 5101 /// templated so it can accept either a CharSourceRange or a SourceRange. 5102 /// 5103 /// \param FixIt optional fix it hint for the format string. 5104 template <typename Range> 5105 void CheckFormatHandler::EmitFormatDiagnostic( 5106 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5107 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5108 Range StringRange, ArrayRef<FixItHint> FixIt) { 5109 if (InFunctionCall) { 5110 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5111 D << StringRange; 5112 D << FixIt; 5113 } else { 5114 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5115 << ArgumentExpr->getSourceRange(); 5116 5117 const Sema::SemaDiagnosticBuilder &Note = 5118 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5119 diag::note_format_string_defined); 5120 5121 Note << StringRange; 5122 Note << FixIt; 5123 } 5124 } 5125 5126 //===--- CHECK: Printf format string checking ------------------------------===// 5127 5128 namespace { 5129 class CheckPrintfHandler : public CheckFormatHandler { 5130 bool ObjCContext; 5131 5132 public: 5133 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5134 const Expr *origFormatExpr, unsigned firstDataArg, 5135 unsigned numDataArgs, bool isObjC, 5136 const char *beg, bool hasVAListArg, 5137 ArrayRef<const Expr *> Args, 5138 unsigned formatIdx, bool inFunctionCall, 5139 Sema::VariadicCallType CallType, 5140 llvm::SmallBitVector &CheckedVarArgs, 5141 UncoveredArgHandler &UncoveredArg) 5142 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 5143 numDataArgs, beg, hasVAListArg, Args, 5144 formatIdx, inFunctionCall, CallType, CheckedVarArgs, 5145 UncoveredArg), 5146 ObjCContext(isObjC) 5147 {} 5148 5149 bool HandleInvalidPrintfConversionSpecifier( 5150 const analyze_printf::PrintfSpecifier &FS, 5151 const char *startSpecifier, 5152 unsigned specifierLen) override; 5153 5154 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5155 const char *startSpecifier, 5156 unsigned specifierLen) override; 5157 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5158 const char *StartSpecifier, 5159 unsigned SpecifierLen, 5160 const Expr *E); 5161 5162 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5163 const char *startSpecifier, unsigned specifierLen); 5164 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5165 const analyze_printf::OptionalAmount &Amt, 5166 unsigned type, 5167 const char *startSpecifier, unsigned specifierLen); 5168 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5169 const analyze_printf::OptionalFlag &flag, 5170 const char *startSpecifier, unsigned specifierLen); 5171 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5172 const analyze_printf::OptionalFlag &ignoredFlag, 5173 const analyze_printf::OptionalFlag &flag, 5174 const char *startSpecifier, unsigned specifierLen); 5175 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5176 const Expr *E); 5177 5178 void HandleEmptyObjCModifierFlag(const char *startFlag, 5179 unsigned flagLen) override; 5180 5181 void HandleInvalidObjCModifierFlag(const char *startFlag, 5182 unsigned flagLen) override; 5183 5184 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5185 const char *flagsEnd, 5186 const char *conversionPosition) 5187 override; 5188 }; 5189 } // end anonymous namespace 5190 5191 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5192 const analyze_printf::PrintfSpecifier &FS, 5193 const char *startSpecifier, 5194 unsigned specifierLen) { 5195 const analyze_printf::PrintfConversionSpecifier &CS = 5196 FS.getConversionSpecifier(); 5197 5198 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5199 getLocationOfByte(CS.getStart()), 5200 startSpecifier, specifierLen, 5201 CS.getStart(), CS.getLength()); 5202 } 5203 5204 bool CheckPrintfHandler::HandleAmount( 5205 const analyze_format_string::OptionalAmount &Amt, 5206 unsigned k, const char *startSpecifier, 5207 unsigned specifierLen) { 5208 if (Amt.hasDataArgument()) { 5209 if (!HasVAListArg) { 5210 unsigned argIndex = Amt.getArgIndex(); 5211 if (argIndex >= NumDataArgs) { 5212 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5213 << k, 5214 getLocationOfByte(Amt.getStart()), 5215 /*IsStringLocation*/true, 5216 getSpecifierRange(startSpecifier, specifierLen)); 5217 // Don't do any more checking. We will just emit 5218 // spurious errors. 5219 return false; 5220 } 5221 5222 // Type check the data argument. It should be an 'int'. 5223 // Although not in conformance with C99, we also allow the argument to be 5224 // an 'unsigned int' as that is a reasonably safe case. GCC also 5225 // doesn't emit a warning for that case. 5226 CoveredArgs.set(argIndex); 5227 const Expr *Arg = getDataArg(argIndex); 5228 if (!Arg) 5229 return false; 5230 5231 QualType T = Arg->getType(); 5232 5233 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5234 assert(AT.isValid()); 5235 5236 if (!AT.matchesType(S.Context, T)) { 5237 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5238 << k << AT.getRepresentativeTypeName(S.Context) 5239 << T << Arg->getSourceRange(), 5240 getLocationOfByte(Amt.getStart()), 5241 /*IsStringLocation*/true, 5242 getSpecifierRange(startSpecifier, specifierLen)); 5243 // Don't do any more checking. We will just emit 5244 // spurious errors. 5245 return false; 5246 } 5247 } 5248 } 5249 return true; 5250 } 5251 5252 void CheckPrintfHandler::HandleInvalidAmount( 5253 const analyze_printf::PrintfSpecifier &FS, 5254 const analyze_printf::OptionalAmount &Amt, 5255 unsigned type, 5256 const char *startSpecifier, 5257 unsigned specifierLen) { 5258 const analyze_printf::PrintfConversionSpecifier &CS = 5259 FS.getConversionSpecifier(); 5260 5261 FixItHint fixit = 5262 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5263 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5264 Amt.getConstantLength())) 5265 : FixItHint(); 5266 5267 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5268 << type << CS.toString(), 5269 getLocationOfByte(Amt.getStart()), 5270 /*IsStringLocation*/true, 5271 getSpecifierRange(startSpecifier, specifierLen), 5272 fixit); 5273 } 5274 5275 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5276 const analyze_printf::OptionalFlag &flag, 5277 const char *startSpecifier, 5278 unsigned specifierLen) { 5279 // Warn about pointless flag with a fixit removal. 5280 const analyze_printf::PrintfConversionSpecifier &CS = 5281 FS.getConversionSpecifier(); 5282 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5283 << flag.toString() << CS.toString(), 5284 getLocationOfByte(flag.getPosition()), 5285 /*IsStringLocation*/true, 5286 getSpecifierRange(startSpecifier, specifierLen), 5287 FixItHint::CreateRemoval( 5288 getSpecifierRange(flag.getPosition(), 1))); 5289 } 5290 5291 void CheckPrintfHandler::HandleIgnoredFlag( 5292 const analyze_printf::PrintfSpecifier &FS, 5293 const analyze_printf::OptionalFlag &ignoredFlag, 5294 const analyze_printf::OptionalFlag &flag, 5295 const char *startSpecifier, 5296 unsigned specifierLen) { 5297 // Warn about ignored flag with a fixit removal. 5298 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5299 << ignoredFlag.toString() << flag.toString(), 5300 getLocationOfByte(ignoredFlag.getPosition()), 5301 /*IsStringLocation*/true, 5302 getSpecifierRange(startSpecifier, specifierLen), 5303 FixItHint::CreateRemoval( 5304 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5305 } 5306 5307 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5308 // bool IsStringLocation, Range StringRange, 5309 // ArrayRef<FixItHint> Fixit = None); 5310 5311 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5312 unsigned flagLen) { 5313 // Warn about an empty flag. 5314 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5315 getLocationOfByte(startFlag), 5316 /*IsStringLocation*/true, 5317 getSpecifierRange(startFlag, flagLen)); 5318 } 5319 5320 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5321 unsigned flagLen) { 5322 // Warn about an invalid flag. 5323 auto Range = getSpecifierRange(startFlag, flagLen); 5324 StringRef flag(startFlag, flagLen); 5325 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5326 getLocationOfByte(startFlag), 5327 /*IsStringLocation*/true, 5328 Range, FixItHint::CreateRemoval(Range)); 5329 } 5330 5331 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5332 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5333 // Warn about using '[...]' without a '@' conversion. 5334 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5335 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5336 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5337 getLocationOfByte(conversionPosition), 5338 /*IsStringLocation*/true, 5339 Range, FixItHint::CreateRemoval(Range)); 5340 } 5341 5342 // Determines if the specified is a C++ class or struct containing 5343 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5344 // "c_str()"). 5345 template<typename MemberKind> 5346 static llvm::SmallPtrSet<MemberKind*, 1> 5347 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5348 const RecordType *RT = Ty->getAs<RecordType>(); 5349 llvm::SmallPtrSet<MemberKind*, 1> Results; 5350 5351 if (!RT) 5352 return Results; 5353 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5354 if (!RD || !RD->getDefinition()) 5355 return Results; 5356 5357 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5358 Sema::LookupMemberName); 5359 R.suppressDiagnostics(); 5360 5361 // We just need to include all members of the right kind turned up by the 5362 // filter, at this point. 5363 if (S.LookupQualifiedName(R, RT->getDecl())) 5364 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5365 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5366 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5367 Results.insert(FK); 5368 } 5369 return Results; 5370 } 5371 5372 /// Check if we could call '.c_str()' on an object. 5373 /// 5374 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5375 /// allow the call, or if it would be ambiguous). 5376 bool Sema::hasCStrMethod(const Expr *E) { 5377 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5378 MethodSet Results = 5379 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5380 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5381 MI != ME; ++MI) 5382 if ((*MI)->getMinRequiredArguments() == 0) 5383 return true; 5384 return false; 5385 } 5386 5387 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5388 // better diagnostic if so. AT is assumed to be valid. 5389 // Returns true when a c_str() conversion method is found. 5390 bool CheckPrintfHandler::checkForCStrMembers( 5391 const analyze_printf::ArgType &AT, const Expr *E) { 5392 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5393 5394 MethodSet Results = 5395 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5396 5397 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5398 MI != ME; ++MI) { 5399 const CXXMethodDecl *Method = *MI; 5400 if (Method->getMinRequiredArguments() == 0 && 5401 AT.matchesType(S.Context, Method->getReturnType())) { 5402 // FIXME: Suggest parens if the expression needs them. 5403 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5404 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5405 << "c_str()" 5406 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5407 return true; 5408 } 5409 } 5410 5411 return false; 5412 } 5413 5414 bool 5415 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5416 &FS, 5417 const char *startSpecifier, 5418 unsigned specifierLen) { 5419 using namespace analyze_format_string; 5420 using namespace analyze_printf; 5421 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5422 5423 if (FS.consumesDataArgument()) { 5424 if (atFirstArg) { 5425 atFirstArg = false; 5426 usesPositionalArgs = FS.usesPositionalArg(); 5427 } 5428 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5429 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5430 startSpecifier, specifierLen); 5431 return false; 5432 } 5433 } 5434 5435 // First check if the field width, precision, and conversion specifier 5436 // have matching data arguments. 5437 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5438 startSpecifier, specifierLen)) { 5439 return false; 5440 } 5441 5442 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5443 startSpecifier, specifierLen)) { 5444 return false; 5445 } 5446 5447 if (!CS.consumesDataArgument()) { 5448 // FIXME: Technically specifying a precision or field width here 5449 // makes no sense. Worth issuing a warning at some point. 5450 return true; 5451 } 5452 5453 // Consume the argument. 5454 unsigned argIndex = FS.getArgIndex(); 5455 if (argIndex < NumDataArgs) { 5456 // The check to see if the argIndex is valid will come later. 5457 // We set the bit here because we may exit early from this 5458 // function if we encounter some other error. 5459 CoveredArgs.set(argIndex); 5460 } 5461 5462 // FreeBSD kernel extensions. 5463 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5464 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5465 // We need at least two arguments. 5466 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5467 return false; 5468 5469 // Claim the second argument. 5470 CoveredArgs.set(argIndex + 1); 5471 5472 // Type check the first argument (int for %b, pointer for %D) 5473 const Expr *Ex = getDataArg(argIndex); 5474 const analyze_printf::ArgType &AT = 5475 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5476 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5477 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5478 EmitFormatDiagnostic( 5479 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5480 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5481 << false << Ex->getSourceRange(), 5482 Ex->getLocStart(), /*IsStringLocation*/false, 5483 getSpecifierRange(startSpecifier, specifierLen)); 5484 5485 // Type check the second argument (char * for both %b and %D) 5486 Ex = getDataArg(argIndex + 1); 5487 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5488 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5489 EmitFormatDiagnostic( 5490 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5491 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5492 << false << Ex->getSourceRange(), 5493 Ex->getLocStart(), /*IsStringLocation*/false, 5494 getSpecifierRange(startSpecifier, specifierLen)); 5495 5496 return true; 5497 } 5498 5499 // Check for using an Objective-C specific conversion specifier 5500 // in a non-ObjC literal. 5501 if (!ObjCContext && CS.isObjCArg()) { 5502 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5503 specifierLen); 5504 } 5505 5506 // Check for invalid use of field width 5507 if (!FS.hasValidFieldWidth()) { 5508 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 5509 startSpecifier, specifierLen); 5510 } 5511 5512 // Check for invalid use of precision 5513 if (!FS.hasValidPrecision()) { 5514 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 5515 startSpecifier, specifierLen); 5516 } 5517 5518 // Check each flag does not conflict with any other component. 5519 if (!FS.hasValidThousandsGroupingPrefix()) 5520 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 5521 if (!FS.hasValidLeadingZeros()) 5522 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 5523 if (!FS.hasValidPlusPrefix()) 5524 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 5525 if (!FS.hasValidSpacePrefix()) 5526 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 5527 if (!FS.hasValidAlternativeForm()) 5528 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 5529 if (!FS.hasValidLeftJustified()) 5530 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 5531 5532 // Check that flags are not ignored by another flag 5533 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 5534 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 5535 startSpecifier, specifierLen); 5536 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 5537 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 5538 startSpecifier, specifierLen); 5539 5540 // Check the length modifier is valid with the given conversion specifier. 5541 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5542 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5543 diag::warn_format_nonsensical_length); 5544 else if (!FS.hasStandardLengthModifier()) 5545 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5546 else if (!FS.hasStandardLengthConversionCombination()) 5547 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5548 diag::warn_format_non_standard_conversion_spec); 5549 5550 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5551 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5552 5553 // The remaining checks depend on the data arguments. 5554 if (HasVAListArg) 5555 return true; 5556 5557 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5558 return false; 5559 5560 const Expr *Arg = getDataArg(argIndex); 5561 if (!Arg) 5562 return true; 5563 5564 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 5565 } 5566 5567 static bool requiresParensToAddCast(const Expr *E) { 5568 // FIXME: We should have a general way to reason about operator 5569 // precedence and whether parens are actually needed here. 5570 // Take care of a few common cases where they aren't. 5571 const Expr *Inside = E->IgnoreImpCasts(); 5572 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 5573 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 5574 5575 switch (Inside->getStmtClass()) { 5576 case Stmt::ArraySubscriptExprClass: 5577 case Stmt::CallExprClass: 5578 case Stmt::CharacterLiteralClass: 5579 case Stmt::CXXBoolLiteralExprClass: 5580 case Stmt::DeclRefExprClass: 5581 case Stmt::FloatingLiteralClass: 5582 case Stmt::IntegerLiteralClass: 5583 case Stmt::MemberExprClass: 5584 case Stmt::ObjCArrayLiteralClass: 5585 case Stmt::ObjCBoolLiteralExprClass: 5586 case Stmt::ObjCBoxedExprClass: 5587 case Stmt::ObjCDictionaryLiteralClass: 5588 case Stmt::ObjCEncodeExprClass: 5589 case Stmt::ObjCIvarRefExprClass: 5590 case Stmt::ObjCMessageExprClass: 5591 case Stmt::ObjCPropertyRefExprClass: 5592 case Stmt::ObjCStringLiteralClass: 5593 case Stmt::ObjCSubscriptRefExprClass: 5594 case Stmt::ParenExprClass: 5595 case Stmt::StringLiteralClass: 5596 case Stmt::UnaryOperatorClass: 5597 return false; 5598 default: 5599 return true; 5600 } 5601 } 5602 5603 static std::pair<QualType, StringRef> 5604 shouldNotPrintDirectly(const ASTContext &Context, 5605 QualType IntendedTy, 5606 const Expr *E) { 5607 // Use a 'while' to peel off layers of typedefs. 5608 QualType TyTy = IntendedTy; 5609 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 5610 StringRef Name = UserTy->getDecl()->getName(); 5611 QualType CastTy = llvm::StringSwitch<QualType>(Name) 5612 .Case("NSInteger", Context.LongTy) 5613 .Case("NSUInteger", Context.UnsignedLongTy) 5614 .Case("SInt32", Context.IntTy) 5615 .Case("UInt32", Context.UnsignedIntTy) 5616 .Default(QualType()); 5617 5618 if (!CastTy.isNull()) 5619 return std::make_pair(CastTy, Name); 5620 5621 TyTy = UserTy->desugar(); 5622 } 5623 5624 // Strip parens if necessary. 5625 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 5626 return shouldNotPrintDirectly(Context, 5627 PE->getSubExpr()->getType(), 5628 PE->getSubExpr()); 5629 5630 // If this is a conditional expression, then its result type is constructed 5631 // via usual arithmetic conversions and thus there might be no necessary 5632 // typedef sugar there. Recurse to operands to check for NSInteger & 5633 // Co. usage condition. 5634 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 5635 QualType TrueTy, FalseTy; 5636 StringRef TrueName, FalseName; 5637 5638 std::tie(TrueTy, TrueName) = 5639 shouldNotPrintDirectly(Context, 5640 CO->getTrueExpr()->getType(), 5641 CO->getTrueExpr()); 5642 std::tie(FalseTy, FalseName) = 5643 shouldNotPrintDirectly(Context, 5644 CO->getFalseExpr()->getType(), 5645 CO->getFalseExpr()); 5646 5647 if (TrueTy == FalseTy) 5648 return std::make_pair(TrueTy, TrueName); 5649 else if (TrueTy.isNull()) 5650 return std::make_pair(FalseTy, FalseName); 5651 else if (FalseTy.isNull()) 5652 return std::make_pair(TrueTy, TrueName); 5653 } 5654 5655 return std::make_pair(QualType(), StringRef()); 5656 } 5657 5658 bool 5659 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5660 const char *StartSpecifier, 5661 unsigned SpecifierLen, 5662 const Expr *E) { 5663 using namespace analyze_format_string; 5664 using namespace analyze_printf; 5665 // Now type check the data expression that matches the 5666 // format specifier. 5667 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, 5668 ObjCContext); 5669 if (!AT.isValid()) 5670 return true; 5671 5672 QualType ExprTy = E->getType(); 5673 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 5674 ExprTy = TET->getUnderlyingExpr()->getType(); 5675 } 5676 5677 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 5678 5679 if (match == analyze_printf::ArgType::Match) { 5680 return true; 5681 } 5682 5683 // Look through argument promotions for our error message's reported type. 5684 // This includes the integral and floating promotions, but excludes array 5685 // and function pointer decay; seeing that an argument intended to be a 5686 // string has type 'char [6]' is probably more confusing than 'char *'. 5687 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5688 if (ICE->getCastKind() == CK_IntegralCast || 5689 ICE->getCastKind() == CK_FloatingCast) { 5690 E = ICE->getSubExpr(); 5691 ExprTy = E->getType(); 5692 5693 // Check if we didn't match because of an implicit cast from a 'char' 5694 // or 'short' to an 'int'. This is done because printf is a varargs 5695 // function. 5696 if (ICE->getType() == S.Context.IntTy || 5697 ICE->getType() == S.Context.UnsignedIntTy) { 5698 // All further checking is done on the subexpression. 5699 if (AT.matchesType(S.Context, ExprTy)) 5700 return true; 5701 } 5702 } 5703 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 5704 // Special case for 'a', which has type 'int' in C. 5705 // Note, however, that we do /not/ want to treat multibyte constants like 5706 // 'MooV' as characters! This form is deprecated but still exists. 5707 if (ExprTy == S.Context.IntTy) 5708 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 5709 ExprTy = S.Context.CharTy; 5710 } 5711 5712 // Look through enums to their underlying type. 5713 bool IsEnum = false; 5714 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 5715 ExprTy = EnumTy->getDecl()->getIntegerType(); 5716 IsEnum = true; 5717 } 5718 5719 // %C in an Objective-C context prints a unichar, not a wchar_t. 5720 // If the argument is an integer of some kind, believe the %C and suggest 5721 // a cast instead of changing the conversion specifier. 5722 QualType IntendedTy = ExprTy; 5723 if (ObjCContext && 5724 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 5725 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 5726 !ExprTy->isCharType()) { 5727 // 'unichar' is defined as a typedef of unsigned short, but we should 5728 // prefer using the typedef if it is visible. 5729 IntendedTy = S.Context.UnsignedShortTy; 5730 5731 // While we are here, check if the value is an IntegerLiteral that happens 5732 // to be within the valid range. 5733 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 5734 const llvm::APInt &V = IL->getValue(); 5735 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 5736 return true; 5737 } 5738 5739 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 5740 Sema::LookupOrdinaryName); 5741 if (S.LookupName(Result, S.getCurScope())) { 5742 NamedDecl *ND = Result.getFoundDecl(); 5743 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 5744 if (TD->getUnderlyingType() == IntendedTy) 5745 IntendedTy = S.Context.getTypedefType(TD); 5746 } 5747 } 5748 } 5749 5750 // Special-case some of Darwin's platform-independence types by suggesting 5751 // casts to primitive types that are known to be large enough. 5752 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 5753 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 5754 QualType CastTy; 5755 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 5756 if (!CastTy.isNull()) { 5757 IntendedTy = CastTy; 5758 ShouldNotPrintDirectly = true; 5759 } 5760 } 5761 5762 // We may be able to offer a FixItHint if it is a supported type. 5763 PrintfSpecifier fixedFS = FS; 5764 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(), 5765 S.Context, ObjCContext); 5766 5767 if (success) { 5768 // Get the fix string from the fixed format specifier 5769 SmallString<16> buf; 5770 llvm::raw_svector_ostream os(buf); 5771 fixedFS.toString(os); 5772 5773 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 5774 5775 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 5776 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5777 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 5778 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5779 } 5780 // In this case, the specifier is wrong and should be changed to match 5781 // the argument. 5782 EmitFormatDiagnostic(S.PDiag(diag) 5783 << AT.getRepresentativeTypeName(S.Context) 5784 << IntendedTy << IsEnum << E->getSourceRange(), 5785 E->getLocStart(), 5786 /*IsStringLocation*/ false, SpecRange, 5787 FixItHint::CreateReplacement(SpecRange, os.str())); 5788 } else { 5789 // The canonical type for formatting this value is different from the 5790 // actual type of the expression. (This occurs, for example, with Darwin's 5791 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 5792 // should be printed as 'long' for 64-bit compatibility.) 5793 // Rather than emitting a normal format/argument mismatch, we want to 5794 // add a cast to the recommended type (and correct the format string 5795 // if necessary). 5796 SmallString<16> CastBuf; 5797 llvm::raw_svector_ostream CastFix(CastBuf); 5798 CastFix << "("; 5799 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 5800 CastFix << ")"; 5801 5802 SmallVector<FixItHint,4> Hints; 5803 if (!AT.matchesType(S.Context, IntendedTy)) 5804 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 5805 5806 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 5807 // If there's already a cast present, just replace it. 5808 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 5809 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 5810 5811 } else if (!requiresParensToAddCast(E)) { 5812 // If the expression has high enough precedence, 5813 // just write the C-style cast. 5814 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 5815 CastFix.str())); 5816 } else { 5817 // Otherwise, add parens around the expression as well as the cast. 5818 CastFix << "("; 5819 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 5820 CastFix.str())); 5821 5822 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 5823 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 5824 } 5825 5826 if (ShouldNotPrintDirectly) { 5827 // The expression has a type that should not be printed directly. 5828 // We extract the name from the typedef because we don't want to show 5829 // the underlying type in the diagnostic. 5830 StringRef Name; 5831 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 5832 Name = TypedefTy->getDecl()->getName(); 5833 else 5834 Name = CastTyName; 5835 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 5836 << Name << IntendedTy << IsEnum 5837 << E->getSourceRange(), 5838 E->getLocStart(), /*IsStringLocation=*/false, 5839 SpecRange, Hints); 5840 } else { 5841 // In this case, the expression could be printed using a different 5842 // specifier, but we've decided that the specifier is probably correct 5843 // and we should cast instead. Just use the normal warning message. 5844 EmitFormatDiagnostic( 5845 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5846 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 5847 << E->getSourceRange(), 5848 E->getLocStart(), /*IsStringLocation*/false, 5849 SpecRange, Hints); 5850 } 5851 } 5852 } else { 5853 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 5854 SpecifierLen); 5855 // Since the warning for passing non-POD types to variadic functions 5856 // was deferred until now, we emit a warning for non-POD 5857 // arguments here. 5858 switch (S.isValidVarArgType(ExprTy)) { 5859 case Sema::VAK_Valid: 5860 case Sema::VAK_ValidInCXX11: { 5861 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5862 if (match == analyze_printf::ArgType::NoMatchPedantic) { 5863 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5864 } 5865 5866 EmitFormatDiagnostic( 5867 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 5868 << IsEnum << CSR << E->getSourceRange(), 5869 E->getLocStart(), /*IsStringLocation*/ false, CSR); 5870 break; 5871 } 5872 case Sema::VAK_Undefined: 5873 case Sema::VAK_MSVCUndefined: 5874 EmitFormatDiagnostic( 5875 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 5876 << S.getLangOpts().CPlusPlus11 5877 << ExprTy 5878 << CallType 5879 << AT.getRepresentativeTypeName(S.Context) 5880 << CSR 5881 << E->getSourceRange(), 5882 E->getLocStart(), /*IsStringLocation*/false, CSR); 5883 checkForCStrMembers(AT, E); 5884 break; 5885 5886 case Sema::VAK_Invalid: 5887 if (ExprTy->isObjCObjectType()) 5888 EmitFormatDiagnostic( 5889 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 5890 << S.getLangOpts().CPlusPlus11 5891 << ExprTy 5892 << CallType 5893 << AT.getRepresentativeTypeName(S.Context) 5894 << CSR 5895 << E->getSourceRange(), 5896 E->getLocStart(), /*IsStringLocation*/false, CSR); 5897 else 5898 // FIXME: If this is an initializer list, suggest removing the braces 5899 // or inserting a cast to the target type. 5900 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 5901 << isa<InitListExpr>(E) << ExprTy << CallType 5902 << AT.getRepresentativeTypeName(S.Context) 5903 << E->getSourceRange(); 5904 break; 5905 } 5906 5907 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 5908 "format string specifier index out of range"); 5909 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 5910 } 5911 5912 return true; 5913 } 5914 5915 //===--- CHECK: Scanf format string checking ------------------------------===// 5916 5917 namespace { 5918 class CheckScanfHandler : public CheckFormatHandler { 5919 public: 5920 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 5921 const Expr *origFormatExpr, unsigned firstDataArg, 5922 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5923 ArrayRef<const Expr *> Args, 5924 unsigned formatIdx, bool inFunctionCall, 5925 Sema::VariadicCallType CallType, 5926 llvm::SmallBitVector &CheckedVarArgs, 5927 UncoveredArgHandler &UncoveredArg) 5928 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 5929 numDataArgs, beg, hasVAListArg, 5930 Args, formatIdx, inFunctionCall, CallType, 5931 CheckedVarArgs, UncoveredArg) 5932 {} 5933 5934 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 5935 const char *startSpecifier, 5936 unsigned specifierLen) override; 5937 5938 bool HandleInvalidScanfConversionSpecifier( 5939 const analyze_scanf::ScanfSpecifier &FS, 5940 const char *startSpecifier, 5941 unsigned specifierLen) override; 5942 5943 void HandleIncompleteScanList(const char *start, const char *end) override; 5944 }; 5945 } // end anonymous namespace 5946 5947 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 5948 const char *end) { 5949 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 5950 getLocationOfByte(end), /*IsStringLocation*/true, 5951 getSpecifierRange(start, end - start)); 5952 } 5953 5954 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 5955 const analyze_scanf::ScanfSpecifier &FS, 5956 const char *startSpecifier, 5957 unsigned specifierLen) { 5958 5959 const analyze_scanf::ScanfConversionSpecifier &CS = 5960 FS.getConversionSpecifier(); 5961 5962 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5963 getLocationOfByte(CS.getStart()), 5964 startSpecifier, specifierLen, 5965 CS.getStart(), CS.getLength()); 5966 } 5967 5968 bool CheckScanfHandler::HandleScanfSpecifier( 5969 const analyze_scanf::ScanfSpecifier &FS, 5970 const char *startSpecifier, 5971 unsigned specifierLen) { 5972 using namespace analyze_scanf; 5973 using namespace analyze_format_string; 5974 5975 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 5976 5977 // Handle case where '%' and '*' don't consume an argument. These shouldn't 5978 // be used to decide if we are using positional arguments consistently. 5979 if (FS.consumesDataArgument()) { 5980 if (atFirstArg) { 5981 atFirstArg = false; 5982 usesPositionalArgs = FS.usesPositionalArg(); 5983 } 5984 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5985 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5986 startSpecifier, specifierLen); 5987 return false; 5988 } 5989 } 5990 5991 // Check if the field with is non-zero. 5992 const OptionalAmount &Amt = FS.getFieldWidth(); 5993 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 5994 if (Amt.getConstantAmount() == 0) { 5995 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 5996 Amt.getConstantLength()); 5997 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 5998 getLocationOfByte(Amt.getStart()), 5999 /*IsStringLocation*/true, R, 6000 FixItHint::CreateRemoval(R)); 6001 } 6002 } 6003 6004 if (!FS.consumesDataArgument()) { 6005 // FIXME: Technically specifying a precision or field width here 6006 // makes no sense. Worth issuing a warning at some point. 6007 return true; 6008 } 6009 6010 // Consume the argument. 6011 unsigned argIndex = FS.getArgIndex(); 6012 if (argIndex < NumDataArgs) { 6013 // The check to see if the argIndex is valid will come later. 6014 // We set the bit here because we may exit early from this 6015 // function if we encounter some other error. 6016 CoveredArgs.set(argIndex); 6017 } 6018 6019 // Check the length modifier is valid with the given conversion specifier. 6020 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6021 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6022 diag::warn_format_nonsensical_length); 6023 else if (!FS.hasStandardLengthModifier()) 6024 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6025 else if (!FS.hasStandardLengthConversionCombination()) 6026 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6027 diag::warn_format_non_standard_conversion_spec); 6028 6029 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6030 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6031 6032 // The remaining checks depend on the data arguments. 6033 if (HasVAListArg) 6034 return true; 6035 6036 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6037 return false; 6038 6039 // Check that the argument type matches the format specifier. 6040 const Expr *Ex = getDataArg(argIndex); 6041 if (!Ex) 6042 return true; 6043 6044 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6045 6046 if (!AT.isValid()) { 6047 return true; 6048 } 6049 6050 analyze_format_string::ArgType::MatchKind match = 6051 AT.matchesType(S.Context, Ex->getType()); 6052 if (match == analyze_format_string::ArgType::Match) { 6053 return true; 6054 } 6055 6056 ScanfSpecifier fixedFS = FS; 6057 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6058 S.getLangOpts(), S.Context); 6059 6060 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6061 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6062 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6063 } 6064 6065 if (success) { 6066 // Get the fix string from the fixed format specifier. 6067 SmallString<128> buf; 6068 llvm::raw_svector_ostream os(buf); 6069 fixedFS.toString(os); 6070 6071 EmitFormatDiagnostic( 6072 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6073 << Ex->getType() << false << Ex->getSourceRange(), 6074 Ex->getLocStart(), 6075 /*IsStringLocation*/ false, 6076 getSpecifierRange(startSpecifier, specifierLen), 6077 FixItHint::CreateReplacement( 6078 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6079 } else { 6080 EmitFormatDiagnostic(S.PDiag(diag) 6081 << AT.getRepresentativeTypeName(S.Context) 6082 << Ex->getType() << false << Ex->getSourceRange(), 6083 Ex->getLocStart(), 6084 /*IsStringLocation*/ false, 6085 getSpecifierRange(startSpecifier, specifierLen)); 6086 } 6087 6088 return true; 6089 } 6090 6091 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6092 const Expr *OrigFormatExpr, 6093 ArrayRef<const Expr *> Args, 6094 bool HasVAListArg, unsigned format_idx, 6095 unsigned firstDataArg, 6096 Sema::FormatStringType Type, 6097 bool inFunctionCall, 6098 Sema::VariadicCallType CallType, 6099 llvm::SmallBitVector &CheckedVarArgs, 6100 UncoveredArgHandler &UncoveredArg) { 6101 // CHECK: is the format string a wide literal? 6102 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6103 CheckFormatHandler::EmitFormatDiagnostic( 6104 S, inFunctionCall, Args[format_idx], 6105 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6106 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6107 return; 6108 } 6109 6110 // Str - The format string. NOTE: this is NOT null-terminated! 6111 StringRef StrRef = FExpr->getString(); 6112 const char *Str = StrRef.data(); 6113 // Account for cases where the string literal is truncated in a declaration. 6114 const ConstantArrayType *T = 6115 S.Context.getAsConstantArrayType(FExpr->getType()); 6116 assert(T && "String literal not of constant array type!"); 6117 size_t TypeSize = T->getSize().getZExtValue(); 6118 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6119 const unsigned numDataArgs = Args.size() - firstDataArg; 6120 6121 // Emit a warning if the string literal is truncated and does not contain an 6122 // embedded null character. 6123 if (TypeSize <= StrRef.size() && 6124 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6125 CheckFormatHandler::EmitFormatDiagnostic( 6126 S, inFunctionCall, Args[format_idx], 6127 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6128 FExpr->getLocStart(), 6129 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6130 return; 6131 } 6132 6133 // CHECK: empty format string? 6134 if (StrLen == 0 && numDataArgs > 0) { 6135 CheckFormatHandler::EmitFormatDiagnostic( 6136 S, inFunctionCall, Args[format_idx], 6137 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6138 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6139 return; 6140 } 6141 6142 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6143 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) { 6144 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, 6145 numDataArgs, (Type == Sema::FST_NSString || 6146 Type == Sema::FST_OSTrace), 6147 Str, HasVAListArg, Args, format_idx, 6148 inFunctionCall, CallType, CheckedVarArgs, 6149 UncoveredArg); 6150 6151 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6152 S.getLangOpts(), 6153 S.Context.getTargetInfo(), 6154 Type == Sema::FST_FreeBSDKPrintf)) 6155 H.DoneProcessing(); 6156 } else if (Type == Sema::FST_Scanf) { 6157 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 6158 Str, HasVAListArg, Args, format_idx, 6159 inFunctionCall, CallType, CheckedVarArgs, 6160 UncoveredArg); 6161 6162 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6163 S.getLangOpts(), 6164 S.Context.getTargetInfo())) 6165 H.DoneProcessing(); 6166 } // TODO: handle other formats 6167 } 6168 6169 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6170 // Str - The format string. NOTE: this is NOT null-terminated! 6171 StringRef StrRef = FExpr->getString(); 6172 const char *Str = StrRef.data(); 6173 // Account for cases where the string literal is truncated in a declaration. 6174 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6175 assert(T && "String literal not of constant array type!"); 6176 size_t TypeSize = T->getSize().getZExtValue(); 6177 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6178 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6179 getLangOpts(), 6180 Context.getTargetInfo()); 6181 } 6182 6183 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6184 6185 // Returns the related absolute value function that is larger, of 0 if one 6186 // does not exist. 6187 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6188 switch (AbsFunction) { 6189 default: 6190 return 0; 6191 6192 case Builtin::BI__builtin_abs: 6193 return Builtin::BI__builtin_labs; 6194 case Builtin::BI__builtin_labs: 6195 return Builtin::BI__builtin_llabs; 6196 case Builtin::BI__builtin_llabs: 6197 return 0; 6198 6199 case Builtin::BI__builtin_fabsf: 6200 return Builtin::BI__builtin_fabs; 6201 case Builtin::BI__builtin_fabs: 6202 return Builtin::BI__builtin_fabsl; 6203 case Builtin::BI__builtin_fabsl: 6204 return 0; 6205 6206 case Builtin::BI__builtin_cabsf: 6207 return Builtin::BI__builtin_cabs; 6208 case Builtin::BI__builtin_cabs: 6209 return Builtin::BI__builtin_cabsl; 6210 case Builtin::BI__builtin_cabsl: 6211 return 0; 6212 6213 case Builtin::BIabs: 6214 return Builtin::BIlabs; 6215 case Builtin::BIlabs: 6216 return Builtin::BIllabs; 6217 case Builtin::BIllabs: 6218 return 0; 6219 6220 case Builtin::BIfabsf: 6221 return Builtin::BIfabs; 6222 case Builtin::BIfabs: 6223 return Builtin::BIfabsl; 6224 case Builtin::BIfabsl: 6225 return 0; 6226 6227 case Builtin::BIcabsf: 6228 return Builtin::BIcabs; 6229 case Builtin::BIcabs: 6230 return Builtin::BIcabsl; 6231 case Builtin::BIcabsl: 6232 return 0; 6233 } 6234 } 6235 6236 // Returns the argument type of the absolute value function. 6237 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6238 unsigned AbsType) { 6239 if (AbsType == 0) 6240 return QualType(); 6241 6242 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6243 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6244 if (Error != ASTContext::GE_None) 6245 return QualType(); 6246 6247 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6248 if (!FT) 6249 return QualType(); 6250 6251 if (FT->getNumParams() != 1) 6252 return QualType(); 6253 6254 return FT->getParamType(0); 6255 } 6256 6257 // Returns the best absolute value function, or zero, based on type and 6258 // current absolute value function. 6259 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6260 unsigned AbsFunctionKind) { 6261 unsigned BestKind = 0; 6262 uint64_t ArgSize = Context.getTypeSize(ArgType); 6263 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6264 Kind = getLargerAbsoluteValueFunction(Kind)) { 6265 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6266 if (Context.getTypeSize(ParamType) >= ArgSize) { 6267 if (BestKind == 0) 6268 BestKind = Kind; 6269 else if (Context.hasSameType(ParamType, ArgType)) { 6270 BestKind = Kind; 6271 break; 6272 } 6273 } 6274 } 6275 return BestKind; 6276 } 6277 6278 enum AbsoluteValueKind { 6279 AVK_Integer, 6280 AVK_Floating, 6281 AVK_Complex 6282 }; 6283 6284 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6285 if (T->isIntegralOrEnumerationType()) 6286 return AVK_Integer; 6287 if (T->isRealFloatingType()) 6288 return AVK_Floating; 6289 if (T->isAnyComplexType()) 6290 return AVK_Complex; 6291 6292 llvm_unreachable("Type not integer, floating, or complex"); 6293 } 6294 6295 // Changes the absolute value function to a different type. Preserves whether 6296 // the function is a builtin. 6297 static unsigned changeAbsFunction(unsigned AbsKind, 6298 AbsoluteValueKind ValueKind) { 6299 switch (ValueKind) { 6300 case AVK_Integer: 6301 switch (AbsKind) { 6302 default: 6303 return 0; 6304 case Builtin::BI__builtin_fabsf: 6305 case Builtin::BI__builtin_fabs: 6306 case Builtin::BI__builtin_fabsl: 6307 case Builtin::BI__builtin_cabsf: 6308 case Builtin::BI__builtin_cabs: 6309 case Builtin::BI__builtin_cabsl: 6310 return Builtin::BI__builtin_abs; 6311 case Builtin::BIfabsf: 6312 case Builtin::BIfabs: 6313 case Builtin::BIfabsl: 6314 case Builtin::BIcabsf: 6315 case Builtin::BIcabs: 6316 case Builtin::BIcabsl: 6317 return Builtin::BIabs; 6318 } 6319 case AVK_Floating: 6320 switch (AbsKind) { 6321 default: 6322 return 0; 6323 case Builtin::BI__builtin_abs: 6324 case Builtin::BI__builtin_labs: 6325 case Builtin::BI__builtin_llabs: 6326 case Builtin::BI__builtin_cabsf: 6327 case Builtin::BI__builtin_cabs: 6328 case Builtin::BI__builtin_cabsl: 6329 return Builtin::BI__builtin_fabsf; 6330 case Builtin::BIabs: 6331 case Builtin::BIlabs: 6332 case Builtin::BIllabs: 6333 case Builtin::BIcabsf: 6334 case Builtin::BIcabs: 6335 case Builtin::BIcabsl: 6336 return Builtin::BIfabsf; 6337 } 6338 case AVK_Complex: 6339 switch (AbsKind) { 6340 default: 6341 return 0; 6342 case Builtin::BI__builtin_abs: 6343 case Builtin::BI__builtin_labs: 6344 case Builtin::BI__builtin_llabs: 6345 case Builtin::BI__builtin_fabsf: 6346 case Builtin::BI__builtin_fabs: 6347 case Builtin::BI__builtin_fabsl: 6348 return Builtin::BI__builtin_cabsf; 6349 case Builtin::BIabs: 6350 case Builtin::BIlabs: 6351 case Builtin::BIllabs: 6352 case Builtin::BIfabsf: 6353 case Builtin::BIfabs: 6354 case Builtin::BIfabsl: 6355 return Builtin::BIcabsf; 6356 } 6357 } 6358 llvm_unreachable("Unable to convert function"); 6359 } 6360 6361 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6362 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6363 if (!FnInfo) 6364 return 0; 6365 6366 switch (FDecl->getBuiltinID()) { 6367 default: 6368 return 0; 6369 case Builtin::BI__builtin_abs: 6370 case Builtin::BI__builtin_fabs: 6371 case Builtin::BI__builtin_fabsf: 6372 case Builtin::BI__builtin_fabsl: 6373 case Builtin::BI__builtin_labs: 6374 case Builtin::BI__builtin_llabs: 6375 case Builtin::BI__builtin_cabs: 6376 case Builtin::BI__builtin_cabsf: 6377 case Builtin::BI__builtin_cabsl: 6378 case Builtin::BIabs: 6379 case Builtin::BIlabs: 6380 case Builtin::BIllabs: 6381 case Builtin::BIfabs: 6382 case Builtin::BIfabsf: 6383 case Builtin::BIfabsl: 6384 case Builtin::BIcabs: 6385 case Builtin::BIcabsf: 6386 case Builtin::BIcabsl: 6387 return FDecl->getBuiltinID(); 6388 } 6389 llvm_unreachable("Unknown Builtin type"); 6390 } 6391 6392 // If the replacement is valid, emit a note with replacement function. 6393 // Additionally, suggest including the proper header if not already included. 6394 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6395 unsigned AbsKind, QualType ArgType) { 6396 bool EmitHeaderHint = true; 6397 const char *HeaderName = nullptr; 6398 const char *FunctionName = nullptr; 6399 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6400 FunctionName = "std::abs"; 6401 if (ArgType->isIntegralOrEnumerationType()) { 6402 HeaderName = "cstdlib"; 6403 } else if (ArgType->isRealFloatingType()) { 6404 HeaderName = "cmath"; 6405 } else { 6406 llvm_unreachable("Invalid Type"); 6407 } 6408 6409 // Lookup all std::abs 6410 if (NamespaceDecl *Std = S.getStdNamespace()) { 6411 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6412 R.suppressDiagnostics(); 6413 S.LookupQualifiedName(R, Std); 6414 6415 for (const auto *I : R) { 6416 const FunctionDecl *FDecl = nullptr; 6417 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6418 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6419 } else { 6420 FDecl = dyn_cast<FunctionDecl>(I); 6421 } 6422 if (!FDecl) 6423 continue; 6424 6425 // Found std::abs(), check that they are the right ones. 6426 if (FDecl->getNumParams() != 1) 6427 continue; 6428 6429 // Check that the parameter type can handle the argument. 6430 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6431 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6432 S.Context.getTypeSize(ArgType) <= 6433 S.Context.getTypeSize(ParamType)) { 6434 // Found a function, don't need the header hint. 6435 EmitHeaderHint = false; 6436 break; 6437 } 6438 } 6439 } 6440 } else { 6441 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6442 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6443 6444 if (HeaderName) { 6445 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6446 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6447 R.suppressDiagnostics(); 6448 S.LookupName(R, S.getCurScope()); 6449 6450 if (R.isSingleResult()) { 6451 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6452 if (FD && FD->getBuiltinID() == AbsKind) { 6453 EmitHeaderHint = false; 6454 } else { 6455 return; 6456 } 6457 } else if (!R.empty()) { 6458 return; 6459 } 6460 } 6461 } 6462 6463 S.Diag(Loc, diag::note_replace_abs_function) 6464 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 6465 6466 if (!HeaderName) 6467 return; 6468 6469 if (!EmitHeaderHint) 6470 return; 6471 6472 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 6473 << FunctionName; 6474 } 6475 6476 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) { 6477 if (!FDecl) 6478 return false; 6479 6480 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs")) 6481 return false; 6482 6483 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext()); 6484 6485 while (ND && ND->isInlineNamespace()) { 6486 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext()); 6487 } 6488 6489 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std")) 6490 return false; 6491 6492 if (!isa<TranslationUnitDecl>(ND->getDeclContext())) 6493 return false; 6494 6495 return true; 6496 } 6497 6498 // Warn when using the wrong abs() function. 6499 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 6500 const FunctionDecl *FDecl, 6501 IdentifierInfo *FnInfo) { 6502 if (Call->getNumArgs() != 1) 6503 return; 6504 6505 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 6506 bool IsStdAbs = IsFunctionStdAbs(FDecl); 6507 if (AbsKind == 0 && !IsStdAbs) 6508 return; 6509 6510 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6511 QualType ParamType = Call->getArg(0)->getType(); 6512 6513 // Unsigned types cannot be negative. Suggest removing the absolute value 6514 // function call. 6515 if (ArgType->isUnsignedIntegerType()) { 6516 const char *FunctionName = 6517 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 6518 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 6519 Diag(Call->getExprLoc(), diag::note_remove_abs) 6520 << FunctionName 6521 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 6522 return; 6523 } 6524 6525 // Taking the absolute value of a pointer is very suspicious, they probably 6526 // wanted to index into an array, dereference a pointer, call a function, etc. 6527 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 6528 unsigned DiagType = 0; 6529 if (ArgType->isFunctionType()) 6530 DiagType = 1; 6531 else if (ArgType->isArrayType()) 6532 DiagType = 2; 6533 6534 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 6535 return; 6536 } 6537 6538 // std::abs has overloads which prevent most of the absolute value problems 6539 // from occurring. 6540 if (IsStdAbs) 6541 return; 6542 6543 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 6544 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 6545 6546 // The argument and parameter are the same kind. Check if they are the right 6547 // size. 6548 if (ArgValueKind == ParamValueKind) { 6549 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 6550 return; 6551 6552 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 6553 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 6554 << FDecl << ArgType << ParamType; 6555 6556 if (NewAbsKind == 0) 6557 return; 6558 6559 emitReplacement(*this, Call->getExprLoc(), 6560 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6561 return; 6562 } 6563 6564 // ArgValueKind != ParamValueKind 6565 // The wrong type of absolute value function was used. Attempt to find the 6566 // proper one. 6567 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 6568 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 6569 if (NewAbsKind == 0) 6570 return; 6571 6572 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 6573 << FDecl << ParamValueKind << ArgValueKind; 6574 6575 emitReplacement(*this, Call->getExprLoc(), 6576 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6577 } 6578 6579 //===--- CHECK: Standard memory functions ---------------------------------===// 6580 6581 /// \brief Takes the expression passed to the size_t parameter of functions 6582 /// such as memcmp, strncat, etc and warns if it's a comparison. 6583 /// 6584 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 6585 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 6586 IdentifierInfo *FnName, 6587 SourceLocation FnLoc, 6588 SourceLocation RParenLoc) { 6589 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 6590 if (!Size) 6591 return false; 6592 6593 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 6594 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 6595 return false; 6596 6597 SourceRange SizeRange = Size->getSourceRange(); 6598 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 6599 << SizeRange << FnName; 6600 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 6601 << FnName << FixItHint::CreateInsertion( 6602 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 6603 << FixItHint::CreateRemoval(RParenLoc); 6604 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 6605 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 6606 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 6607 ")"); 6608 6609 return true; 6610 } 6611 6612 /// \brief Determine whether the given type is or contains a dynamic class type 6613 /// (e.g., whether it has a vtable). 6614 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 6615 bool &IsContained) { 6616 // Look through array types while ignoring qualifiers. 6617 const Type *Ty = T->getBaseElementTypeUnsafe(); 6618 IsContained = false; 6619 6620 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 6621 RD = RD ? RD->getDefinition() : nullptr; 6622 if (!RD || RD->isInvalidDecl()) 6623 return nullptr; 6624 6625 if (RD->isDynamicClass()) 6626 return RD; 6627 6628 // Check all the fields. If any bases were dynamic, the class is dynamic. 6629 // It's impossible for a class to transitively contain itself by value, so 6630 // infinite recursion is impossible. 6631 for (auto *FD : RD->fields()) { 6632 bool SubContained; 6633 if (const CXXRecordDecl *ContainedRD = 6634 getContainedDynamicClass(FD->getType(), SubContained)) { 6635 IsContained = true; 6636 return ContainedRD; 6637 } 6638 } 6639 6640 return nullptr; 6641 } 6642 6643 /// \brief If E is a sizeof expression, returns its argument expression, 6644 /// otherwise returns NULL. 6645 static const Expr *getSizeOfExprArg(const Expr *E) { 6646 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6647 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6648 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 6649 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 6650 6651 return nullptr; 6652 } 6653 6654 /// \brief If E is a sizeof expression, returns its argument type. 6655 static QualType getSizeOfArgType(const Expr *E) { 6656 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6657 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6658 if (SizeOf->getKind() == clang::UETT_SizeOf) 6659 return SizeOf->getTypeOfArgument(); 6660 6661 return QualType(); 6662 } 6663 6664 /// \brief Check for dangerous or invalid arguments to memset(). 6665 /// 6666 /// This issues warnings on known problematic, dangerous or unspecified 6667 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 6668 /// function calls. 6669 /// 6670 /// \param Call The call expression to diagnose. 6671 void Sema::CheckMemaccessArguments(const CallExpr *Call, 6672 unsigned BId, 6673 IdentifierInfo *FnName) { 6674 assert(BId != 0); 6675 6676 // It is possible to have a non-standard definition of memset. Validate 6677 // we have enough arguments, and if not, abort further checking. 6678 unsigned ExpectedNumArgs = 6679 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 6680 if (Call->getNumArgs() < ExpectedNumArgs) 6681 return; 6682 6683 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 6684 BId == Builtin::BIstrndup ? 1 : 2); 6685 unsigned LenArg = 6686 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 6687 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 6688 6689 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 6690 Call->getLocStart(), Call->getRParenLoc())) 6691 return; 6692 6693 // We have special checking when the length is a sizeof expression. 6694 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 6695 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 6696 llvm::FoldingSetNodeID SizeOfArgID; 6697 6698 // Although widely used, 'bzero' is not a standard function. Be more strict 6699 // with the argument types before allowing diagnostics and only allow the 6700 // form bzero(ptr, sizeof(...)). 6701 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6702 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 6703 return; 6704 6705 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 6706 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 6707 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 6708 6709 QualType DestTy = Dest->getType(); 6710 QualType PointeeTy; 6711 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 6712 PointeeTy = DestPtrTy->getPointeeType(); 6713 6714 // Never warn about void type pointers. This can be used to suppress 6715 // false positives. 6716 if (PointeeTy->isVoidType()) 6717 continue; 6718 6719 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 6720 // actually comparing the expressions for equality. Because computing the 6721 // expression IDs can be expensive, we only do this if the diagnostic is 6722 // enabled. 6723 if (SizeOfArg && 6724 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 6725 SizeOfArg->getExprLoc())) { 6726 // We only compute IDs for expressions if the warning is enabled, and 6727 // cache the sizeof arg's ID. 6728 if (SizeOfArgID == llvm::FoldingSetNodeID()) 6729 SizeOfArg->Profile(SizeOfArgID, Context, true); 6730 llvm::FoldingSetNodeID DestID; 6731 Dest->Profile(DestID, Context, true); 6732 if (DestID == SizeOfArgID) { 6733 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 6734 // over sizeof(src) as well. 6735 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 6736 StringRef ReadableName = FnName->getName(); 6737 6738 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 6739 if (UnaryOp->getOpcode() == UO_AddrOf) 6740 ActionIdx = 1; // If its an address-of operator, just remove it. 6741 if (!PointeeTy->isIncompleteType() && 6742 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 6743 ActionIdx = 2; // If the pointee's size is sizeof(char), 6744 // suggest an explicit length. 6745 6746 // If the function is defined as a builtin macro, do not show macro 6747 // expansion. 6748 SourceLocation SL = SizeOfArg->getExprLoc(); 6749 SourceRange DSR = Dest->getSourceRange(); 6750 SourceRange SSR = SizeOfArg->getSourceRange(); 6751 SourceManager &SM = getSourceManager(); 6752 6753 if (SM.isMacroArgExpansion(SL)) { 6754 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 6755 SL = SM.getSpellingLoc(SL); 6756 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 6757 SM.getSpellingLoc(DSR.getEnd())); 6758 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 6759 SM.getSpellingLoc(SSR.getEnd())); 6760 } 6761 6762 DiagRuntimeBehavior(SL, SizeOfArg, 6763 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 6764 << ReadableName 6765 << PointeeTy 6766 << DestTy 6767 << DSR 6768 << SSR); 6769 DiagRuntimeBehavior(SL, SizeOfArg, 6770 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 6771 << ActionIdx 6772 << SSR); 6773 6774 break; 6775 } 6776 } 6777 6778 // Also check for cases where the sizeof argument is the exact same 6779 // type as the memory argument, and where it points to a user-defined 6780 // record type. 6781 if (SizeOfArgTy != QualType()) { 6782 if (PointeeTy->isRecordType() && 6783 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 6784 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 6785 PDiag(diag::warn_sizeof_pointer_type_memaccess) 6786 << FnName << SizeOfArgTy << ArgIdx 6787 << PointeeTy << Dest->getSourceRange() 6788 << LenExpr->getSourceRange()); 6789 break; 6790 } 6791 } 6792 } else if (DestTy->isArrayType()) { 6793 PointeeTy = DestTy; 6794 } 6795 6796 if (PointeeTy == QualType()) 6797 continue; 6798 6799 // Always complain about dynamic classes. 6800 bool IsContained; 6801 if (const CXXRecordDecl *ContainedRD = 6802 getContainedDynamicClass(PointeeTy, IsContained)) { 6803 6804 unsigned OperationType = 0; 6805 // "overwritten" if we're warning about the destination for any call 6806 // but memcmp; otherwise a verb appropriate to the call. 6807 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 6808 if (BId == Builtin::BImemcpy) 6809 OperationType = 1; 6810 else if(BId == Builtin::BImemmove) 6811 OperationType = 2; 6812 else if (BId == Builtin::BImemcmp) 6813 OperationType = 3; 6814 } 6815 6816 DiagRuntimeBehavior( 6817 Dest->getExprLoc(), Dest, 6818 PDiag(diag::warn_dyn_class_memaccess) 6819 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 6820 << FnName << IsContained << ContainedRD << OperationType 6821 << Call->getCallee()->getSourceRange()); 6822 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 6823 BId != Builtin::BImemset) 6824 DiagRuntimeBehavior( 6825 Dest->getExprLoc(), Dest, 6826 PDiag(diag::warn_arc_object_memaccess) 6827 << ArgIdx << FnName << PointeeTy 6828 << Call->getCallee()->getSourceRange()); 6829 else 6830 continue; 6831 6832 DiagRuntimeBehavior( 6833 Dest->getExprLoc(), Dest, 6834 PDiag(diag::note_bad_memaccess_silence) 6835 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 6836 break; 6837 } 6838 } 6839 6840 // A little helper routine: ignore addition and subtraction of integer literals. 6841 // This intentionally does not ignore all integer constant expressions because 6842 // we don't want to remove sizeof(). 6843 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 6844 Ex = Ex->IgnoreParenCasts(); 6845 6846 for (;;) { 6847 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 6848 if (!BO || !BO->isAdditiveOp()) 6849 break; 6850 6851 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 6852 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 6853 6854 if (isa<IntegerLiteral>(RHS)) 6855 Ex = LHS; 6856 else if (isa<IntegerLiteral>(LHS)) 6857 Ex = RHS; 6858 else 6859 break; 6860 } 6861 6862 return Ex; 6863 } 6864 6865 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 6866 ASTContext &Context) { 6867 // Only handle constant-sized or VLAs, but not flexible members. 6868 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 6869 // Only issue the FIXIT for arrays of size > 1. 6870 if (CAT->getSize().getSExtValue() <= 1) 6871 return false; 6872 } else if (!Ty->isVariableArrayType()) { 6873 return false; 6874 } 6875 return true; 6876 } 6877 6878 // Warn if the user has made the 'size' argument to strlcpy or strlcat 6879 // be the size of the source, instead of the destination. 6880 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 6881 IdentifierInfo *FnName) { 6882 6883 // Don't crash if the user has the wrong number of arguments 6884 unsigned NumArgs = Call->getNumArgs(); 6885 if ((NumArgs != 3) && (NumArgs != 4)) 6886 return; 6887 6888 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 6889 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 6890 const Expr *CompareWithSrc = nullptr; 6891 6892 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 6893 Call->getLocStart(), Call->getRParenLoc())) 6894 return; 6895 6896 // Look for 'strlcpy(dst, x, sizeof(x))' 6897 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 6898 CompareWithSrc = Ex; 6899 else { 6900 // Look for 'strlcpy(dst, x, strlen(x))' 6901 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 6902 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 6903 SizeCall->getNumArgs() == 1) 6904 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 6905 } 6906 } 6907 6908 if (!CompareWithSrc) 6909 return; 6910 6911 // Determine if the argument to sizeof/strlen is equal to the source 6912 // argument. In principle there's all kinds of things you could do 6913 // here, for instance creating an == expression and evaluating it with 6914 // EvaluateAsBooleanCondition, but this uses a more direct technique: 6915 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 6916 if (!SrcArgDRE) 6917 return; 6918 6919 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 6920 if (!CompareWithSrcDRE || 6921 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 6922 return; 6923 6924 const Expr *OriginalSizeArg = Call->getArg(2); 6925 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 6926 << OriginalSizeArg->getSourceRange() << FnName; 6927 6928 // Output a FIXIT hint if the destination is an array (rather than a 6929 // pointer to an array). This could be enhanced to handle some 6930 // pointers if we know the actual size, like if DstArg is 'array+2' 6931 // we could say 'sizeof(array)-2'. 6932 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 6933 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 6934 return; 6935 6936 SmallString<128> sizeString; 6937 llvm::raw_svector_ostream OS(sizeString); 6938 OS << "sizeof("; 6939 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 6940 OS << ")"; 6941 6942 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 6943 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 6944 OS.str()); 6945 } 6946 6947 /// Check if two expressions refer to the same declaration. 6948 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 6949 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 6950 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 6951 return D1->getDecl() == D2->getDecl(); 6952 return false; 6953 } 6954 6955 static const Expr *getStrlenExprArg(const Expr *E) { 6956 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6957 const FunctionDecl *FD = CE->getDirectCallee(); 6958 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 6959 return nullptr; 6960 return CE->getArg(0)->IgnoreParenCasts(); 6961 } 6962 return nullptr; 6963 } 6964 6965 // Warn on anti-patterns as the 'size' argument to strncat. 6966 // The correct size argument should look like following: 6967 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 6968 void Sema::CheckStrncatArguments(const CallExpr *CE, 6969 IdentifierInfo *FnName) { 6970 // Don't crash if the user has the wrong number of arguments. 6971 if (CE->getNumArgs() < 3) 6972 return; 6973 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 6974 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 6975 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 6976 6977 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 6978 CE->getRParenLoc())) 6979 return; 6980 6981 // Identify common expressions, which are wrongly used as the size argument 6982 // to strncat and may lead to buffer overflows. 6983 unsigned PatternType = 0; 6984 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 6985 // - sizeof(dst) 6986 if (referToTheSameDecl(SizeOfArg, DstArg)) 6987 PatternType = 1; 6988 // - sizeof(src) 6989 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 6990 PatternType = 2; 6991 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 6992 if (BE->getOpcode() == BO_Sub) { 6993 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 6994 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 6995 // - sizeof(dst) - strlen(dst) 6996 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 6997 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 6998 PatternType = 1; 6999 // - sizeof(src) - (anything) 7000 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7001 PatternType = 2; 7002 } 7003 } 7004 7005 if (PatternType == 0) 7006 return; 7007 7008 // Generate the diagnostic. 7009 SourceLocation SL = LenArg->getLocStart(); 7010 SourceRange SR = LenArg->getSourceRange(); 7011 SourceManager &SM = getSourceManager(); 7012 7013 // If the function is defined as a builtin macro, do not show macro expansion. 7014 if (SM.isMacroArgExpansion(SL)) { 7015 SL = SM.getSpellingLoc(SL); 7016 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7017 SM.getSpellingLoc(SR.getEnd())); 7018 } 7019 7020 // Check if the destination is an array (rather than a pointer to an array). 7021 QualType DstTy = DstArg->getType(); 7022 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7023 Context); 7024 if (!isKnownSizeArray) { 7025 if (PatternType == 1) 7026 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7027 else 7028 Diag(SL, diag::warn_strncat_src_size) << SR; 7029 return; 7030 } 7031 7032 if (PatternType == 1) 7033 Diag(SL, diag::warn_strncat_large_size) << SR; 7034 else 7035 Diag(SL, diag::warn_strncat_src_size) << SR; 7036 7037 SmallString<128> sizeString; 7038 llvm::raw_svector_ostream OS(sizeString); 7039 OS << "sizeof("; 7040 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7041 OS << ") - "; 7042 OS << "strlen("; 7043 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7044 OS << ") - 1"; 7045 7046 Diag(SL, diag::note_strncat_wrong_size) 7047 << FixItHint::CreateReplacement(SR, OS.str()); 7048 } 7049 7050 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7051 7052 static const Expr *EvalVal(const Expr *E, 7053 SmallVectorImpl<const DeclRefExpr *> &refVars, 7054 const Decl *ParentDecl); 7055 static const Expr *EvalAddr(const Expr *E, 7056 SmallVectorImpl<const DeclRefExpr *> &refVars, 7057 const Decl *ParentDecl); 7058 7059 /// CheckReturnStackAddr - Check if a return statement returns the address 7060 /// of a stack variable. 7061 static void 7062 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7063 SourceLocation ReturnLoc) { 7064 7065 const Expr *stackE = nullptr; 7066 SmallVector<const DeclRefExpr *, 8> refVars; 7067 7068 // Perform checking for returned stack addresses, local blocks, 7069 // label addresses or references to temporaries. 7070 if (lhsType->isPointerType() || 7071 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7072 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7073 } else if (lhsType->isReferenceType()) { 7074 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7075 } 7076 7077 if (!stackE) 7078 return; // Nothing suspicious was found. 7079 7080 // Parameters are initalized in the calling scope, so taking the address 7081 // of a parameter reference doesn't need a warning. 7082 for (auto *DRE : refVars) 7083 if (isa<ParmVarDecl>(DRE->getDecl())) 7084 return; 7085 7086 SourceLocation diagLoc; 7087 SourceRange diagRange; 7088 if (refVars.empty()) { 7089 diagLoc = stackE->getLocStart(); 7090 diagRange = stackE->getSourceRange(); 7091 } else { 7092 // We followed through a reference variable. 'stackE' contains the 7093 // problematic expression but we will warn at the return statement pointing 7094 // at the reference variable. We will later display the "trail" of 7095 // reference variables using notes. 7096 diagLoc = refVars[0]->getLocStart(); 7097 diagRange = refVars[0]->getSourceRange(); 7098 } 7099 7100 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7101 // address of local var 7102 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7103 << DR->getDecl()->getDeclName() << diagRange; 7104 } else if (isa<BlockExpr>(stackE)) { // local block. 7105 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7106 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7107 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7108 } else { // local temporary. 7109 // If there is an LValue->RValue conversion, then the value of the 7110 // reference type is used, not the reference. 7111 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7112 if (ICE->getCastKind() == CK_LValueToRValue) { 7113 return; 7114 } 7115 } 7116 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7117 << lhsType->isReferenceType() << diagRange; 7118 } 7119 7120 // Display the "trail" of reference variables that we followed until we 7121 // found the problematic expression using notes. 7122 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7123 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7124 // If this var binds to another reference var, show the range of the next 7125 // var, otherwise the var binds to the problematic expression, in which case 7126 // show the range of the expression. 7127 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7128 : stackE->getSourceRange(); 7129 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7130 << VD->getDeclName() << range; 7131 } 7132 } 7133 7134 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7135 /// check if the expression in a return statement evaluates to an address 7136 /// to a location on the stack, a local block, an address of a label, or a 7137 /// reference to local temporary. The recursion is used to traverse the 7138 /// AST of the return expression, with recursion backtracking when we 7139 /// encounter a subexpression that (1) clearly does not lead to one of the 7140 /// above problematic expressions (2) is something we cannot determine leads to 7141 /// a problematic expression based on such local checking. 7142 /// 7143 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7144 /// the expression that they point to. Such variables are added to the 7145 /// 'refVars' vector so that we know what the reference variable "trail" was. 7146 /// 7147 /// EvalAddr processes expressions that are pointers that are used as 7148 /// references (and not L-values). EvalVal handles all other values. 7149 /// At the base case of the recursion is a check for the above problematic 7150 /// expressions. 7151 /// 7152 /// This implementation handles: 7153 /// 7154 /// * pointer-to-pointer casts 7155 /// * implicit conversions from array references to pointers 7156 /// * taking the address of fields 7157 /// * arbitrary interplay between "&" and "*" operators 7158 /// * pointer arithmetic from an address of a stack variable 7159 /// * taking the address of an array element where the array is on the stack 7160 static const Expr *EvalAddr(const Expr *E, 7161 SmallVectorImpl<const DeclRefExpr *> &refVars, 7162 const Decl *ParentDecl) { 7163 if (E->isTypeDependent()) 7164 return nullptr; 7165 7166 // We should only be called for evaluating pointer expressions. 7167 assert((E->getType()->isAnyPointerType() || 7168 E->getType()->isBlockPointerType() || 7169 E->getType()->isObjCQualifiedIdType()) && 7170 "EvalAddr only works on pointers"); 7171 7172 E = E->IgnoreParens(); 7173 7174 // Our "symbolic interpreter" is just a dispatch off the currently 7175 // viewed AST node. We then recursively traverse the AST by calling 7176 // EvalAddr and EvalVal appropriately. 7177 switch (E->getStmtClass()) { 7178 case Stmt::DeclRefExprClass: { 7179 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7180 7181 // If we leave the immediate function, the lifetime isn't about to end. 7182 if (DR->refersToEnclosingVariableOrCapture()) 7183 return nullptr; 7184 7185 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7186 // If this is a reference variable, follow through to the expression that 7187 // it points to. 7188 if (V->hasLocalStorage() && 7189 V->getType()->isReferenceType() && V->hasInit()) { 7190 // Add the reference variable to the "trail". 7191 refVars.push_back(DR); 7192 return EvalAddr(V->getInit(), refVars, ParentDecl); 7193 } 7194 7195 return nullptr; 7196 } 7197 7198 case Stmt::UnaryOperatorClass: { 7199 // The only unary operator that make sense to handle here 7200 // is AddrOf. All others don't make sense as pointers. 7201 const UnaryOperator *U = cast<UnaryOperator>(E); 7202 7203 if (U->getOpcode() == UO_AddrOf) 7204 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7205 return nullptr; 7206 } 7207 7208 case Stmt::BinaryOperatorClass: { 7209 // Handle pointer arithmetic. All other binary operators are not valid 7210 // in this context. 7211 const BinaryOperator *B = cast<BinaryOperator>(E); 7212 BinaryOperatorKind op = B->getOpcode(); 7213 7214 if (op != BO_Add && op != BO_Sub) 7215 return nullptr; 7216 7217 const Expr *Base = B->getLHS(); 7218 7219 // Determine which argument is the real pointer base. It could be 7220 // the RHS argument instead of the LHS. 7221 if (!Base->getType()->isPointerType()) 7222 Base = B->getRHS(); 7223 7224 assert(Base->getType()->isPointerType()); 7225 return EvalAddr(Base, refVars, ParentDecl); 7226 } 7227 7228 // For conditional operators we need to see if either the LHS or RHS are 7229 // valid DeclRefExpr*s. If one of them is valid, we return it. 7230 case Stmt::ConditionalOperatorClass: { 7231 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7232 7233 // Handle the GNU extension for missing LHS. 7234 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7235 if (const Expr *LHSExpr = C->getLHS()) { 7236 // In C++, we can have a throw-expression, which has 'void' type. 7237 if (!LHSExpr->getType()->isVoidType()) 7238 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7239 return LHS; 7240 } 7241 7242 // In C++, we can have a throw-expression, which has 'void' type. 7243 if (C->getRHS()->getType()->isVoidType()) 7244 return nullptr; 7245 7246 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7247 } 7248 7249 case Stmt::BlockExprClass: 7250 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7251 return E; // local block. 7252 return nullptr; 7253 7254 case Stmt::AddrLabelExprClass: 7255 return E; // address of label. 7256 7257 case Stmt::ExprWithCleanupsClass: 7258 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7259 ParentDecl); 7260 7261 // For casts, we need to handle conversions from arrays to 7262 // pointer values, and pointer-to-pointer conversions. 7263 case Stmt::ImplicitCastExprClass: 7264 case Stmt::CStyleCastExprClass: 7265 case Stmt::CXXFunctionalCastExprClass: 7266 case Stmt::ObjCBridgedCastExprClass: 7267 case Stmt::CXXStaticCastExprClass: 7268 case Stmt::CXXDynamicCastExprClass: 7269 case Stmt::CXXConstCastExprClass: 7270 case Stmt::CXXReinterpretCastExprClass: { 7271 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7272 switch (cast<CastExpr>(E)->getCastKind()) { 7273 case CK_LValueToRValue: 7274 case CK_NoOp: 7275 case CK_BaseToDerived: 7276 case CK_DerivedToBase: 7277 case CK_UncheckedDerivedToBase: 7278 case CK_Dynamic: 7279 case CK_CPointerToObjCPointerCast: 7280 case CK_BlockPointerToObjCPointerCast: 7281 case CK_AnyPointerToBlockPointerCast: 7282 return EvalAddr(SubExpr, refVars, ParentDecl); 7283 7284 case CK_ArrayToPointerDecay: 7285 return EvalVal(SubExpr, refVars, ParentDecl); 7286 7287 case CK_BitCast: 7288 if (SubExpr->getType()->isAnyPointerType() || 7289 SubExpr->getType()->isBlockPointerType() || 7290 SubExpr->getType()->isObjCQualifiedIdType()) 7291 return EvalAddr(SubExpr, refVars, ParentDecl); 7292 else 7293 return nullptr; 7294 7295 default: 7296 return nullptr; 7297 } 7298 } 7299 7300 case Stmt::MaterializeTemporaryExprClass: 7301 if (const Expr *Result = 7302 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7303 refVars, ParentDecl)) 7304 return Result; 7305 return E; 7306 7307 // Everything else: we simply don't reason about them. 7308 default: 7309 return nullptr; 7310 } 7311 } 7312 7313 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7314 /// See the comments for EvalAddr for more details. 7315 static const Expr *EvalVal(const Expr *E, 7316 SmallVectorImpl<const DeclRefExpr *> &refVars, 7317 const Decl *ParentDecl) { 7318 do { 7319 // We should only be called for evaluating non-pointer expressions, or 7320 // expressions with a pointer type that are not used as references but 7321 // instead 7322 // are l-values (e.g., DeclRefExpr with a pointer type). 7323 7324 // Our "symbolic interpreter" is just a dispatch off the currently 7325 // viewed AST node. We then recursively traverse the AST by calling 7326 // EvalAddr and EvalVal appropriately. 7327 7328 E = E->IgnoreParens(); 7329 switch (E->getStmtClass()) { 7330 case Stmt::ImplicitCastExprClass: { 7331 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7332 if (IE->getValueKind() == VK_LValue) { 7333 E = IE->getSubExpr(); 7334 continue; 7335 } 7336 return nullptr; 7337 } 7338 7339 case Stmt::ExprWithCleanupsClass: 7340 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7341 ParentDecl); 7342 7343 case Stmt::DeclRefExprClass: { 7344 // When we hit a DeclRefExpr we are looking at code that refers to a 7345 // variable's name. If it's not a reference variable we check if it has 7346 // local storage within the function, and if so, return the expression. 7347 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7348 7349 // If we leave the immediate function, the lifetime isn't about to end. 7350 if (DR->refersToEnclosingVariableOrCapture()) 7351 return nullptr; 7352 7353 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7354 // Check if it refers to itself, e.g. "int& i = i;". 7355 if (V == ParentDecl) 7356 return DR; 7357 7358 if (V->hasLocalStorage()) { 7359 if (!V->getType()->isReferenceType()) 7360 return DR; 7361 7362 // Reference variable, follow through to the expression that 7363 // it points to. 7364 if (V->hasInit()) { 7365 // Add the reference variable to the "trail". 7366 refVars.push_back(DR); 7367 return EvalVal(V->getInit(), refVars, V); 7368 } 7369 } 7370 } 7371 7372 return nullptr; 7373 } 7374 7375 case Stmt::UnaryOperatorClass: { 7376 // The only unary operator that make sense to handle here 7377 // is Deref. All others don't resolve to a "name." This includes 7378 // handling all sorts of rvalues passed to a unary operator. 7379 const UnaryOperator *U = cast<UnaryOperator>(E); 7380 7381 if (U->getOpcode() == UO_Deref) 7382 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7383 7384 return nullptr; 7385 } 7386 7387 case Stmt::ArraySubscriptExprClass: { 7388 // Array subscripts are potential references to data on the stack. We 7389 // retrieve the DeclRefExpr* for the array variable if it indeed 7390 // has local storage. 7391 const auto *ASE = cast<ArraySubscriptExpr>(E); 7392 if (ASE->isTypeDependent()) 7393 return nullptr; 7394 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7395 } 7396 7397 case Stmt::OMPArraySectionExprClass: { 7398 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7399 ParentDecl); 7400 } 7401 7402 case Stmt::ConditionalOperatorClass: { 7403 // For conditional operators we need to see if either the LHS or RHS are 7404 // non-NULL Expr's. If one is non-NULL, we return it. 7405 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7406 7407 // Handle the GNU extension for missing LHS. 7408 if (const Expr *LHSExpr = C->getLHS()) { 7409 // In C++, we can have a throw-expression, which has 'void' type. 7410 if (!LHSExpr->getType()->isVoidType()) 7411 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 7412 return LHS; 7413 } 7414 7415 // In C++, we can have a throw-expression, which has 'void' type. 7416 if (C->getRHS()->getType()->isVoidType()) 7417 return nullptr; 7418 7419 return EvalVal(C->getRHS(), refVars, ParentDecl); 7420 } 7421 7422 // Accesses to members are potential references to data on the stack. 7423 case Stmt::MemberExprClass: { 7424 const MemberExpr *M = cast<MemberExpr>(E); 7425 7426 // Check for indirect access. We only want direct field accesses. 7427 if (M->isArrow()) 7428 return nullptr; 7429 7430 // Check whether the member type is itself a reference, in which case 7431 // we're not going to refer to the member, but to what the member refers 7432 // to. 7433 if (M->getMemberDecl()->getType()->isReferenceType()) 7434 return nullptr; 7435 7436 return EvalVal(M->getBase(), refVars, ParentDecl); 7437 } 7438 7439 case Stmt::MaterializeTemporaryExprClass: 7440 if (const Expr *Result = 7441 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7442 refVars, ParentDecl)) 7443 return Result; 7444 return E; 7445 7446 default: 7447 // Check that we don't return or take the address of a reference to a 7448 // temporary. This is only useful in C++. 7449 if (!E->isTypeDependent() && E->isRValue()) 7450 return E; 7451 7452 // Everything else: we simply don't reason about them. 7453 return nullptr; 7454 } 7455 } while (true); 7456 } 7457 7458 void 7459 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 7460 SourceLocation ReturnLoc, 7461 bool isObjCMethod, 7462 const AttrVec *Attrs, 7463 const FunctionDecl *FD) { 7464 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 7465 7466 // Check if the return value is null but should not be. 7467 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 7468 (!isObjCMethod && isNonNullType(Context, lhsType))) && 7469 CheckNonNullExpr(*this, RetValExp)) 7470 Diag(ReturnLoc, diag::warn_null_ret) 7471 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 7472 7473 // C++11 [basic.stc.dynamic.allocation]p4: 7474 // If an allocation function declared with a non-throwing 7475 // exception-specification fails to allocate storage, it shall return 7476 // a null pointer. Any other allocation function that fails to allocate 7477 // storage shall indicate failure only by throwing an exception [...] 7478 if (FD) { 7479 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 7480 if (Op == OO_New || Op == OO_Array_New) { 7481 const FunctionProtoType *Proto 7482 = FD->getType()->castAs<FunctionProtoType>(); 7483 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 7484 CheckNonNullExpr(*this, RetValExp)) 7485 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 7486 << FD << getLangOpts().CPlusPlus11; 7487 } 7488 } 7489 } 7490 7491 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 7492 7493 /// Check for comparisons of floating point operands using != and ==. 7494 /// Issue a warning if these are no self-comparisons, as they are not likely 7495 /// to do what the programmer intended. 7496 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 7497 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 7498 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 7499 7500 // Special case: check for x == x (which is OK). 7501 // Do not emit warnings for such cases. 7502 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 7503 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 7504 if (DRL->getDecl() == DRR->getDecl()) 7505 return; 7506 7507 // Special case: check for comparisons against literals that can be exactly 7508 // represented by APFloat. In such cases, do not emit a warning. This 7509 // is a heuristic: often comparison against such literals are used to 7510 // detect if a value in a variable has not changed. This clearly can 7511 // lead to false negatives. 7512 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 7513 if (FLL->isExact()) 7514 return; 7515 } else 7516 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 7517 if (FLR->isExact()) 7518 return; 7519 7520 // Check for comparisons with builtin types. 7521 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 7522 if (CL->getBuiltinCallee()) 7523 return; 7524 7525 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 7526 if (CR->getBuiltinCallee()) 7527 return; 7528 7529 // Emit the diagnostic. 7530 Diag(Loc, diag::warn_floatingpoint_eq) 7531 << LHS->getSourceRange() << RHS->getSourceRange(); 7532 } 7533 7534 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 7535 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 7536 7537 namespace { 7538 7539 /// Structure recording the 'active' range of an integer-valued 7540 /// expression. 7541 struct IntRange { 7542 /// The number of bits active in the int. 7543 unsigned Width; 7544 7545 /// True if the int is known not to have negative values. 7546 bool NonNegative; 7547 7548 IntRange(unsigned Width, bool NonNegative) 7549 : Width(Width), NonNegative(NonNegative) 7550 {} 7551 7552 /// Returns the range of the bool type. 7553 static IntRange forBoolType() { 7554 return IntRange(1, true); 7555 } 7556 7557 /// Returns the range of an opaque value of the given integral type. 7558 static IntRange forValueOfType(ASTContext &C, QualType T) { 7559 return forValueOfCanonicalType(C, 7560 T->getCanonicalTypeInternal().getTypePtr()); 7561 } 7562 7563 /// Returns the range of an opaque value of a canonical integral type. 7564 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 7565 assert(T->isCanonicalUnqualified()); 7566 7567 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7568 T = VT->getElementType().getTypePtr(); 7569 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7570 T = CT->getElementType().getTypePtr(); 7571 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7572 T = AT->getValueType().getTypePtr(); 7573 7574 // For enum types, use the known bit width of the enumerators. 7575 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 7576 EnumDecl *Enum = ET->getDecl(); 7577 if (!Enum->isCompleteDefinition()) 7578 return IntRange(C.getIntWidth(QualType(T, 0)), false); 7579 7580 unsigned NumPositive = Enum->getNumPositiveBits(); 7581 unsigned NumNegative = Enum->getNumNegativeBits(); 7582 7583 if (NumNegative == 0) 7584 return IntRange(NumPositive, true/*NonNegative*/); 7585 else 7586 return IntRange(std::max(NumPositive + 1, NumNegative), 7587 false/*NonNegative*/); 7588 } 7589 7590 const BuiltinType *BT = cast<BuiltinType>(T); 7591 assert(BT->isInteger()); 7592 7593 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7594 } 7595 7596 /// Returns the "target" range of a canonical integral type, i.e. 7597 /// the range of values expressible in the type. 7598 /// 7599 /// This matches forValueOfCanonicalType except that enums have the 7600 /// full range of their type, not the range of their enumerators. 7601 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 7602 assert(T->isCanonicalUnqualified()); 7603 7604 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7605 T = VT->getElementType().getTypePtr(); 7606 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7607 T = CT->getElementType().getTypePtr(); 7608 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7609 T = AT->getValueType().getTypePtr(); 7610 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7611 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 7612 7613 const BuiltinType *BT = cast<BuiltinType>(T); 7614 assert(BT->isInteger()); 7615 7616 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7617 } 7618 7619 /// Returns the supremum of two ranges: i.e. their conservative merge. 7620 static IntRange join(IntRange L, IntRange R) { 7621 return IntRange(std::max(L.Width, R.Width), 7622 L.NonNegative && R.NonNegative); 7623 } 7624 7625 /// Returns the infinum of two ranges: i.e. their aggressive merge. 7626 static IntRange meet(IntRange L, IntRange R) { 7627 return IntRange(std::min(L.Width, R.Width), 7628 L.NonNegative || R.NonNegative); 7629 } 7630 }; 7631 7632 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 7633 if (value.isSigned() && value.isNegative()) 7634 return IntRange(value.getMinSignedBits(), false); 7635 7636 if (value.getBitWidth() > MaxWidth) 7637 value = value.trunc(MaxWidth); 7638 7639 // isNonNegative() just checks the sign bit without considering 7640 // signedness. 7641 return IntRange(value.getActiveBits(), true); 7642 } 7643 7644 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 7645 unsigned MaxWidth) { 7646 if (result.isInt()) 7647 return GetValueRange(C, result.getInt(), MaxWidth); 7648 7649 if (result.isVector()) { 7650 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 7651 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 7652 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 7653 R = IntRange::join(R, El); 7654 } 7655 return R; 7656 } 7657 7658 if (result.isComplexInt()) { 7659 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 7660 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 7661 return IntRange::join(R, I); 7662 } 7663 7664 // This can happen with lossless casts to intptr_t of "based" lvalues. 7665 // Assume it might use arbitrary bits. 7666 // FIXME: The only reason we need to pass the type in here is to get 7667 // the sign right on this one case. It would be nice if APValue 7668 // preserved this. 7669 assert(result.isLValue() || result.isAddrLabelDiff()); 7670 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 7671 } 7672 7673 QualType GetExprType(const Expr *E) { 7674 QualType Ty = E->getType(); 7675 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 7676 Ty = AtomicRHS->getValueType(); 7677 return Ty; 7678 } 7679 7680 /// Pseudo-evaluate the given integer expression, estimating the 7681 /// range of values it might take. 7682 /// 7683 /// \param MaxWidth - the width to which the value will be truncated 7684 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 7685 E = E->IgnoreParens(); 7686 7687 // Try a full evaluation first. 7688 Expr::EvalResult result; 7689 if (E->EvaluateAsRValue(result, C)) 7690 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 7691 7692 // I think we only want to look through implicit casts here; if the 7693 // user has an explicit widening cast, we should treat the value as 7694 // being of the new, wider type. 7695 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 7696 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 7697 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 7698 7699 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 7700 7701 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 7702 CE->getCastKind() == CK_BooleanToSignedIntegral; 7703 7704 // Assume that non-integer casts can span the full range of the type. 7705 if (!isIntegerCast) 7706 return OutputTypeRange; 7707 7708 IntRange SubRange 7709 = GetExprRange(C, CE->getSubExpr(), 7710 std::min(MaxWidth, OutputTypeRange.Width)); 7711 7712 // Bail out if the subexpr's range is as wide as the cast type. 7713 if (SubRange.Width >= OutputTypeRange.Width) 7714 return OutputTypeRange; 7715 7716 // Otherwise, we take the smaller width, and we're non-negative if 7717 // either the output type or the subexpr is. 7718 return IntRange(SubRange.Width, 7719 SubRange.NonNegative || OutputTypeRange.NonNegative); 7720 } 7721 7722 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 7723 // If we can fold the condition, just take that operand. 7724 bool CondResult; 7725 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 7726 return GetExprRange(C, CondResult ? CO->getTrueExpr() 7727 : CO->getFalseExpr(), 7728 MaxWidth); 7729 7730 // Otherwise, conservatively merge. 7731 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 7732 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 7733 return IntRange::join(L, R); 7734 } 7735 7736 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 7737 switch (BO->getOpcode()) { 7738 7739 // Boolean-valued operations are single-bit and positive. 7740 case BO_LAnd: 7741 case BO_LOr: 7742 case BO_LT: 7743 case BO_GT: 7744 case BO_LE: 7745 case BO_GE: 7746 case BO_EQ: 7747 case BO_NE: 7748 return IntRange::forBoolType(); 7749 7750 // The type of the assignments is the type of the LHS, so the RHS 7751 // is not necessarily the same type. 7752 case BO_MulAssign: 7753 case BO_DivAssign: 7754 case BO_RemAssign: 7755 case BO_AddAssign: 7756 case BO_SubAssign: 7757 case BO_XorAssign: 7758 case BO_OrAssign: 7759 // TODO: bitfields? 7760 return IntRange::forValueOfType(C, GetExprType(E)); 7761 7762 // Simple assignments just pass through the RHS, which will have 7763 // been coerced to the LHS type. 7764 case BO_Assign: 7765 // TODO: bitfields? 7766 return GetExprRange(C, BO->getRHS(), MaxWidth); 7767 7768 // Operations with opaque sources are black-listed. 7769 case BO_PtrMemD: 7770 case BO_PtrMemI: 7771 return IntRange::forValueOfType(C, GetExprType(E)); 7772 7773 // Bitwise-and uses the *infinum* of the two source ranges. 7774 case BO_And: 7775 case BO_AndAssign: 7776 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 7777 GetExprRange(C, BO->getRHS(), MaxWidth)); 7778 7779 // Left shift gets black-listed based on a judgement call. 7780 case BO_Shl: 7781 // ...except that we want to treat '1 << (blah)' as logically 7782 // positive. It's an important idiom. 7783 if (IntegerLiteral *I 7784 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 7785 if (I->getValue() == 1) { 7786 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 7787 return IntRange(R.Width, /*NonNegative*/ true); 7788 } 7789 } 7790 // fallthrough 7791 7792 case BO_ShlAssign: 7793 return IntRange::forValueOfType(C, GetExprType(E)); 7794 7795 // Right shift by a constant can narrow its left argument. 7796 case BO_Shr: 7797 case BO_ShrAssign: { 7798 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 7799 7800 // If the shift amount is a positive constant, drop the width by 7801 // that much. 7802 llvm::APSInt shift; 7803 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 7804 shift.isNonNegative()) { 7805 unsigned zext = shift.getZExtValue(); 7806 if (zext >= L.Width) 7807 L.Width = (L.NonNegative ? 0 : 1); 7808 else 7809 L.Width -= zext; 7810 } 7811 7812 return L; 7813 } 7814 7815 // Comma acts as its right operand. 7816 case BO_Comma: 7817 return GetExprRange(C, BO->getRHS(), MaxWidth); 7818 7819 // Black-list pointer subtractions. 7820 case BO_Sub: 7821 if (BO->getLHS()->getType()->isPointerType()) 7822 return IntRange::forValueOfType(C, GetExprType(E)); 7823 break; 7824 7825 // The width of a division result is mostly determined by the size 7826 // of the LHS. 7827 case BO_Div: { 7828 // Don't 'pre-truncate' the operands. 7829 unsigned opWidth = C.getIntWidth(GetExprType(E)); 7830 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 7831 7832 // If the divisor is constant, use that. 7833 llvm::APSInt divisor; 7834 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 7835 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 7836 if (log2 >= L.Width) 7837 L.Width = (L.NonNegative ? 0 : 1); 7838 else 7839 L.Width = std::min(L.Width - log2, MaxWidth); 7840 return L; 7841 } 7842 7843 // Otherwise, just use the LHS's width. 7844 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 7845 return IntRange(L.Width, L.NonNegative && R.NonNegative); 7846 } 7847 7848 // The result of a remainder can't be larger than the result of 7849 // either side. 7850 case BO_Rem: { 7851 // Don't 'pre-truncate' the operands. 7852 unsigned opWidth = C.getIntWidth(GetExprType(E)); 7853 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 7854 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 7855 7856 IntRange meet = IntRange::meet(L, R); 7857 meet.Width = std::min(meet.Width, MaxWidth); 7858 return meet; 7859 } 7860 7861 // The default behavior is okay for these. 7862 case BO_Mul: 7863 case BO_Add: 7864 case BO_Xor: 7865 case BO_Or: 7866 break; 7867 } 7868 7869 // The default case is to treat the operation as if it were closed 7870 // on the narrowest type that encompasses both operands. 7871 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 7872 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 7873 return IntRange::join(L, R); 7874 } 7875 7876 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 7877 switch (UO->getOpcode()) { 7878 // Boolean-valued operations are white-listed. 7879 case UO_LNot: 7880 return IntRange::forBoolType(); 7881 7882 // Operations with opaque sources are black-listed. 7883 case UO_Deref: 7884 case UO_AddrOf: // should be impossible 7885 return IntRange::forValueOfType(C, GetExprType(E)); 7886 7887 default: 7888 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 7889 } 7890 } 7891 7892 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 7893 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 7894 7895 if (const auto *BitField = E->getSourceBitField()) 7896 return IntRange(BitField->getBitWidthValue(C), 7897 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 7898 7899 return IntRange::forValueOfType(C, GetExprType(E)); 7900 } 7901 7902 IntRange GetExprRange(ASTContext &C, const Expr *E) { 7903 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 7904 } 7905 7906 /// Checks whether the given value, which currently has the given 7907 /// source semantics, has the same value when coerced through the 7908 /// target semantics. 7909 bool IsSameFloatAfterCast(const llvm::APFloat &value, 7910 const llvm::fltSemantics &Src, 7911 const llvm::fltSemantics &Tgt) { 7912 llvm::APFloat truncated = value; 7913 7914 bool ignored; 7915 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 7916 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 7917 7918 return truncated.bitwiseIsEqual(value); 7919 } 7920 7921 /// Checks whether the given value, which currently has the given 7922 /// source semantics, has the same value when coerced through the 7923 /// target semantics. 7924 /// 7925 /// The value might be a vector of floats (or a complex number). 7926 bool IsSameFloatAfterCast(const APValue &value, 7927 const llvm::fltSemantics &Src, 7928 const llvm::fltSemantics &Tgt) { 7929 if (value.isFloat()) 7930 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 7931 7932 if (value.isVector()) { 7933 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 7934 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 7935 return false; 7936 return true; 7937 } 7938 7939 assert(value.isComplexFloat()); 7940 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 7941 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 7942 } 7943 7944 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 7945 7946 bool IsZero(Sema &S, Expr *E) { 7947 // Suppress cases where we are comparing against an enum constant. 7948 if (const DeclRefExpr *DR = 7949 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 7950 if (isa<EnumConstantDecl>(DR->getDecl())) 7951 return false; 7952 7953 // Suppress cases where the '0' value is expanded from a macro. 7954 if (E->getLocStart().isMacroID()) 7955 return false; 7956 7957 llvm::APSInt Value; 7958 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 7959 } 7960 7961 bool HasEnumType(Expr *E) { 7962 // Strip off implicit integral promotions. 7963 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7964 if (ICE->getCastKind() != CK_IntegralCast && 7965 ICE->getCastKind() != CK_NoOp) 7966 break; 7967 E = ICE->getSubExpr(); 7968 } 7969 7970 return E->getType()->isEnumeralType(); 7971 } 7972 7973 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 7974 // Disable warning in template instantiations. 7975 if (!S.ActiveTemplateInstantiations.empty()) 7976 return; 7977 7978 BinaryOperatorKind op = E->getOpcode(); 7979 if (E->isValueDependent()) 7980 return; 7981 7982 if (op == BO_LT && IsZero(S, E->getRHS())) { 7983 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 7984 << "< 0" << "false" << HasEnumType(E->getLHS()) 7985 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7986 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 7987 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 7988 << ">= 0" << "true" << HasEnumType(E->getLHS()) 7989 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7990 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 7991 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 7992 << "0 >" << "false" << HasEnumType(E->getRHS()) 7993 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7994 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 7995 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 7996 << "0 <=" << "true" << HasEnumType(E->getRHS()) 7997 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7998 } 7999 } 8000 8001 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8002 Expr *Other, const llvm::APSInt &Value, 8003 bool RhsConstant) { 8004 // Disable warning in template instantiations. 8005 if (!S.ActiveTemplateInstantiations.empty()) 8006 return; 8007 8008 // TODO: Investigate using GetExprRange() to get tighter bounds 8009 // on the bit ranges. 8010 QualType OtherT = Other->getType(); 8011 if (const auto *AT = OtherT->getAs<AtomicType>()) 8012 OtherT = AT->getValueType(); 8013 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8014 unsigned OtherWidth = OtherRange.Width; 8015 8016 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8017 8018 // 0 values are handled later by CheckTrivialUnsignedComparison(). 8019 if ((Value == 0) && (!OtherIsBooleanType)) 8020 return; 8021 8022 BinaryOperatorKind op = E->getOpcode(); 8023 bool IsTrue = true; 8024 8025 // Used for diagnostic printout. 8026 enum { 8027 LiteralConstant = 0, 8028 CXXBoolLiteralTrue, 8029 CXXBoolLiteralFalse 8030 } LiteralOrBoolConstant = LiteralConstant; 8031 8032 if (!OtherIsBooleanType) { 8033 QualType ConstantT = Constant->getType(); 8034 QualType CommonT = E->getLHS()->getType(); 8035 8036 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8037 return; 8038 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8039 "comparison with non-integer type"); 8040 8041 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8042 bool CommonSigned = CommonT->isSignedIntegerType(); 8043 8044 bool EqualityOnly = false; 8045 8046 if (CommonSigned) { 8047 // The common type is signed, therefore no signed to unsigned conversion. 8048 if (!OtherRange.NonNegative) { 8049 // Check that the constant is representable in type OtherT. 8050 if (ConstantSigned) { 8051 if (OtherWidth >= Value.getMinSignedBits()) 8052 return; 8053 } else { // !ConstantSigned 8054 if (OtherWidth >= Value.getActiveBits() + 1) 8055 return; 8056 } 8057 } else { // !OtherSigned 8058 // Check that the constant is representable in type OtherT. 8059 // Negative values are out of range. 8060 if (ConstantSigned) { 8061 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8062 return; 8063 } else { // !ConstantSigned 8064 if (OtherWidth >= Value.getActiveBits()) 8065 return; 8066 } 8067 } 8068 } else { // !CommonSigned 8069 if (OtherRange.NonNegative) { 8070 if (OtherWidth >= Value.getActiveBits()) 8071 return; 8072 } else { // OtherSigned 8073 assert(!ConstantSigned && 8074 "Two signed types converted to unsigned types."); 8075 // Check to see if the constant is representable in OtherT. 8076 if (OtherWidth > Value.getActiveBits()) 8077 return; 8078 // Check to see if the constant is equivalent to a negative value 8079 // cast to CommonT. 8080 if (S.Context.getIntWidth(ConstantT) == 8081 S.Context.getIntWidth(CommonT) && 8082 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8083 return; 8084 // The constant value rests between values that OtherT can represent 8085 // after conversion. Relational comparison still works, but equality 8086 // comparisons will be tautological. 8087 EqualityOnly = true; 8088 } 8089 } 8090 8091 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8092 8093 if (op == BO_EQ || op == BO_NE) { 8094 IsTrue = op == BO_NE; 8095 } else if (EqualityOnly) { 8096 return; 8097 } else if (RhsConstant) { 8098 if (op == BO_GT || op == BO_GE) 8099 IsTrue = !PositiveConstant; 8100 else // op == BO_LT || op == BO_LE 8101 IsTrue = PositiveConstant; 8102 } else { 8103 if (op == BO_LT || op == BO_LE) 8104 IsTrue = !PositiveConstant; 8105 else // op == BO_GT || op == BO_GE 8106 IsTrue = PositiveConstant; 8107 } 8108 } else { 8109 // Other isKnownToHaveBooleanValue 8110 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8111 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8112 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8113 8114 static const struct LinkedConditions { 8115 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8116 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8117 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8118 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8119 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8120 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8121 8122 } TruthTable = { 8123 // Constant on LHS. | Constant on RHS. | 8124 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8125 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8126 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8127 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8128 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8129 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8130 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8131 }; 8132 8133 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8134 8135 enum ConstantValue ConstVal = Zero; 8136 if (Value.isUnsigned() || Value.isNonNegative()) { 8137 if (Value == 0) { 8138 LiteralOrBoolConstant = 8139 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8140 ConstVal = Zero; 8141 } else if (Value == 1) { 8142 LiteralOrBoolConstant = 8143 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8144 ConstVal = One; 8145 } else { 8146 LiteralOrBoolConstant = LiteralConstant; 8147 ConstVal = GT_One; 8148 } 8149 } else { 8150 ConstVal = LT_Zero; 8151 } 8152 8153 CompareBoolWithConstantResult CmpRes; 8154 8155 switch (op) { 8156 case BO_LT: 8157 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8158 break; 8159 case BO_GT: 8160 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8161 break; 8162 case BO_LE: 8163 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8164 break; 8165 case BO_GE: 8166 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8167 break; 8168 case BO_EQ: 8169 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8170 break; 8171 case BO_NE: 8172 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8173 break; 8174 default: 8175 CmpRes = Unkwn; 8176 break; 8177 } 8178 8179 if (CmpRes == AFals) { 8180 IsTrue = false; 8181 } else if (CmpRes == ATrue) { 8182 IsTrue = true; 8183 } else { 8184 return; 8185 } 8186 } 8187 8188 // If this is a comparison to an enum constant, include that 8189 // constant in the diagnostic. 8190 const EnumConstantDecl *ED = nullptr; 8191 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8192 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8193 8194 SmallString<64> PrettySourceValue; 8195 llvm::raw_svector_ostream OS(PrettySourceValue); 8196 if (ED) 8197 OS << '\'' << *ED << "' (" << Value << ")"; 8198 else 8199 OS << Value; 8200 8201 S.DiagRuntimeBehavior( 8202 E->getOperatorLoc(), E, 8203 S.PDiag(diag::warn_out_of_range_compare) 8204 << OS.str() << LiteralOrBoolConstant 8205 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8206 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8207 } 8208 8209 /// Analyze the operands of the given comparison. Implements the 8210 /// fallback case from AnalyzeComparison. 8211 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8212 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8213 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8214 } 8215 8216 /// \brief Implements -Wsign-compare. 8217 /// 8218 /// \param E the binary operator to check for warnings 8219 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8220 // The type the comparison is being performed in. 8221 QualType T = E->getLHS()->getType(); 8222 8223 // Only analyze comparison operators where both sides have been converted to 8224 // the same type. 8225 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8226 return AnalyzeImpConvsInComparison(S, E); 8227 8228 // Don't analyze value-dependent comparisons directly. 8229 if (E->isValueDependent()) 8230 return AnalyzeImpConvsInComparison(S, E); 8231 8232 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8233 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8234 8235 bool IsComparisonConstant = false; 8236 8237 // Check whether an integer constant comparison results in a value 8238 // of 'true' or 'false'. 8239 if (T->isIntegralType(S.Context)) { 8240 llvm::APSInt RHSValue; 8241 bool IsRHSIntegralLiteral = 8242 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8243 llvm::APSInt LHSValue; 8244 bool IsLHSIntegralLiteral = 8245 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8246 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8247 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8248 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8249 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8250 else 8251 IsComparisonConstant = 8252 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8253 } else if (!T->hasUnsignedIntegerRepresentation()) 8254 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8255 8256 // We don't do anything special if this isn't an unsigned integral 8257 // comparison: we're only interested in integral comparisons, and 8258 // signed comparisons only happen in cases we don't care to warn about. 8259 // 8260 // We also don't care about value-dependent expressions or expressions 8261 // whose result is a constant. 8262 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 8263 return AnalyzeImpConvsInComparison(S, E); 8264 8265 // Check to see if one of the (unmodified) operands is of different 8266 // signedness. 8267 Expr *signedOperand, *unsignedOperand; 8268 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8269 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8270 "unsigned comparison between two signed integer expressions?"); 8271 signedOperand = LHS; 8272 unsignedOperand = RHS; 8273 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8274 signedOperand = RHS; 8275 unsignedOperand = LHS; 8276 } else { 8277 CheckTrivialUnsignedComparison(S, E); 8278 return AnalyzeImpConvsInComparison(S, E); 8279 } 8280 8281 // Otherwise, calculate the effective range of the signed operand. 8282 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8283 8284 // Go ahead and analyze implicit conversions in the operands. Note 8285 // that we skip the implicit conversions on both sides. 8286 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8287 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8288 8289 // If the signed range is non-negative, -Wsign-compare won't fire, 8290 // but we should still check for comparisons which are always true 8291 // or false. 8292 if (signedRange.NonNegative) 8293 return CheckTrivialUnsignedComparison(S, E); 8294 8295 // For (in)equality comparisons, if the unsigned operand is a 8296 // constant which cannot collide with a overflowed signed operand, 8297 // then reinterpreting the signed operand as unsigned will not 8298 // change the result of the comparison. 8299 if (E->isEqualityOp()) { 8300 unsigned comparisonWidth = S.Context.getIntWidth(T); 8301 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8302 8303 // We should never be unable to prove that the unsigned operand is 8304 // non-negative. 8305 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8306 8307 if (unsignedRange.Width < comparisonWidth) 8308 return; 8309 } 8310 8311 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8312 S.PDiag(diag::warn_mixed_sign_comparison) 8313 << LHS->getType() << RHS->getType() 8314 << LHS->getSourceRange() << RHS->getSourceRange()); 8315 } 8316 8317 /// Analyzes an attempt to assign the given value to a bitfield. 8318 /// 8319 /// Returns true if there was something fishy about the attempt. 8320 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8321 SourceLocation InitLoc) { 8322 assert(Bitfield->isBitField()); 8323 if (Bitfield->isInvalidDecl()) 8324 return false; 8325 8326 // White-list bool bitfields. 8327 if (Bitfield->getType()->isBooleanType()) 8328 return false; 8329 8330 // Ignore value- or type-dependent expressions. 8331 if (Bitfield->getBitWidth()->isValueDependent() || 8332 Bitfield->getBitWidth()->isTypeDependent() || 8333 Init->isValueDependent() || 8334 Init->isTypeDependent()) 8335 return false; 8336 8337 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8338 8339 llvm::APSInt Value; 8340 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 8341 return false; 8342 8343 unsigned OriginalWidth = Value.getBitWidth(); 8344 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8345 8346 if (!Value.isSigned() || Value.isNegative()) 8347 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 8348 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 8349 OriginalWidth = Value.getMinSignedBits(); 8350 8351 if (OriginalWidth <= FieldWidth) 8352 return false; 8353 8354 // Compute the value which the bitfield will contain. 8355 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 8356 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 8357 8358 // Check whether the stored value is equal to the original value. 8359 TruncatedValue = TruncatedValue.extend(OriginalWidth); 8360 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 8361 return false; 8362 8363 // Special-case bitfields of width 1: booleans are naturally 0/1, and 8364 // therefore don't strictly fit into a signed bitfield of width 1. 8365 if (FieldWidth == 1 && Value == 1) 8366 return false; 8367 8368 std::string PrettyValue = Value.toString(10); 8369 std::string PrettyTrunc = TruncatedValue.toString(10); 8370 8371 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 8372 << PrettyValue << PrettyTrunc << OriginalInit->getType() 8373 << Init->getSourceRange(); 8374 8375 return true; 8376 } 8377 8378 /// Analyze the given simple or compound assignment for warning-worthy 8379 /// operations. 8380 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 8381 // Just recurse on the LHS. 8382 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8383 8384 // We want to recurse on the RHS as normal unless we're assigning to 8385 // a bitfield. 8386 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 8387 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 8388 E->getOperatorLoc())) { 8389 // Recurse, ignoring any implicit conversions on the RHS. 8390 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 8391 E->getOperatorLoc()); 8392 } 8393 } 8394 8395 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8396 } 8397 8398 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8399 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 8400 SourceLocation CContext, unsigned diag, 8401 bool pruneControlFlow = false) { 8402 if (pruneControlFlow) { 8403 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8404 S.PDiag(diag) 8405 << SourceType << T << E->getSourceRange() 8406 << SourceRange(CContext)); 8407 return; 8408 } 8409 S.Diag(E->getExprLoc(), diag) 8410 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 8411 } 8412 8413 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8414 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 8415 unsigned diag, bool pruneControlFlow = false) { 8416 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 8417 } 8418 8419 8420 /// Diagnose an implicit cast from a floating point value to an integer value. 8421 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 8422 8423 SourceLocation CContext) { 8424 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 8425 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty(); 8426 8427 Expr *InnerE = E->IgnoreParenImpCasts(); 8428 // We also want to warn on, e.g., "int i = -1.234" 8429 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 8430 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 8431 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 8432 8433 const bool IsLiteral = 8434 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 8435 8436 llvm::APFloat Value(0.0); 8437 bool IsConstant = 8438 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 8439 if (!IsConstant) { 8440 return DiagnoseImpCast(S, E, T, CContext, 8441 diag::warn_impcast_float_integer, PruneWarnings); 8442 } 8443 8444 bool isExact = false; 8445 8446 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 8447 T->hasUnsignedIntegerRepresentation()); 8448 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 8449 &isExact) == llvm::APFloat::opOK && 8450 isExact) { 8451 if (IsLiteral) return; 8452 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 8453 PruneWarnings); 8454 } 8455 8456 unsigned DiagID = 0; 8457 if (IsLiteral) { 8458 // Warn on floating point literal to integer. 8459 DiagID = diag::warn_impcast_literal_float_to_integer; 8460 } else if (IntegerValue == 0) { 8461 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 8462 return DiagnoseImpCast(S, E, T, CContext, 8463 diag::warn_impcast_float_integer, PruneWarnings); 8464 } 8465 // Warn on non-zero to zero conversion. 8466 DiagID = diag::warn_impcast_float_to_integer_zero; 8467 } else { 8468 if (IntegerValue.isUnsigned()) { 8469 if (!IntegerValue.isMaxValue()) { 8470 return DiagnoseImpCast(S, E, T, CContext, 8471 diag::warn_impcast_float_integer, PruneWarnings); 8472 } 8473 } else { // IntegerValue.isSigned() 8474 if (!IntegerValue.isMaxSignedValue() && 8475 !IntegerValue.isMinSignedValue()) { 8476 return DiagnoseImpCast(S, E, T, CContext, 8477 diag::warn_impcast_float_integer, PruneWarnings); 8478 } 8479 } 8480 // Warn on evaluatable floating point expression to integer conversion. 8481 DiagID = diag::warn_impcast_float_to_integer; 8482 } 8483 8484 // FIXME: Force the precision of the source value down so we don't print 8485 // digits which are usually useless (we don't really care here if we 8486 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 8487 // would automatically print the shortest representation, but it's a bit 8488 // tricky to implement. 8489 SmallString<16> PrettySourceValue; 8490 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 8491 precision = (precision * 59 + 195) / 196; 8492 Value.toString(PrettySourceValue, precision); 8493 8494 SmallString<16> PrettyTargetValue; 8495 if (IsBool) 8496 PrettyTargetValue = Value.isZero() ? "false" : "true"; 8497 else 8498 IntegerValue.toString(PrettyTargetValue); 8499 8500 if (PruneWarnings) { 8501 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8502 S.PDiag(DiagID) 8503 << E->getType() << T.getUnqualifiedType() 8504 << PrettySourceValue << PrettyTargetValue 8505 << E->getSourceRange() << SourceRange(CContext)); 8506 } else { 8507 S.Diag(E->getExprLoc(), DiagID) 8508 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 8509 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 8510 } 8511 } 8512 8513 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 8514 if (!Range.Width) return "0"; 8515 8516 llvm::APSInt ValueInRange = Value; 8517 ValueInRange.setIsSigned(!Range.NonNegative); 8518 ValueInRange = ValueInRange.trunc(Range.Width); 8519 return ValueInRange.toString(10); 8520 } 8521 8522 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 8523 if (!isa<ImplicitCastExpr>(Ex)) 8524 return false; 8525 8526 Expr *InnerE = Ex->IgnoreParenImpCasts(); 8527 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 8528 const Type *Source = 8529 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 8530 if (Target->isDependentType()) 8531 return false; 8532 8533 const BuiltinType *FloatCandidateBT = 8534 dyn_cast<BuiltinType>(ToBool ? Source : Target); 8535 const Type *BoolCandidateType = ToBool ? Target : Source; 8536 8537 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 8538 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 8539 } 8540 8541 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 8542 SourceLocation CC) { 8543 unsigned NumArgs = TheCall->getNumArgs(); 8544 for (unsigned i = 0; i < NumArgs; ++i) { 8545 Expr *CurrA = TheCall->getArg(i); 8546 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 8547 continue; 8548 8549 bool IsSwapped = ((i > 0) && 8550 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 8551 IsSwapped |= ((i < (NumArgs - 1)) && 8552 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 8553 if (IsSwapped) { 8554 // Warn on this floating-point to bool conversion. 8555 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 8556 CurrA->getType(), CC, 8557 diag::warn_impcast_floating_point_to_bool); 8558 } 8559 } 8560 } 8561 8562 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 8563 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 8564 E->getExprLoc())) 8565 return; 8566 8567 // Don't warn on functions which have return type nullptr_t. 8568 if (isa<CallExpr>(E)) 8569 return; 8570 8571 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 8572 const Expr::NullPointerConstantKind NullKind = 8573 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 8574 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 8575 return; 8576 8577 // Return if target type is a safe conversion. 8578 if (T->isAnyPointerType() || T->isBlockPointerType() || 8579 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 8580 return; 8581 8582 SourceLocation Loc = E->getSourceRange().getBegin(); 8583 8584 // Venture through the macro stacks to get to the source of macro arguments. 8585 // The new location is a better location than the complete location that was 8586 // passed in. 8587 while (S.SourceMgr.isMacroArgExpansion(Loc)) 8588 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 8589 8590 while (S.SourceMgr.isMacroArgExpansion(CC)) 8591 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 8592 8593 // __null is usually wrapped in a macro. Go up a macro if that is the case. 8594 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 8595 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 8596 Loc, S.SourceMgr, S.getLangOpts()); 8597 if (MacroName == "NULL") 8598 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 8599 } 8600 8601 // Only warn if the null and context location are in the same macro expansion. 8602 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 8603 return; 8604 8605 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 8606 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 8607 << FixItHint::CreateReplacement(Loc, 8608 S.getFixItZeroLiteralForType(T, Loc)); 8609 } 8610 8611 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8612 ObjCArrayLiteral *ArrayLiteral); 8613 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8614 ObjCDictionaryLiteral *DictionaryLiteral); 8615 8616 /// Check a single element within a collection literal against the 8617 /// target element type. 8618 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 8619 Expr *Element, unsigned ElementKind) { 8620 // Skip a bitcast to 'id' or qualified 'id'. 8621 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 8622 if (ICE->getCastKind() == CK_BitCast && 8623 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 8624 Element = ICE->getSubExpr(); 8625 } 8626 8627 QualType ElementType = Element->getType(); 8628 ExprResult ElementResult(Element); 8629 if (ElementType->getAs<ObjCObjectPointerType>() && 8630 S.CheckSingleAssignmentConstraints(TargetElementType, 8631 ElementResult, 8632 false, false) 8633 != Sema::Compatible) { 8634 S.Diag(Element->getLocStart(), 8635 diag::warn_objc_collection_literal_element) 8636 << ElementType << ElementKind << TargetElementType 8637 << Element->getSourceRange(); 8638 } 8639 8640 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 8641 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 8642 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 8643 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 8644 } 8645 8646 /// Check an Objective-C array literal being converted to the given 8647 /// target type. 8648 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8649 ObjCArrayLiteral *ArrayLiteral) { 8650 if (!S.NSArrayDecl) 8651 return; 8652 8653 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8654 if (!TargetObjCPtr) 8655 return; 8656 8657 if (TargetObjCPtr->isUnspecialized() || 8658 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8659 != S.NSArrayDecl->getCanonicalDecl()) 8660 return; 8661 8662 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8663 if (TypeArgs.size() != 1) 8664 return; 8665 8666 QualType TargetElementType = TypeArgs[0]; 8667 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 8668 checkObjCCollectionLiteralElement(S, TargetElementType, 8669 ArrayLiteral->getElement(I), 8670 0); 8671 } 8672 } 8673 8674 /// Check an Objective-C dictionary literal being converted to the given 8675 /// target type. 8676 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8677 ObjCDictionaryLiteral *DictionaryLiteral) { 8678 if (!S.NSDictionaryDecl) 8679 return; 8680 8681 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8682 if (!TargetObjCPtr) 8683 return; 8684 8685 if (TargetObjCPtr->isUnspecialized() || 8686 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8687 != S.NSDictionaryDecl->getCanonicalDecl()) 8688 return; 8689 8690 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8691 if (TypeArgs.size() != 2) 8692 return; 8693 8694 QualType TargetKeyType = TypeArgs[0]; 8695 QualType TargetObjectType = TypeArgs[1]; 8696 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 8697 auto Element = DictionaryLiteral->getKeyValueElement(I); 8698 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 8699 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 8700 } 8701 } 8702 8703 // Helper function to filter out cases for constant width constant conversion. 8704 // Don't warn on char array initialization or for non-decimal values. 8705 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 8706 SourceLocation CC) { 8707 // If initializing from a constant, and the constant starts with '0', 8708 // then it is a binary, octal, or hexadecimal. Allow these constants 8709 // to fill all the bits, even if there is a sign change. 8710 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 8711 const char FirstLiteralCharacter = 8712 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 8713 if (FirstLiteralCharacter == '0') 8714 return false; 8715 } 8716 8717 // If the CC location points to a '{', and the type is char, then assume 8718 // assume it is an array initialization. 8719 if (CC.isValid() && T->isCharType()) { 8720 const char FirstContextCharacter = 8721 S.getSourceManager().getCharacterData(CC)[0]; 8722 if (FirstContextCharacter == '{') 8723 return false; 8724 } 8725 8726 return true; 8727 } 8728 8729 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 8730 SourceLocation CC, bool *ICContext = nullptr) { 8731 if (E->isTypeDependent() || E->isValueDependent()) return; 8732 8733 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 8734 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 8735 if (Source == Target) return; 8736 if (Target->isDependentType()) return; 8737 8738 // If the conversion context location is invalid don't complain. We also 8739 // don't want to emit a warning if the issue occurs from the expansion of 8740 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 8741 // delay this check as long as possible. Once we detect we are in that 8742 // scenario, we just return. 8743 if (CC.isInvalid()) 8744 return; 8745 8746 // Diagnose implicit casts to bool. 8747 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 8748 if (isa<StringLiteral>(E)) 8749 // Warn on string literal to bool. Checks for string literals in logical 8750 // and expressions, for instance, assert(0 && "error here"), are 8751 // prevented by a check in AnalyzeImplicitConversions(). 8752 return DiagnoseImpCast(S, E, T, CC, 8753 diag::warn_impcast_string_literal_to_bool); 8754 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 8755 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 8756 // This covers the literal expressions that evaluate to Objective-C 8757 // objects. 8758 return DiagnoseImpCast(S, E, T, CC, 8759 diag::warn_impcast_objective_c_literal_to_bool); 8760 } 8761 if (Source->isPointerType() || Source->canDecayToPointerType()) { 8762 // Warn on pointer to bool conversion that is always true. 8763 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 8764 SourceRange(CC)); 8765 } 8766 } 8767 8768 // Check implicit casts from Objective-C collection literals to specialized 8769 // collection types, e.g., NSArray<NSString *> *. 8770 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 8771 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 8772 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 8773 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 8774 8775 // Strip vector types. 8776 if (isa<VectorType>(Source)) { 8777 if (!isa<VectorType>(Target)) { 8778 if (S.SourceMgr.isInSystemMacro(CC)) 8779 return; 8780 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 8781 } 8782 8783 // If the vector cast is cast between two vectors of the same size, it is 8784 // a bitcast, not a conversion. 8785 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 8786 return; 8787 8788 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 8789 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 8790 } 8791 if (auto VecTy = dyn_cast<VectorType>(Target)) 8792 Target = VecTy->getElementType().getTypePtr(); 8793 8794 // Strip complex types. 8795 if (isa<ComplexType>(Source)) { 8796 if (!isa<ComplexType>(Target)) { 8797 if (S.SourceMgr.isInSystemMacro(CC)) 8798 return; 8799 8800 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 8801 } 8802 8803 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 8804 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 8805 } 8806 8807 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 8808 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 8809 8810 // If the source is floating point... 8811 if (SourceBT && SourceBT->isFloatingPoint()) { 8812 // ...and the target is floating point... 8813 if (TargetBT && TargetBT->isFloatingPoint()) { 8814 // ...then warn if we're dropping FP rank. 8815 8816 // Builtin FP kinds are ordered by increasing FP rank. 8817 if (SourceBT->getKind() > TargetBT->getKind()) { 8818 // Don't warn about float constants that are precisely 8819 // representable in the target type. 8820 Expr::EvalResult result; 8821 if (E->EvaluateAsRValue(result, S.Context)) { 8822 // Value might be a float, a float vector, or a float complex. 8823 if (IsSameFloatAfterCast(result.Val, 8824 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 8825 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 8826 return; 8827 } 8828 8829 if (S.SourceMgr.isInSystemMacro(CC)) 8830 return; 8831 8832 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 8833 } 8834 // ... or possibly if we're increasing rank, too 8835 else if (TargetBT->getKind() > SourceBT->getKind()) { 8836 if (S.SourceMgr.isInSystemMacro(CC)) 8837 return; 8838 8839 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 8840 } 8841 return; 8842 } 8843 8844 // If the target is integral, always warn. 8845 if (TargetBT && TargetBT->isInteger()) { 8846 if (S.SourceMgr.isInSystemMacro(CC)) 8847 return; 8848 8849 DiagnoseFloatingImpCast(S, E, T, CC); 8850 } 8851 8852 // Detect the case where a call result is converted from floating-point to 8853 // to bool, and the final argument to the call is converted from bool, to 8854 // discover this typo: 8855 // 8856 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 8857 // 8858 // FIXME: This is an incredibly special case; is there some more general 8859 // way to detect this class of misplaced-parentheses bug? 8860 if (Target->isBooleanType() && isa<CallExpr>(E)) { 8861 // Check last argument of function call to see if it is an 8862 // implicit cast from a type matching the type the result 8863 // is being cast to. 8864 CallExpr *CEx = cast<CallExpr>(E); 8865 if (unsigned NumArgs = CEx->getNumArgs()) { 8866 Expr *LastA = CEx->getArg(NumArgs - 1); 8867 Expr *InnerE = LastA->IgnoreParenImpCasts(); 8868 if (isa<ImplicitCastExpr>(LastA) && 8869 InnerE->getType()->isBooleanType()) { 8870 // Warn on this floating-point to bool conversion 8871 DiagnoseImpCast(S, E, T, CC, 8872 diag::warn_impcast_floating_point_to_bool); 8873 } 8874 } 8875 } 8876 return; 8877 } 8878 8879 DiagnoseNullConversion(S, E, T, CC); 8880 8881 S.DiscardMisalignedMemberAddress(Target, E); 8882 8883 if (!Source->isIntegerType() || !Target->isIntegerType()) 8884 return; 8885 8886 // TODO: remove this early return once the false positives for constant->bool 8887 // in templates, macros, etc, are reduced or removed. 8888 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 8889 return; 8890 8891 IntRange SourceRange = GetExprRange(S.Context, E); 8892 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 8893 8894 if (SourceRange.Width > TargetRange.Width) { 8895 // If the source is a constant, use a default-on diagnostic. 8896 // TODO: this should happen for bitfield stores, too. 8897 llvm::APSInt Value(32); 8898 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 8899 if (S.SourceMgr.isInSystemMacro(CC)) 8900 return; 8901 8902 std::string PrettySourceValue = Value.toString(10); 8903 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 8904 8905 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8906 S.PDiag(diag::warn_impcast_integer_precision_constant) 8907 << PrettySourceValue << PrettyTargetValue 8908 << E->getType() << T << E->getSourceRange() 8909 << clang::SourceRange(CC)); 8910 return; 8911 } 8912 8913 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 8914 if (S.SourceMgr.isInSystemMacro(CC)) 8915 return; 8916 8917 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 8918 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 8919 /* pruneControlFlow */ true); 8920 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 8921 } 8922 8923 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 8924 SourceRange.NonNegative && Source->isSignedIntegerType()) { 8925 // Warn when doing a signed to signed conversion, warn if the positive 8926 // source value is exactly the width of the target type, which will 8927 // cause a negative value to be stored. 8928 8929 llvm::APSInt Value; 8930 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 8931 !S.SourceMgr.isInSystemMacro(CC)) { 8932 if (isSameWidthConstantConversion(S, E, T, CC)) { 8933 std::string PrettySourceValue = Value.toString(10); 8934 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 8935 8936 S.DiagRuntimeBehavior( 8937 E->getExprLoc(), E, 8938 S.PDiag(diag::warn_impcast_integer_precision_constant) 8939 << PrettySourceValue << PrettyTargetValue << E->getType() << T 8940 << E->getSourceRange() << clang::SourceRange(CC)); 8941 return; 8942 } 8943 } 8944 8945 // Fall through for non-constants to give a sign conversion warning. 8946 } 8947 8948 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 8949 (!TargetRange.NonNegative && SourceRange.NonNegative && 8950 SourceRange.Width == TargetRange.Width)) { 8951 if (S.SourceMgr.isInSystemMacro(CC)) 8952 return; 8953 8954 unsigned DiagID = diag::warn_impcast_integer_sign; 8955 8956 // Traditionally, gcc has warned about this under -Wsign-compare. 8957 // We also want to warn about it in -Wconversion. 8958 // So if -Wconversion is off, use a completely identical diagnostic 8959 // in the sign-compare group. 8960 // The conditional-checking code will 8961 if (ICContext) { 8962 DiagID = diag::warn_impcast_integer_sign_conditional; 8963 *ICContext = true; 8964 } 8965 8966 return DiagnoseImpCast(S, E, T, CC, DiagID); 8967 } 8968 8969 // Diagnose conversions between different enumeration types. 8970 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 8971 // type, to give us better diagnostics. 8972 QualType SourceType = E->getType(); 8973 if (!S.getLangOpts().CPlusPlus) { 8974 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8975 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 8976 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 8977 SourceType = S.Context.getTypeDeclType(Enum); 8978 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 8979 } 8980 } 8981 8982 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 8983 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 8984 if (SourceEnum->getDecl()->hasNameForLinkage() && 8985 TargetEnum->getDecl()->hasNameForLinkage() && 8986 SourceEnum != TargetEnum) { 8987 if (S.SourceMgr.isInSystemMacro(CC)) 8988 return; 8989 8990 return DiagnoseImpCast(S, E, SourceType, T, CC, 8991 diag::warn_impcast_different_enum_types); 8992 } 8993 } 8994 8995 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 8996 SourceLocation CC, QualType T); 8997 8998 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 8999 SourceLocation CC, bool &ICContext) { 9000 E = E->IgnoreParenImpCasts(); 9001 9002 if (isa<ConditionalOperator>(E)) 9003 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9004 9005 AnalyzeImplicitConversions(S, E, CC); 9006 if (E->getType() != T) 9007 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9008 } 9009 9010 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9011 SourceLocation CC, QualType T) { 9012 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9013 9014 bool Suspicious = false; 9015 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9016 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9017 9018 // If -Wconversion would have warned about either of the candidates 9019 // for a signedness conversion to the context type... 9020 if (!Suspicious) return; 9021 9022 // ...but it's currently ignored... 9023 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9024 return; 9025 9026 // ...then check whether it would have warned about either of the 9027 // candidates for a signedness conversion to the condition type. 9028 if (E->getType() == T) return; 9029 9030 Suspicious = false; 9031 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9032 E->getType(), CC, &Suspicious); 9033 if (!Suspicious) 9034 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9035 E->getType(), CC, &Suspicious); 9036 } 9037 9038 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9039 /// Input argument E is a logical expression. 9040 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9041 if (S.getLangOpts().Bool) 9042 return; 9043 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9044 } 9045 9046 /// AnalyzeImplicitConversions - Find and report any interesting 9047 /// implicit conversions in the given expression. There are a couple 9048 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9049 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9050 QualType T = OrigE->getType(); 9051 Expr *E = OrigE->IgnoreParenImpCasts(); 9052 9053 if (E->isTypeDependent() || E->isValueDependent()) 9054 return; 9055 9056 // For conditional operators, we analyze the arguments as if they 9057 // were being fed directly into the output. 9058 if (isa<ConditionalOperator>(E)) { 9059 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9060 CheckConditionalOperator(S, CO, CC, T); 9061 return; 9062 } 9063 9064 // Check implicit argument conversions for function calls. 9065 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9066 CheckImplicitArgumentConversions(S, Call, CC); 9067 9068 // Go ahead and check any implicit conversions we might have skipped. 9069 // The non-canonical typecheck is just an optimization; 9070 // CheckImplicitConversion will filter out dead implicit conversions. 9071 if (E->getType() != T) 9072 CheckImplicitConversion(S, E, T, CC); 9073 9074 // Now continue drilling into this expression. 9075 9076 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9077 // The bound subexpressions in a PseudoObjectExpr are not reachable 9078 // as transitive children. 9079 // FIXME: Use a more uniform representation for this. 9080 for (auto *SE : POE->semantics()) 9081 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9082 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9083 } 9084 9085 // Skip past explicit casts. 9086 if (isa<ExplicitCastExpr>(E)) { 9087 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9088 return AnalyzeImplicitConversions(S, E, CC); 9089 } 9090 9091 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9092 // Do a somewhat different check with comparison operators. 9093 if (BO->isComparisonOp()) 9094 return AnalyzeComparison(S, BO); 9095 9096 // And with simple assignments. 9097 if (BO->getOpcode() == BO_Assign) 9098 return AnalyzeAssignment(S, BO); 9099 } 9100 9101 // These break the otherwise-useful invariant below. Fortunately, 9102 // we don't really need to recurse into them, because any internal 9103 // expressions should have been analyzed already when they were 9104 // built into statements. 9105 if (isa<StmtExpr>(E)) return; 9106 9107 // Don't descend into unevaluated contexts. 9108 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9109 9110 // Now just recurse over the expression's children. 9111 CC = E->getExprLoc(); 9112 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9113 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9114 for (Stmt *SubStmt : E->children()) { 9115 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9116 if (!ChildExpr) 9117 continue; 9118 9119 if (IsLogicalAndOperator && 9120 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9121 // Ignore checking string literals that are in logical and operators. 9122 // This is a common pattern for asserts. 9123 continue; 9124 AnalyzeImplicitConversions(S, ChildExpr, CC); 9125 } 9126 9127 if (BO && BO->isLogicalOp()) { 9128 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9129 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9130 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9131 9132 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9133 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9134 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9135 } 9136 9137 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9138 if (U->getOpcode() == UO_LNot) 9139 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9140 } 9141 9142 } // end anonymous namespace 9143 9144 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 9145 unsigned Start, unsigned End) { 9146 bool IllegalParams = false; 9147 for (unsigned I = Start; I <= End; ++I) { 9148 QualType Ty = TheCall->getArg(I)->getType(); 9149 // Taking into account implicit conversions, 9150 // allow any integer within 32 bits range 9151 if (!Ty->isIntegerType() || 9152 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) { 9153 S.Diag(TheCall->getArg(I)->getLocStart(), 9154 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9155 IllegalParams = true; 9156 } 9157 // Potentially emit standard warnings for implicit conversions if enabled 9158 // using -Wconversion. 9159 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy, 9160 TheCall->getArg(I)->getLocStart()); 9161 } 9162 return IllegalParams; 9163 } 9164 9165 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9166 // Returns true when emitting a warning about taking the address of a reference. 9167 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9168 const PartialDiagnostic &PD) { 9169 E = E->IgnoreParenImpCasts(); 9170 9171 const FunctionDecl *FD = nullptr; 9172 9173 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9174 if (!DRE->getDecl()->getType()->isReferenceType()) 9175 return false; 9176 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9177 if (!M->getMemberDecl()->getType()->isReferenceType()) 9178 return false; 9179 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9180 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9181 return false; 9182 FD = Call->getDirectCallee(); 9183 } else { 9184 return false; 9185 } 9186 9187 SemaRef.Diag(E->getExprLoc(), PD); 9188 9189 // If possible, point to location of function. 9190 if (FD) { 9191 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9192 } 9193 9194 return true; 9195 } 9196 9197 // Returns true if the SourceLocation is expanded from any macro body. 9198 // Returns false if the SourceLocation is invalid, is from not in a macro 9199 // expansion, or is from expanded from a top-level macro argument. 9200 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9201 if (Loc.isInvalid()) 9202 return false; 9203 9204 while (Loc.isMacroID()) { 9205 if (SM.isMacroBodyExpansion(Loc)) 9206 return true; 9207 Loc = SM.getImmediateMacroCallerLoc(Loc); 9208 } 9209 9210 return false; 9211 } 9212 9213 /// \brief Diagnose pointers that are always non-null. 9214 /// \param E the expression containing the pointer 9215 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9216 /// compared to a null pointer 9217 /// \param IsEqual True when the comparison is equal to a null pointer 9218 /// \param Range Extra SourceRange to highlight in the diagnostic 9219 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9220 Expr::NullPointerConstantKind NullKind, 9221 bool IsEqual, SourceRange Range) { 9222 if (!E) 9223 return; 9224 9225 // Don't warn inside macros. 9226 if (E->getExprLoc().isMacroID()) { 9227 const SourceManager &SM = getSourceManager(); 9228 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9229 IsInAnyMacroBody(SM, Range.getBegin())) 9230 return; 9231 } 9232 E = E->IgnoreImpCasts(); 9233 9234 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9235 9236 if (isa<CXXThisExpr>(E)) { 9237 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9238 : diag::warn_this_bool_conversion; 9239 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9240 return; 9241 } 9242 9243 bool IsAddressOf = false; 9244 9245 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9246 if (UO->getOpcode() != UO_AddrOf) 9247 return; 9248 IsAddressOf = true; 9249 E = UO->getSubExpr(); 9250 } 9251 9252 if (IsAddressOf) { 9253 unsigned DiagID = IsCompare 9254 ? diag::warn_address_of_reference_null_compare 9255 : diag::warn_address_of_reference_bool_conversion; 9256 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 9257 << IsEqual; 9258 if (CheckForReference(*this, E, PD)) { 9259 return; 9260 } 9261 } 9262 9263 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 9264 bool IsParam = isa<NonNullAttr>(NonnullAttr); 9265 std::string Str; 9266 llvm::raw_string_ostream S(Str); 9267 E->printPretty(S, nullptr, getPrintingPolicy()); 9268 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 9269 : diag::warn_cast_nonnull_to_bool; 9270 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 9271 << E->getSourceRange() << Range << IsEqual; 9272 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 9273 }; 9274 9275 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 9276 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 9277 if (auto *Callee = Call->getDirectCallee()) { 9278 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 9279 ComplainAboutNonnullParamOrCall(A); 9280 return; 9281 } 9282 } 9283 } 9284 9285 // Expect to find a single Decl. Skip anything more complicated. 9286 ValueDecl *D = nullptr; 9287 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 9288 D = R->getDecl(); 9289 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9290 D = M->getMemberDecl(); 9291 } 9292 9293 // Weak Decls can be null. 9294 if (!D || D->isWeak()) 9295 return; 9296 9297 // Check for parameter decl with nonnull attribute 9298 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 9299 if (getCurFunction() && 9300 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 9301 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 9302 ComplainAboutNonnullParamOrCall(A); 9303 return; 9304 } 9305 9306 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 9307 auto ParamIter = llvm::find(FD->parameters(), PV); 9308 assert(ParamIter != FD->param_end()); 9309 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 9310 9311 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 9312 if (!NonNull->args_size()) { 9313 ComplainAboutNonnullParamOrCall(NonNull); 9314 return; 9315 } 9316 9317 for (unsigned ArgNo : NonNull->args()) { 9318 if (ArgNo == ParamNo) { 9319 ComplainAboutNonnullParamOrCall(NonNull); 9320 return; 9321 } 9322 } 9323 } 9324 } 9325 } 9326 } 9327 9328 QualType T = D->getType(); 9329 const bool IsArray = T->isArrayType(); 9330 const bool IsFunction = T->isFunctionType(); 9331 9332 // Address of function is used to silence the function warning. 9333 if (IsAddressOf && IsFunction) { 9334 return; 9335 } 9336 9337 // Found nothing. 9338 if (!IsAddressOf && !IsFunction && !IsArray) 9339 return; 9340 9341 // Pretty print the expression for the diagnostic. 9342 std::string Str; 9343 llvm::raw_string_ostream S(Str); 9344 E->printPretty(S, nullptr, getPrintingPolicy()); 9345 9346 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 9347 : diag::warn_impcast_pointer_to_bool; 9348 enum { 9349 AddressOf, 9350 FunctionPointer, 9351 ArrayPointer 9352 } DiagType; 9353 if (IsAddressOf) 9354 DiagType = AddressOf; 9355 else if (IsFunction) 9356 DiagType = FunctionPointer; 9357 else if (IsArray) 9358 DiagType = ArrayPointer; 9359 else 9360 llvm_unreachable("Could not determine diagnostic."); 9361 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 9362 << Range << IsEqual; 9363 9364 if (!IsFunction) 9365 return; 9366 9367 // Suggest '&' to silence the function warning. 9368 Diag(E->getExprLoc(), diag::note_function_warning_silence) 9369 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 9370 9371 // Check to see if '()' fixit should be emitted. 9372 QualType ReturnType; 9373 UnresolvedSet<4> NonTemplateOverloads; 9374 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 9375 if (ReturnType.isNull()) 9376 return; 9377 9378 if (IsCompare) { 9379 // There are two cases here. If there is null constant, the only suggest 9380 // for a pointer return type. If the null is 0, then suggest if the return 9381 // type is a pointer or an integer type. 9382 if (!ReturnType->isPointerType()) { 9383 if (NullKind == Expr::NPCK_ZeroExpression || 9384 NullKind == Expr::NPCK_ZeroLiteral) { 9385 if (!ReturnType->isIntegerType()) 9386 return; 9387 } else { 9388 return; 9389 } 9390 } 9391 } else { // !IsCompare 9392 // For function to bool, only suggest if the function pointer has bool 9393 // return type. 9394 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 9395 return; 9396 } 9397 Diag(E->getExprLoc(), diag::note_function_to_function_call) 9398 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 9399 } 9400 9401 /// Diagnoses "dangerous" implicit conversions within the given 9402 /// expression (which is a full expression). Implements -Wconversion 9403 /// and -Wsign-compare. 9404 /// 9405 /// \param CC the "context" location of the implicit conversion, i.e. 9406 /// the most location of the syntactic entity requiring the implicit 9407 /// conversion 9408 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 9409 // Don't diagnose in unevaluated contexts. 9410 if (isUnevaluatedContext()) 9411 return; 9412 9413 // Don't diagnose for value- or type-dependent expressions. 9414 if (E->isTypeDependent() || E->isValueDependent()) 9415 return; 9416 9417 // Check for array bounds violations in cases where the check isn't triggered 9418 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 9419 // ArraySubscriptExpr is on the RHS of a variable initialization. 9420 CheckArrayAccess(E); 9421 9422 // This is not the right CC for (e.g.) a variable initialization. 9423 AnalyzeImplicitConversions(*this, E, CC); 9424 } 9425 9426 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9427 /// Input argument E is a logical expression. 9428 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 9429 ::CheckBoolLikeConversion(*this, E, CC); 9430 } 9431 9432 /// Diagnose when expression is an integer constant expression and its evaluation 9433 /// results in integer overflow 9434 void Sema::CheckForIntOverflow (Expr *E) { 9435 // Use a work list to deal with nested struct initializers. 9436 SmallVector<Expr *, 2> Exprs(1, E); 9437 9438 do { 9439 Expr *E = Exprs.pop_back_val(); 9440 9441 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 9442 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 9443 continue; 9444 } 9445 9446 if (auto InitList = dyn_cast<InitListExpr>(E)) 9447 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 9448 } while (!Exprs.empty()); 9449 } 9450 9451 namespace { 9452 /// \brief Visitor for expressions which looks for unsequenced operations on the 9453 /// same object. 9454 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 9455 typedef EvaluatedExprVisitor<SequenceChecker> Base; 9456 9457 /// \brief A tree of sequenced regions within an expression. Two regions are 9458 /// unsequenced if one is an ancestor or a descendent of the other. When we 9459 /// finish processing an expression with sequencing, such as a comma 9460 /// expression, we fold its tree nodes into its parent, since they are 9461 /// unsequenced with respect to nodes we will visit later. 9462 class SequenceTree { 9463 struct Value { 9464 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 9465 unsigned Parent : 31; 9466 unsigned Merged : 1; 9467 }; 9468 SmallVector<Value, 8> Values; 9469 9470 public: 9471 /// \brief A region within an expression which may be sequenced with respect 9472 /// to some other region. 9473 class Seq { 9474 explicit Seq(unsigned N) : Index(N) {} 9475 unsigned Index; 9476 friend class SequenceTree; 9477 public: 9478 Seq() : Index(0) {} 9479 }; 9480 9481 SequenceTree() { Values.push_back(Value(0)); } 9482 Seq root() const { return Seq(0); } 9483 9484 /// \brief Create a new sequence of operations, which is an unsequenced 9485 /// subset of \p Parent. This sequence of operations is sequenced with 9486 /// respect to other children of \p Parent. 9487 Seq allocate(Seq Parent) { 9488 Values.push_back(Value(Parent.Index)); 9489 return Seq(Values.size() - 1); 9490 } 9491 9492 /// \brief Merge a sequence of operations into its parent. 9493 void merge(Seq S) { 9494 Values[S.Index].Merged = true; 9495 } 9496 9497 /// \brief Determine whether two operations are unsequenced. This operation 9498 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 9499 /// should have been merged into its parent as appropriate. 9500 bool isUnsequenced(Seq Cur, Seq Old) { 9501 unsigned C = representative(Cur.Index); 9502 unsigned Target = representative(Old.Index); 9503 while (C >= Target) { 9504 if (C == Target) 9505 return true; 9506 C = Values[C].Parent; 9507 } 9508 return false; 9509 } 9510 9511 private: 9512 /// \brief Pick a representative for a sequence. 9513 unsigned representative(unsigned K) { 9514 if (Values[K].Merged) 9515 // Perform path compression as we go. 9516 return Values[K].Parent = representative(Values[K].Parent); 9517 return K; 9518 } 9519 }; 9520 9521 /// An object for which we can track unsequenced uses. 9522 typedef NamedDecl *Object; 9523 9524 /// Different flavors of object usage which we track. We only track the 9525 /// least-sequenced usage of each kind. 9526 enum UsageKind { 9527 /// A read of an object. Multiple unsequenced reads are OK. 9528 UK_Use, 9529 /// A modification of an object which is sequenced before the value 9530 /// computation of the expression, such as ++n in C++. 9531 UK_ModAsValue, 9532 /// A modification of an object which is not sequenced before the value 9533 /// computation of the expression, such as n++. 9534 UK_ModAsSideEffect, 9535 9536 UK_Count = UK_ModAsSideEffect + 1 9537 }; 9538 9539 struct Usage { 9540 Usage() : Use(nullptr), Seq() {} 9541 Expr *Use; 9542 SequenceTree::Seq Seq; 9543 }; 9544 9545 struct UsageInfo { 9546 UsageInfo() : Diagnosed(false) {} 9547 Usage Uses[UK_Count]; 9548 /// Have we issued a diagnostic for this variable already? 9549 bool Diagnosed; 9550 }; 9551 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 9552 9553 Sema &SemaRef; 9554 /// Sequenced regions within the expression. 9555 SequenceTree Tree; 9556 /// Declaration modifications and references which we have seen. 9557 UsageInfoMap UsageMap; 9558 /// The region we are currently within. 9559 SequenceTree::Seq Region; 9560 /// Filled in with declarations which were modified as a side-effect 9561 /// (that is, post-increment operations). 9562 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 9563 /// Expressions to check later. We defer checking these to reduce 9564 /// stack usage. 9565 SmallVectorImpl<Expr *> &WorkList; 9566 9567 /// RAII object wrapping the visitation of a sequenced subexpression of an 9568 /// expression. At the end of this process, the side-effects of the evaluation 9569 /// become sequenced with respect to the value computation of the result, so 9570 /// we downgrade any UK_ModAsSideEffect within the evaluation to 9571 /// UK_ModAsValue. 9572 struct SequencedSubexpression { 9573 SequencedSubexpression(SequenceChecker &Self) 9574 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 9575 Self.ModAsSideEffect = &ModAsSideEffect; 9576 } 9577 ~SequencedSubexpression() { 9578 for (auto &M : llvm::reverse(ModAsSideEffect)) { 9579 UsageInfo &U = Self.UsageMap[M.first]; 9580 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 9581 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 9582 SideEffectUsage = M.second; 9583 } 9584 Self.ModAsSideEffect = OldModAsSideEffect; 9585 } 9586 9587 SequenceChecker &Self; 9588 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 9589 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 9590 }; 9591 9592 /// RAII object wrapping the visitation of a subexpression which we might 9593 /// choose to evaluate as a constant. If any subexpression is evaluated and 9594 /// found to be non-constant, this allows us to suppress the evaluation of 9595 /// the outer expression. 9596 class EvaluationTracker { 9597 public: 9598 EvaluationTracker(SequenceChecker &Self) 9599 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 9600 Self.EvalTracker = this; 9601 } 9602 ~EvaluationTracker() { 9603 Self.EvalTracker = Prev; 9604 if (Prev) 9605 Prev->EvalOK &= EvalOK; 9606 } 9607 9608 bool evaluate(const Expr *E, bool &Result) { 9609 if (!EvalOK || E->isValueDependent()) 9610 return false; 9611 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 9612 return EvalOK; 9613 } 9614 9615 private: 9616 SequenceChecker &Self; 9617 EvaluationTracker *Prev; 9618 bool EvalOK; 9619 } *EvalTracker; 9620 9621 /// \brief Find the object which is produced by the specified expression, 9622 /// if any. 9623 Object getObject(Expr *E, bool Mod) const { 9624 E = E->IgnoreParenCasts(); 9625 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9626 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 9627 return getObject(UO->getSubExpr(), Mod); 9628 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9629 if (BO->getOpcode() == BO_Comma) 9630 return getObject(BO->getRHS(), Mod); 9631 if (Mod && BO->isAssignmentOp()) 9632 return getObject(BO->getLHS(), Mod); 9633 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9634 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 9635 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 9636 return ME->getMemberDecl(); 9637 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9638 // FIXME: If this is a reference, map through to its value. 9639 return DRE->getDecl(); 9640 return nullptr; 9641 } 9642 9643 /// \brief Note that an object was modified or used by an expression. 9644 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 9645 Usage &U = UI.Uses[UK]; 9646 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 9647 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 9648 ModAsSideEffect->push_back(std::make_pair(O, U)); 9649 U.Use = Ref; 9650 U.Seq = Region; 9651 } 9652 } 9653 /// \brief Check whether a modification or use conflicts with a prior usage. 9654 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 9655 bool IsModMod) { 9656 if (UI.Diagnosed) 9657 return; 9658 9659 const Usage &U = UI.Uses[OtherKind]; 9660 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 9661 return; 9662 9663 Expr *Mod = U.Use; 9664 Expr *ModOrUse = Ref; 9665 if (OtherKind == UK_Use) 9666 std::swap(Mod, ModOrUse); 9667 9668 SemaRef.Diag(Mod->getExprLoc(), 9669 IsModMod ? diag::warn_unsequenced_mod_mod 9670 : diag::warn_unsequenced_mod_use) 9671 << O << SourceRange(ModOrUse->getExprLoc()); 9672 UI.Diagnosed = true; 9673 } 9674 9675 void notePreUse(Object O, Expr *Use) { 9676 UsageInfo &U = UsageMap[O]; 9677 // Uses conflict with other modifications. 9678 checkUsage(O, U, Use, UK_ModAsValue, false); 9679 } 9680 void notePostUse(Object O, Expr *Use) { 9681 UsageInfo &U = UsageMap[O]; 9682 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 9683 addUsage(U, O, Use, UK_Use); 9684 } 9685 9686 void notePreMod(Object O, Expr *Mod) { 9687 UsageInfo &U = UsageMap[O]; 9688 // Modifications conflict with other modifications and with uses. 9689 checkUsage(O, U, Mod, UK_ModAsValue, true); 9690 checkUsage(O, U, Mod, UK_Use, false); 9691 } 9692 void notePostMod(Object O, Expr *Use, UsageKind UK) { 9693 UsageInfo &U = UsageMap[O]; 9694 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 9695 addUsage(U, O, Use, UK); 9696 } 9697 9698 public: 9699 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 9700 : Base(S.Context), SemaRef(S), Region(Tree.root()), 9701 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 9702 Visit(E); 9703 } 9704 9705 void VisitStmt(Stmt *S) { 9706 // Skip all statements which aren't expressions for now. 9707 } 9708 9709 void VisitExpr(Expr *E) { 9710 // By default, just recurse to evaluated subexpressions. 9711 Base::VisitStmt(E); 9712 } 9713 9714 void VisitCastExpr(CastExpr *E) { 9715 Object O = Object(); 9716 if (E->getCastKind() == CK_LValueToRValue) 9717 O = getObject(E->getSubExpr(), false); 9718 9719 if (O) 9720 notePreUse(O, E); 9721 VisitExpr(E); 9722 if (O) 9723 notePostUse(O, E); 9724 } 9725 9726 void VisitBinComma(BinaryOperator *BO) { 9727 // C++11 [expr.comma]p1: 9728 // Every value computation and side effect associated with the left 9729 // expression is sequenced before every value computation and side 9730 // effect associated with the right expression. 9731 SequenceTree::Seq LHS = Tree.allocate(Region); 9732 SequenceTree::Seq RHS = Tree.allocate(Region); 9733 SequenceTree::Seq OldRegion = Region; 9734 9735 { 9736 SequencedSubexpression SeqLHS(*this); 9737 Region = LHS; 9738 Visit(BO->getLHS()); 9739 } 9740 9741 Region = RHS; 9742 Visit(BO->getRHS()); 9743 9744 Region = OldRegion; 9745 9746 // Forget that LHS and RHS are sequenced. They are both unsequenced 9747 // with respect to other stuff. 9748 Tree.merge(LHS); 9749 Tree.merge(RHS); 9750 } 9751 9752 void VisitBinAssign(BinaryOperator *BO) { 9753 // The modification is sequenced after the value computation of the LHS 9754 // and RHS, so check it before inspecting the operands and update the 9755 // map afterwards. 9756 Object O = getObject(BO->getLHS(), true); 9757 if (!O) 9758 return VisitExpr(BO); 9759 9760 notePreMod(O, BO); 9761 9762 // C++11 [expr.ass]p7: 9763 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 9764 // only once. 9765 // 9766 // Therefore, for a compound assignment operator, O is considered used 9767 // everywhere except within the evaluation of E1 itself. 9768 if (isa<CompoundAssignOperator>(BO)) 9769 notePreUse(O, BO); 9770 9771 Visit(BO->getLHS()); 9772 9773 if (isa<CompoundAssignOperator>(BO)) 9774 notePostUse(O, BO); 9775 9776 Visit(BO->getRHS()); 9777 9778 // C++11 [expr.ass]p1: 9779 // the assignment is sequenced [...] before the value computation of the 9780 // assignment expression. 9781 // C11 6.5.16/3 has no such rule. 9782 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 9783 : UK_ModAsSideEffect); 9784 } 9785 9786 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 9787 VisitBinAssign(CAO); 9788 } 9789 9790 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 9791 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 9792 void VisitUnaryPreIncDec(UnaryOperator *UO) { 9793 Object O = getObject(UO->getSubExpr(), true); 9794 if (!O) 9795 return VisitExpr(UO); 9796 9797 notePreMod(O, UO); 9798 Visit(UO->getSubExpr()); 9799 // C++11 [expr.pre.incr]p1: 9800 // the expression ++x is equivalent to x+=1 9801 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 9802 : UK_ModAsSideEffect); 9803 } 9804 9805 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 9806 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 9807 void VisitUnaryPostIncDec(UnaryOperator *UO) { 9808 Object O = getObject(UO->getSubExpr(), true); 9809 if (!O) 9810 return VisitExpr(UO); 9811 9812 notePreMod(O, UO); 9813 Visit(UO->getSubExpr()); 9814 notePostMod(O, UO, UK_ModAsSideEffect); 9815 } 9816 9817 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 9818 void VisitBinLOr(BinaryOperator *BO) { 9819 // The side-effects of the LHS of an '&&' are sequenced before the 9820 // value computation of the RHS, and hence before the value computation 9821 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 9822 // as if they were unconditionally sequenced. 9823 EvaluationTracker Eval(*this); 9824 { 9825 SequencedSubexpression Sequenced(*this); 9826 Visit(BO->getLHS()); 9827 } 9828 9829 bool Result; 9830 if (Eval.evaluate(BO->getLHS(), Result)) { 9831 if (!Result) 9832 Visit(BO->getRHS()); 9833 } else { 9834 // Check for unsequenced operations in the RHS, treating it as an 9835 // entirely separate evaluation. 9836 // 9837 // FIXME: If there are operations in the RHS which are unsequenced 9838 // with respect to operations outside the RHS, and those operations 9839 // are unconditionally evaluated, diagnose them. 9840 WorkList.push_back(BO->getRHS()); 9841 } 9842 } 9843 void VisitBinLAnd(BinaryOperator *BO) { 9844 EvaluationTracker Eval(*this); 9845 { 9846 SequencedSubexpression Sequenced(*this); 9847 Visit(BO->getLHS()); 9848 } 9849 9850 bool Result; 9851 if (Eval.evaluate(BO->getLHS(), Result)) { 9852 if (Result) 9853 Visit(BO->getRHS()); 9854 } else { 9855 WorkList.push_back(BO->getRHS()); 9856 } 9857 } 9858 9859 // Only visit the condition, unless we can be sure which subexpression will 9860 // be chosen. 9861 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 9862 EvaluationTracker Eval(*this); 9863 { 9864 SequencedSubexpression Sequenced(*this); 9865 Visit(CO->getCond()); 9866 } 9867 9868 bool Result; 9869 if (Eval.evaluate(CO->getCond(), Result)) 9870 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 9871 else { 9872 WorkList.push_back(CO->getTrueExpr()); 9873 WorkList.push_back(CO->getFalseExpr()); 9874 } 9875 } 9876 9877 void VisitCallExpr(CallExpr *CE) { 9878 // C++11 [intro.execution]p15: 9879 // When calling a function [...], every value computation and side effect 9880 // associated with any argument expression, or with the postfix expression 9881 // designating the called function, is sequenced before execution of every 9882 // expression or statement in the body of the function [and thus before 9883 // the value computation of its result]. 9884 SequencedSubexpression Sequenced(*this); 9885 Base::VisitCallExpr(CE); 9886 9887 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 9888 } 9889 9890 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 9891 // This is a call, so all subexpressions are sequenced before the result. 9892 SequencedSubexpression Sequenced(*this); 9893 9894 if (!CCE->isListInitialization()) 9895 return VisitExpr(CCE); 9896 9897 // In C++11, list initializations are sequenced. 9898 SmallVector<SequenceTree::Seq, 32> Elts; 9899 SequenceTree::Seq Parent = Region; 9900 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 9901 E = CCE->arg_end(); 9902 I != E; ++I) { 9903 Region = Tree.allocate(Parent); 9904 Elts.push_back(Region); 9905 Visit(*I); 9906 } 9907 9908 // Forget that the initializers are sequenced. 9909 Region = Parent; 9910 for (unsigned I = 0; I < Elts.size(); ++I) 9911 Tree.merge(Elts[I]); 9912 } 9913 9914 void VisitInitListExpr(InitListExpr *ILE) { 9915 if (!SemaRef.getLangOpts().CPlusPlus11) 9916 return VisitExpr(ILE); 9917 9918 // In C++11, list initializations are sequenced. 9919 SmallVector<SequenceTree::Seq, 32> Elts; 9920 SequenceTree::Seq Parent = Region; 9921 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 9922 Expr *E = ILE->getInit(I); 9923 if (!E) continue; 9924 Region = Tree.allocate(Parent); 9925 Elts.push_back(Region); 9926 Visit(E); 9927 } 9928 9929 // Forget that the initializers are sequenced. 9930 Region = Parent; 9931 for (unsigned I = 0; I < Elts.size(); ++I) 9932 Tree.merge(Elts[I]); 9933 } 9934 }; 9935 } // end anonymous namespace 9936 9937 void Sema::CheckUnsequencedOperations(Expr *E) { 9938 SmallVector<Expr *, 8> WorkList; 9939 WorkList.push_back(E); 9940 while (!WorkList.empty()) { 9941 Expr *Item = WorkList.pop_back_val(); 9942 SequenceChecker(*this, Item, WorkList); 9943 } 9944 } 9945 9946 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 9947 bool IsConstexpr) { 9948 CheckImplicitConversions(E, CheckLoc); 9949 if (!E->isInstantiationDependent()) 9950 CheckUnsequencedOperations(E); 9951 if (!IsConstexpr && !E->isValueDependent()) 9952 CheckForIntOverflow(E); 9953 DiagnoseMisalignedMembers(); 9954 } 9955 9956 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 9957 FieldDecl *BitField, 9958 Expr *Init) { 9959 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 9960 } 9961 9962 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 9963 SourceLocation Loc) { 9964 if (!PType->isVariablyModifiedType()) 9965 return; 9966 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 9967 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 9968 return; 9969 } 9970 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 9971 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 9972 return; 9973 } 9974 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 9975 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 9976 return; 9977 } 9978 9979 const ArrayType *AT = S.Context.getAsArrayType(PType); 9980 if (!AT) 9981 return; 9982 9983 if (AT->getSizeModifier() != ArrayType::Star) { 9984 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 9985 return; 9986 } 9987 9988 S.Diag(Loc, diag::err_array_star_in_function_definition); 9989 } 9990 9991 /// CheckParmsForFunctionDef - Check that the parameters of the given 9992 /// function are appropriate for the definition of a function. This 9993 /// takes care of any checks that cannot be performed on the 9994 /// declaration itself, e.g., that the types of each of the function 9995 /// parameters are complete. 9996 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 9997 bool CheckParameterNames) { 9998 bool HasInvalidParm = false; 9999 for (ParmVarDecl *Param : Parameters) { 10000 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10001 // function declarator that is part of a function definition of 10002 // that function shall not have incomplete type. 10003 // 10004 // This is also C++ [dcl.fct]p6. 10005 if (!Param->isInvalidDecl() && 10006 RequireCompleteType(Param->getLocation(), Param->getType(), 10007 diag::err_typecheck_decl_incomplete_type)) { 10008 Param->setInvalidDecl(); 10009 HasInvalidParm = true; 10010 } 10011 10012 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10013 // declaration of each parameter shall include an identifier. 10014 if (CheckParameterNames && 10015 Param->getIdentifier() == nullptr && 10016 !Param->isImplicit() && 10017 !getLangOpts().CPlusPlus) 10018 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10019 10020 // C99 6.7.5.3p12: 10021 // If the function declarator is not part of a definition of that 10022 // function, parameters may have incomplete type and may use the [*] 10023 // notation in their sequences of declarator specifiers to specify 10024 // variable length array types. 10025 QualType PType = Param->getOriginalType(); 10026 // FIXME: This diagnostic should point the '[*]' if source-location 10027 // information is added for it. 10028 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10029 10030 // MSVC destroys objects passed by value in the callee. Therefore a 10031 // function definition which takes such a parameter must be able to call the 10032 // object's destructor. However, we don't perform any direct access check 10033 // on the dtor. 10034 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10035 .getCXXABI() 10036 .areArgsDestroyedLeftToRightInCallee()) { 10037 if (!Param->isInvalidDecl()) { 10038 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10039 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10040 if (!ClassDecl->isInvalidDecl() && 10041 !ClassDecl->hasIrrelevantDestructor() && 10042 !ClassDecl->isDependentContext()) { 10043 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10044 MarkFunctionReferenced(Param->getLocation(), Destructor); 10045 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10046 } 10047 } 10048 } 10049 } 10050 10051 // Parameters with the pass_object_size attribute only need to be marked 10052 // constant at function definitions. Because we lack information about 10053 // whether we're on a declaration or definition when we're instantiating the 10054 // attribute, we need to check for constness here. 10055 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10056 if (!Param->getType().isConstQualified()) 10057 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10058 << Attr->getSpelling() << 1; 10059 } 10060 10061 return HasInvalidParm; 10062 } 10063 10064 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10065 /// pointer cast increases the alignment requirements. 10066 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10067 // This is actually a lot of work to potentially be doing on every 10068 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10069 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10070 return; 10071 10072 // Ignore dependent types. 10073 if (T->isDependentType() || Op->getType()->isDependentType()) 10074 return; 10075 10076 // Require that the destination be a pointer type. 10077 const PointerType *DestPtr = T->getAs<PointerType>(); 10078 if (!DestPtr) return; 10079 10080 // If the destination has alignment 1, we're done. 10081 QualType DestPointee = DestPtr->getPointeeType(); 10082 if (DestPointee->isIncompleteType()) return; 10083 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10084 if (DestAlign.isOne()) return; 10085 10086 // Require that the source be a pointer type. 10087 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10088 if (!SrcPtr) return; 10089 QualType SrcPointee = SrcPtr->getPointeeType(); 10090 10091 // Whitelist casts from cv void*. We already implicitly 10092 // whitelisted casts to cv void*, since they have alignment 1. 10093 // Also whitelist casts involving incomplete types, which implicitly 10094 // includes 'void'. 10095 if (SrcPointee->isIncompleteType()) return; 10096 10097 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10098 if (SrcAlign >= DestAlign) return; 10099 10100 Diag(TRange.getBegin(), diag::warn_cast_align) 10101 << Op->getType() << T 10102 << static_cast<unsigned>(SrcAlign.getQuantity()) 10103 << static_cast<unsigned>(DestAlign.getQuantity()) 10104 << TRange << Op->getSourceRange(); 10105 } 10106 10107 /// \brief Check whether this array fits the idiom of a size-one tail padded 10108 /// array member of a struct. 10109 /// 10110 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10111 /// commonly used to emulate flexible arrays in C89 code. 10112 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10113 const NamedDecl *ND) { 10114 if (Size != 1 || !ND) return false; 10115 10116 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10117 if (!FD) return false; 10118 10119 // Don't consider sizes resulting from macro expansions or template argument 10120 // substitution to form C89 tail-padded arrays. 10121 10122 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10123 while (TInfo) { 10124 TypeLoc TL = TInfo->getTypeLoc(); 10125 // Look through typedefs. 10126 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10127 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10128 TInfo = TDL->getTypeSourceInfo(); 10129 continue; 10130 } 10131 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10132 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10133 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10134 return false; 10135 } 10136 break; 10137 } 10138 10139 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10140 if (!RD) return false; 10141 if (RD->isUnion()) return false; 10142 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10143 if (!CRD->isStandardLayout()) return false; 10144 } 10145 10146 // See if this is the last field decl in the record. 10147 const Decl *D = FD; 10148 while ((D = D->getNextDeclInContext())) 10149 if (isa<FieldDecl>(D)) 10150 return false; 10151 return true; 10152 } 10153 10154 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10155 const ArraySubscriptExpr *ASE, 10156 bool AllowOnePastEnd, bool IndexNegated) { 10157 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10158 if (IndexExpr->isValueDependent()) 10159 return; 10160 10161 const Type *EffectiveType = 10162 BaseExpr->getType()->getPointeeOrArrayElementType(); 10163 BaseExpr = BaseExpr->IgnoreParenCasts(); 10164 const ConstantArrayType *ArrayTy = 10165 Context.getAsConstantArrayType(BaseExpr->getType()); 10166 if (!ArrayTy) 10167 return; 10168 10169 llvm::APSInt index; 10170 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10171 return; 10172 if (IndexNegated) 10173 index = -index; 10174 10175 const NamedDecl *ND = nullptr; 10176 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10177 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10178 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10179 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10180 10181 if (index.isUnsigned() || !index.isNegative()) { 10182 llvm::APInt size = ArrayTy->getSize(); 10183 if (!size.isStrictlyPositive()) 10184 return; 10185 10186 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10187 if (BaseType != EffectiveType) { 10188 // Make sure we're comparing apples to apples when comparing index to size 10189 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10190 uint64_t array_typesize = Context.getTypeSize(BaseType); 10191 // Handle ptrarith_typesize being zero, such as when casting to void* 10192 if (!ptrarith_typesize) ptrarith_typesize = 1; 10193 if (ptrarith_typesize != array_typesize) { 10194 // There's a cast to a different size type involved 10195 uint64_t ratio = array_typesize / ptrarith_typesize; 10196 // TODO: Be smarter about handling cases where array_typesize is not a 10197 // multiple of ptrarith_typesize 10198 if (ptrarith_typesize * ratio == array_typesize) 10199 size *= llvm::APInt(size.getBitWidth(), ratio); 10200 } 10201 } 10202 10203 if (size.getBitWidth() > index.getBitWidth()) 10204 index = index.zext(size.getBitWidth()); 10205 else if (size.getBitWidth() < index.getBitWidth()) 10206 size = size.zext(index.getBitWidth()); 10207 10208 // For array subscripting the index must be less than size, but for pointer 10209 // arithmetic also allow the index (offset) to be equal to size since 10210 // computing the next address after the end of the array is legal and 10211 // commonly done e.g. in C++ iterators and range-based for loops. 10212 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10213 return; 10214 10215 // Also don't warn for arrays of size 1 which are members of some 10216 // structure. These are often used to approximate flexible arrays in C89 10217 // code. 10218 if (IsTailPaddedMemberArray(*this, size, ND)) 10219 return; 10220 10221 // Suppress the warning if the subscript expression (as identified by the 10222 // ']' location) and the index expression are both from macro expansions 10223 // within a system header. 10224 if (ASE) { 10225 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 10226 ASE->getRBracketLoc()); 10227 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 10228 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 10229 IndexExpr->getLocStart()); 10230 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 10231 return; 10232 } 10233 } 10234 10235 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 10236 if (ASE) 10237 DiagID = diag::warn_array_index_exceeds_bounds; 10238 10239 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10240 PDiag(DiagID) << index.toString(10, true) 10241 << size.toString(10, true) 10242 << (unsigned)size.getLimitedValue(~0U) 10243 << IndexExpr->getSourceRange()); 10244 } else { 10245 unsigned DiagID = diag::warn_array_index_precedes_bounds; 10246 if (!ASE) { 10247 DiagID = diag::warn_ptr_arith_precedes_bounds; 10248 if (index.isNegative()) index = -index; 10249 } 10250 10251 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10252 PDiag(DiagID) << index.toString(10, true) 10253 << IndexExpr->getSourceRange()); 10254 } 10255 10256 if (!ND) { 10257 // Try harder to find a NamedDecl to point at in the note. 10258 while (const ArraySubscriptExpr *ASE = 10259 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 10260 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 10261 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10262 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10263 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10264 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10265 } 10266 10267 if (ND) 10268 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 10269 PDiag(diag::note_array_index_out_of_bounds) 10270 << ND->getDeclName()); 10271 } 10272 10273 void Sema::CheckArrayAccess(const Expr *expr) { 10274 int AllowOnePastEnd = 0; 10275 while (expr) { 10276 expr = expr->IgnoreParenImpCasts(); 10277 switch (expr->getStmtClass()) { 10278 case Stmt::ArraySubscriptExprClass: { 10279 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 10280 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 10281 AllowOnePastEnd > 0); 10282 return; 10283 } 10284 case Stmt::OMPArraySectionExprClass: { 10285 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 10286 if (ASE->getLowerBound()) 10287 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 10288 /*ASE=*/nullptr, AllowOnePastEnd > 0); 10289 return; 10290 } 10291 case Stmt::UnaryOperatorClass: { 10292 // Only unwrap the * and & unary operators 10293 const UnaryOperator *UO = cast<UnaryOperator>(expr); 10294 expr = UO->getSubExpr(); 10295 switch (UO->getOpcode()) { 10296 case UO_AddrOf: 10297 AllowOnePastEnd++; 10298 break; 10299 case UO_Deref: 10300 AllowOnePastEnd--; 10301 break; 10302 default: 10303 return; 10304 } 10305 break; 10306 } 10307 case Stmt::ConditionalOperatorClass: { 10308 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 10309 if (const Expr *lhs = cond->getLHS()) 10310 CheckArrayAccess(lhs); 10311 if (const Expr *rhs = cond->getRHS()) 10312 CheckArrayAccess(rhs); 10313 return; 10314 } 10315 default: 10316 return; 10317 } 10318 } 10319 } 10320 10321 //===--- CHECK: Objective-C retain cycles ----------------------------------// 10322 10323 namespace { 10324 struct RetainCycleOwner { 10325 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 10326 VarDecl *Variable; 10327 SourceRange Range; 10328 SourceLocation Loc; 10329 bool Indirect; 10330 10331 void setLocsFrom(Expr *e) { 10332 Loc = e->getExprLoc(); 10333 Range = e->getSourceRange(); 10334 } 10335 }; 10336 } // end anonymous namespace 10337 10338 /// Consider whether capturing the given variable can possibly lead to 10339 /// a retain cycle. 10340 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 10341 // In ARC, it's captured strongly iff the variable has __strong 10342 // lifetime. In MRR, it's captured strongly if the variable is 10343 // __block and has an appropriate type. 10344 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10345 return false; 10346 10347 owner.Variable = var; 10348 if (ref) 10349 owner.setLocsFrom(ref); 10350 return true; 10351 } 10352 10353 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 10354 while (true) { 10355 e = e->IgnoreParens(); 10356 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 10357 switch (cast->getCastKind()) { 10358 case CK_BitCast: 10359 case CK_LValueBitCast: 10360 case CK_LValueToRValue: 10361 case CK_ARCReclaimReturnedObject: 10362 e = cast->getSubExpr(); 10363 continue; 10364 10365 default: 10366 return false; 10367 } 10368 } 10369 10370 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 10371 ObjCIvarDecl *ivar = ref->getDecl(); 10372 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10373 return false; 10374 10375 // Try to find a retain cycle in the base. 10376 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 10377 return false; 10378 10379 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 10380 owner.Indirect = true; 10381 return true; 10382 } 10383 10384 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 10385 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 10386 if (!var) return false; 10387 return considerVariable(var, ref, owner); 10388 } 10389 10390 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 10391 if (member->isArrow()) return false; 10392 10393 // Don't count this as an indirect ownership. 10394 e = member->getBase(); 10395 continue; 10396 } 10397 10398 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 10399 // Only pay attention to pseudo-objects on property references. 10400 ObjCPropertyRefExpr *pre 10401 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 10402 ->IgnoreParens()); 10403 if (!pre) return false; 10404 if (pre->isImplicitProperty()) return false; 10405 ObjCPropertyDecl *property = pre->getExplicitProperty(); 10406 if (!property->isRetaining() && 10407 !(property->getPropertyIvarDecl() && 10408 property->getPropertyIvarDecl()->getType() 10409 .getObjCLifetime() == Qualifiers::OCL_Strong)) 10410 return false; 10411 10412 owner.Indirect = true; 10413 if (pre->isSuperReceiver()) { 10414 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 10415 if (!owner.Variable) 10416 return false; 10417 owner.Loc = pre->getLocation(); 10418 owner.Range = pre->getSourceRange(); 10419 return true; 10420 } 10421 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 10422 ->getSourceExpr()); 10423 continue; 10424 } 10425 10426 // Array ivars? 10427 10428 return false; 10429 } 10430 } 10431 10432 namespace { 10433 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 10434 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 10435 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 10436 Context(Context), Variable(variable), Capturer(nullptr), 10437 VarWillBeReased(false) {} 10438 ASTContext &Context; 10439 VarDecl *Variable; 10440 Expr *Capturer; 10441 bool VarWillBeReased; 10442 10443 void VisitDeclRefExpr(DeclRefExpr *ref) { 10444 if (ref->getDecl() == Variable && !Capturer) 10445 Capturer = ref; 10446 } 10447 10448 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 10449 if (Capturer) return; 10450 Visit(ref->getBase()); 10451 if (Capturer && ref->isFreeIvar()) 10452 Capturer = ref; 10453 } 10454 10455 void VisitBlockExpr(BlockExpr *block) { 10456 // Look inside nested blocks 10457 if (block->getBlockDecl()->capturesVariable(Variable)) 10458 Visit(block->getBlockDecl()->getBody()); 10459 } 10460 10461 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 10462 if (Capturer) return; 10463 if (OVE->getSourceExpr()) 10464 Visit(OVE->getSourceExpr()); 10465 } 10466 void VisitBinaryOperator(BinaryOperator *BinOp) { 10467 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 10468 return; 10469 Expr *LHS = BinOp->getLHS(); 10470 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 10471 if (DRE->getDecl() != Variable) 10472 return; 10473 if (Expr *RHS = BinOp->getRHS()) { 10474 RHS = RHS->IgnoreParenCasts(); 10475 llvm::APSInt Value; 10476 VarWillBeReased = 10477 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 10478 } 10479 } 10480 } 10481 }; 10482 } // end anonymous namespace 10483 10484 /// Check whether the given argument is a block which captures a 10485 /// variable. 10486 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 10487 assert(owner.Variable && owner.Loc.isValid()); 10488 10489 e = e->IgnoreParenCasts(); 10490 10491 // Look through [^{...} copy] and Block_copy(^{...}). 10492 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 10493 Selector Cmd = ME->getSelector(); 10494 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 10495 e = ME->getInstanceReceiver(); 10496 if (!e) 10497 return nullptr; 10498 e = e->IgnoreParenCasts(); 10499 } 10500 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 10501 if (CE->getNumArgs() == 1) { 10502 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 10503 if (Fn) { 10504 const IdentifierInfo *FnI = Fn->getIdentifier(); 10505 if (FnI && FnI->isStr("_Block_copy")) { 10506 e = CE->getArg(0)->IgnoreParenCasts(); 10507 } 10508 } 10509 } 10510 } 10511 10512 BlockExpr *block = dyn_cast<BlockExpr>(e); 10513 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 10514 return nullptr; 10515 10516 FindCaptureVisitor visitor(S.Context, owner.Variable); 10517 visitor.Visit(block->getBlockDecl()->getBody()); 10518 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 10519 } 10520 10521 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 10522 RetainCycleOwner &owner) { 10523 assert(capturer); 10524 assert(owner.Variable && owner.Loc.isValid()); 10525 10526 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 10527 << owner.Variable << capturer->getSourceRange(); 10528 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 10529 << owner.Indirect << owner.Range; 10530 } 10531 10532 /// Check for a keyword selector that starts with the word 'add' or 10533 /// 'set'. 10534 static bool isSetterLikeSelector(Selector sel) { 10535 if (sel.isUnarySelector()) return false; 10536 10537 StringRef str = sel.getNameForSlot(0); 10538 while (!str.empty() && str.front() == '_') str = str.substr(1); 10539 if (str.startswith("set")) 10540 str = str.substr(3); 10541 else if (str.startswith("add")) { 10542 // Specially whitelist 'addOperationWithBlock:'. 10543 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 10544 return false; 10545 str = str.substr(3); 10546 } 10547 else 10548 return false; 10549 10550 if (str.empty()) return true; 10551 return !isLowercase(str.front()); 10552 } 10553 10554 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 10555 ObjCMessageExpr *Message) { 10556 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 10557 Message->getReceiverInterface(), 10558 NSAPI::ClassId_NSMutableArray); 10559 if (!IsMutableArray) { 10560 return None; 10561 } 10562 10563 Selector Sel = Message->getSelector(); 10564 10565 Optional<NSAPI::NSArrayMethodKind> MKOpt = 10566 S.NSAPIObj->getNSArrayMethodKind(Sel); 10567 if (!MKOpt) { 10568 return None; 10569 } 10570 10571 NSAPI::NSArrayMethodKind MK = *MKOpt; 10572 10573 switch (MK) { 10574 case NSAPI::NSMutableArr_addObject: 10575 case NSAPI::NSMutableArr_insertObjectAtIndex: 10576 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 10577 return 0; 10578 case NSAPI::NSMutableArr_replaceObjectAtIndex: 10579 return 1; 10580 10581 default: 10582 return None; 10583 } 10584 10585 return None; 10586 } 10587 10588 static 10589 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 10590 ObjCMessageExpr *Message) { 10591 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 10592 Message->getReceiverInterface(), 10593 NSAPI::ClassId_NSMutableDictionary); 10594 if (!IsMutableDictionary) { 10595 return None; 10596 } 10597 10598 Selector Sel = Message->getSelector(); 10599 10600 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 10601 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 10602 if (!MKOpt) { 10603 return None; 10604 } 10605 10606 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 10607 10608 switch (MK) { 10609 case NSAPI::NSMutableDict_setObjectForKey: 10610 case NSAPI::NSMutableDict_setValueForKey: 10611 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 10612 return 0; 10613 10614 default: 10615 return None; 10616 } 10617 10618 return None; 10619 } 10620 10621 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 10622 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 10623 Message->getReceiverInterface(), 10624 NSAPI::ClassId_NSMutableSet); 10625 10626 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 10627 Message->getReceiverInterface(), 10628 NSAPI::ClassId_NSMutableOrderedSet); 10629 if (!IsMutableSet && !IsMutableOrderedSet) { 10630 return None; 10631 } 10632 10633 Selector Sel = Message->getSelector(); 10634 10635 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 10636 if (!MKOpt) { 10637 return None; 10638 } 10639 10640 NSAPI::NSSetMethodKind MK = *MKOpt; 10641 10642 switch (MK) { 10643 case NSAPI::NSMutableSet_addObject: 10644 case NSAPI::NSOrderedSet_setObjectAtIndex: 10645 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 10646 case NSAPI::NSOrderedSet_insertObjectAtIndex: 10647 return 0; 10648 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 10649 return 1; 10650 } 10651 10652 return None; 10653 } 10654 10655 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 10656 if (!Message->isInstanceMessage()) { 10657 return; 10658 } 10659 10660 Optional<int> ArgOpt; 10661 10662 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 10663 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 10664 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 10665 return; 10666 } 10667 10668 int ArgIndex = *ArgOpt; 10669 10670 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 10671 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 10672 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 10673 } 10674 10675 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 10676 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10677 if (ArgRE->isObjCSelfExpr()) { 10678 Diag(Message->getSourceRange().getBegin(), 10679 diag::warn_objc_circular_container) 10680 << ArgRE->getDecl()->getName() << StringRef("super"); 10681 } 10682 } 10683 } else { 10684 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 10685 10686 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 10687 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 10688 } 10689 10690 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 10691 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10692 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 10693 ValueDecl *Decl = ReceiverRE->getDecl(); 10694 Diag(Message->getSourceRange().getBegin(), 10695 diag::warn_objc_circular_container) 10696 << Decl->getName() << Decl->getName(); 10697 if (!ArgRE->isObjCSelfExpr()) { 10698 Diag(Decl->getLocation(), 10699 diag::note_objc_circular_container_declared_here) 10700 << Decl->getName(); 10701 } 10702 } 10703 } 10704 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 10705 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 10706 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 10707 ObjCIvarDecl *Decl = IvarRE->getDecl(); 10708 Diag(Message->getSourceRange().getBegin(), 10709 diag::warn_objc_circular_container) 10710 << Decl->getName() << Decl->getName(); 10711 Diag(Decl->getLocation(), 10712 diag::note_objc_circular_container_declared_here) 10713 << Decl->getName(); 10714 } 10715 } 10716 } 10717 } 10718 } 10719 10720 /// Check a message send to see if it's likely to cause a retain cycle. 10721 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 10722 // Only check instance methods whose selector looks like a setter. 10723 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 10724 return; 10725 10726 // Try to find a variable that the receiver is strongly owned by. 10727 RetainCycleOwner owner; 10728 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 10729 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 10730 return; 10731 } else { 10732 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 10733 owner.Variable = getCurMethodDecl()->getSelfDecl(); 10734 owner.Loc = msg->getSuperLoc(); 10735 owner.Range = msg->getSuperLoc(); 10736 } 10737 10738 // Check whether the receiver is captured by any of the arguments. 10739 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 10740 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 10741 return diagnoseRetainCycle(*this, capturer, owner); 10742 } 10743 10744 /// Check a property assign to see if it's likely to cause a retain cycle. 10745 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 10746 RetainCycleOwner owner; 10747 if (!findRetainCycleOwner(*this, receiver, owner)) 10748 return; 10749 10750 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 10751 diagnoseRetainCycle(*this, capturer, owner); 10752 } 10753 10754 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 10755 RetainCycleOwner Owner; 10756 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 10757 return; 10758 10759 // Because we don't have an expression for the variable, we have to set the 10760 // location explicitly here. 10761 Owner.Loc = Var->getLocation(); 10762 Owner.Range = Var->getSourceRange(); 10763 10764 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 10765 diagnoseRetainCycle(*this, Capturer, Owner); 10766 } 10767 10768 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 10769 Expr *RHS, bool isProperty) { 10770 // Check if RHS is an Objective-C object literal, which also can get 10771 // immediately zapped in a weak reference. Note that we explicitly 10772 // allow ObjCStringLiterals, since those are designed to never really die. 10773 RHS = RHS->IgnoreParenImpCasts(); 10774 10775 // This enum needs to match with the 'select' in 10776 // warn_objc_arc_literal_assign (off-by-1). 10777 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 10778 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 10779 return false; 10780 10781 S.Diag(Loc, diag::warn_arc_literal_assign) 10782 << (unsigned) Kind 10783 << (isProperty ? 0 : 1) 10784 << RHS->getSourceRange(); 10785 10786 return true; 10787 } 10788 10789 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 10790 Qualifiers::ObjCLifetime LT, 10791 Expr *RHS, bool isProperty) { 10792 // Strip off any implicit cast added to get to the one ARC-specific. 10793 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 10794 if (cast->getCastKind() == CK_ARCConsumeObject) { 10795 S.Diag(Loc, diag::warn_arc_retained_assign) 10796 << (LT == Qualifiers::OCL_ExplicitNone) 10797 << (isProperty ? 0 : 1) 10798 << RHS->getSourceRange(); 10799 return true; 10800 } 10801 RHS = cast->getSubExpr(); 10802 } 10803 10804 if (LT == Qualifiers::OCL_Weak && 10805 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 10806 return true; 10807 10808 return false; 10809 } 10810 10811 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 10812 QualType LHS, Expr *RHS) { 10813 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 10814 10815 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 10816 return false; 10817 10818 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 10819 return true; 10820 10821 return false; 10822 } 10823 10824 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 10825 Expr *LHS, Expr *RHS) { 10826 QualType LHSType; 10827 // PropertyRef on LHS type need be directly obtained from 10828 // its declaration as it has a PseudoType. 10829 ObjCPropertyRefExpr *PRE 10830 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 10831 if (PRE && !PRE->isImplicitProperty()) { 10832 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 10833 if (PD) 10834 LHSType = PD->getType(); 10835 } 10836 10837 if (LHSType.isNull()) 10838 LHSType = LHS->getType(); 10839 10840 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 10841 10842 if (LT == Qualifiers::OCL_Weak) { 10843 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 10844 getCurFunction()->markSafeWeakUse(LHS); 10845 } 10846 10847 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 10848 return; 10849 10850 // FIXME. Check for other life times. 10851 if (LT != Qualifiers::OCL_None) 10852 return; 10853 10854 if (PRE) { 10855 if (PRE->isImplicitProperty()) 10856 return; 10857 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 10858 if (!PD) 10859 return; 10860 10861 unsigned Attributes = PD->getPropertyAttributes(); 10862 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 10863 // when 'assign' attribute was not explicitly specified 10864 // by user, ignore it and rely on property type itself 10865 // for lifetime info. 10866 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 10867 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 10868 LHSType->isObjCRetainableType()) 10869 return; 10870 10871 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 10872 if (cast->getCastKind() == CK_ARCConsumeObject) { 10873 Diag(Loc, diag::warn_arc_retained_property_assign) 10874 << RHS->getSourceRange(); 10875 return; 10876 } 10877 RHS = cast->getSubExpr(); 10878 } 10879 } 10880 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 10881 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 10882 return; 10883 } 10884 } 10885 } 10886 10887 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 10888 10889 namespace { 10890 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 10891 SourceLocation StmtLoc, 10892 const NullStmt *Body) { 10893 // Do not warn if the body is a macro that expands to nothing, e.g: 10894 // 10895 // #define CALL(x) 10896 // if (condition) 10897 // CALL(0); 10898 // 10899 if (Body->hasLeadingEmptyMacro()) 10900 return false; 10901 10902 // Get line numbers of statement and body. 10903 bool StmtLineInvalid; 10904 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 10905 &StmtLineInvalid); 10906 if (StmtLineInvalid) 10907 return false; 10908 10909 bool BodyLineInvalid; 10910 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 10911 &BodyLineInvalid); 10912 if (BodyLineInvalid) 10913 return false; 10914 10915 // Warn if null statement and body are on the same line. 10916 if (StmtLine != BodyLine) 10917 return false; 10918 10919 return true; 10920 } 10921 } // end anonymous namespace 10922 10923 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 10924 const Stmt *Body, 10925 unsigned DiagID) { 10926 // Since this is a syntactic check, don't emit diagnostic for template 10927 // instantiations, this just adds noise. 10928 if (CurrentInstantiationScope) 10929 return; 10930 10931 // The body should be a null statement. 10932 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 10933 if (!NBody) 10934 return; 10935 10936 // Do the usual checks. 10937 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 10938 return; 10939 10940 Diag(NBody->getSemiLoc(), DiagID); 10941 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 10942 } 10943 10944 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 10945 const Stmt *PossibleBody) { 10946 assert(!CurrentInstantiationScope); // Ensured by caller 10947 10948 SourceLocation StmtLoc; 10949 const Stmt *Body; 10950 unsigned DiagID; 10951 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 10952 StmtLoc = FS->getRParenLoc(); 10953 Body = FS->getBody(); 10954 DiagID = diag::warn_empty_for_body; 10955 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 10956 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 10957 Body = WS->getBody(); 10958 DiagID = diag::warn_empty_while_body; 10959 } else 10960 return; // Neither `for' nor `while'. 10961 10962 // The body should be a null statement. 10963 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 10964 if (!NBody) 10965 return; 10966 10967 // Skip expensive checks if diagnostic is disabled. 10968 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 10969 return; 10970 10971 // Do the usual checks. 10972 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 10973 return; 10974 10975 // `for(...);' and `while(...);' are popular idioms, so in order to keep 10976 // noise level low, emit diagnostics only if for/while is followed by a 10977 // CompoundStmt, e.g.: 10978 // for (int i = 0; i < n; i++); 10979 // { 10980 // a(i); 10981 // } 10982 // or if for/while is followed by a statement with more indentation 10983 // than for/while itself: 10984 // for (int i = 0; i < n; i++); 10985 // a(i); 10986 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 10987 if (!ProbableTypo) { 10988 bool BodyColInvalid; 10989 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 10990 PossibleBody->getLocStart(), 10991 &BodyColInvalid); 10992 if (BodyColInvalid) 10993 return; 10994 10995 bool StmtColInvalid; 10996 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 10997 S->getLocStart(), 10998 &StmtColInvalid); 10999 if (StmtColInvalid) 11000 return; 11001 11002 if (BodyCol > StmtCol) 11003 ProbableTypo = true; 11004 } 11005 11006 if (ProbableTypo) { 11007 Diag(NBody->getSemiLoc(), DiagID); 11008 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11009 } 11010 } 11011 11012 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11013 11014 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11015 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11016 SourceLocation OpLoc) { 11017 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11018 return; 11019 11020 if (!ActiveTemplateInstantiations.empty()) 11021 return; 11022 11023 // Strip parens and casts away. 11024 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11025 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11026 11027 // Check for a call expression 11028 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11029 if (!CE || CE->getNumArgs() != 1) 11030 return; 11031 11032 // Check for a call to std::move 11033 const FunctionDecl *FD = CE->getDirectCallee(); 11034 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 11035 !FD->getIdentifier()->isStr("move")) 11036 return; 11037 11038 // Get argument from std::move 11039 RHSExpr = CE->getArg(0); 11040 11041 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11042 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11043 11044 // Two DeclRefExpr's, check that the decls are the same. 11045 if (LHSDeclRef && RHSDeclRef) { 11046 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11047 return; 11048 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11049 RHSDeclRef->getDecl()->getCanonicalDecl()) 11050 return; 11051 11052 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11053 << LHSExpr->getSourceRange() 11054 << RHSExpr->getSourceRange(); 11055 return; 11056 } 11057 11058 // Member variables require a different approach to check for self moves. 11059 // MemberExpr's are the same if every nested MemberExpr refers to the same 11060 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11061 // the base Expr's are CXXThisExpr's. 11062 const Expr *LHSBase = LHSExpr; 11063 const Expr *RHSBase = RHSExpr; 11064 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11065 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11066 if (!LHSME || !RHSME) 11067 return; 11068 11069 while (LHSME && RHSME) { 11070 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11071 RHSME->getMemberDecl()->getCanonicalDecl()) 11072 return; 11073 11074 LHSBase = LHSME->getBase(); 11075 RHSBase = RHSME->getBase(); 11076 LHSME = dyn_cast<MemberExpr>(LHSBase); 11077 RHSME = dyn_cast<MemberExpr>(RHSBase); 11078 } 11079 11080 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11081 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11082 if (LHSDeclRef && RHSDeclRef) { 11083 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11084 return; 11085 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11086 RHSDeclRef->getDecl()->getCanonicalDecl()) 11087 return; 11088 11089 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11090 << LHSExpr->getSourceRange() 11091 << RHSExpr->getSourceRange(); 11092 return; 11093 } 11094 11095 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11096 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11097 << LHSExpr->getSourceRange() 11098 << RHSExpr->getSourceRange(); 11099 } 11100 11101 //===--- Layout compatibility ----------------------------------------------// 11102 11103 namespace { 11104 11105 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11106 11107 /// \brief Check if two enumeration types are layout-compatible. 11108 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11109 // C++11 [dcl.enum] p8: 11110 // Two enumeration types are layout-compatible if they have the same 11111 // underlying type. 11112 return ED1->isComplete() && ED2->isComplete() && 11113 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11114 } 11115 11116 /// \brief Check if two fields are layout-compatible. 11117 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11118 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11119 return false; 11120 11121 if (Field1->isBitField() != Field2->isBitField()) 11122 return false; 11123 11124 if (Field1->isBitField()) { 11125 // Make sure that the bit-fields are the same length. 11126 unsigned Bits1 = Field1->getBitWidthValue(C); 11127 unsigned Bits2 = Field2->getBitWidthValue(C); 11128 11129 if (Bits1 != Bits2) 11130 return false; 11131 } 11132 11133 return true; 11134 } 11135 11136 /// \brief Check if two standard-layout structs are layout-compatible. 11137 /// (C++11 [class.mem] p17) 11138 bool isLayoutCompatibleStruct(ASTContext &C, 11139 RecordDecl *RD1, 11140 RecordDecl *RD2) { 11141 // If both records are C++ classes, check that base classes match. 11142 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11143 // If one of records is a CXXRecordDecl we are in C++ mode, 11144 // thus the other one is a CXXRecordDecl, too. 11145 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11146 // Check number of base classes. 11147 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11148 return false; 11149 11150 // Check the base classes. 11151 for (CXXRecordDecl::base_class_const_iterator 11152 Base1 = D1CXX->bases_begin(), 11153 BaseEnd1 = D1CXX->bases_end(), 11154 Base2 = D2CXX->bases_begin(); 11155 Base1 != BaseEnd1; 11156 ++Base1, ++Base2) { 11157 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11158 return false; 11159 } 11160 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11161 // If only RD2 is a C++ class, it should have zero base classes. 11162 if (D2CXX->getNumBases() > 0) 11163 return false; 11164 } 11165 11166 // Check the fields. 11167 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11168 Field2End = RD2->field_end(), 11169 Field1 = RD1->field_begin(), 11170 Field1End = RD1->field_end(); 11171 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11172 if (!isLayoutCompatible(C, *Field1, *Field2)) 11173 return false; 11174 } 11175 if (Field1 != Field1End || Field2 != Field2End) 11176 return false; 11177 11178 return true; 11179 } 11180 11181 /// \brief Check if two standard-layout unions are layout-compatible. 11182 /// (C++11 [class.mem] p18) 11183 bool isLayoutCompatibleUnion(ASTContext &C, 11184 RecordDecl *RD1, 11185 RecordDecl *RD2) { 11186 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11187 for (auto *Field2 : RD2->fields()) 11188 UnmatchedFields.insert(Field2); 11189 11190 for (auto *Field1 : RD1->fields()) { 11191 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11192 I = UnmatchedFields.begin(), 11193 E = UnmatchedFields.end(); 11194 11195 for ( ; I != E; ++I) { 11196 if (isLayoutCompatible(C, Field1, *I)) { 11197 bool Result = UnmatchedFields.erase(*I); 11198 (void) Result; 11199 assert(Result); 11200 break; 11201 } 11202 } 11203 if (I == E) 11204 return false; 11205 } 11206 11207 return UnmatchedFields.empty(); 11208 } 11209 11210 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11211 if (RD1->isUnion() != RD2->isUnion()) 11212 return false; 11213 11214 if (RD1->isUnion()) 11215 return isLayoutCompatibleUnion(C, RD1, RD2); 11216 else 11217 return isLayoutCompatibleStruct(C, RD1, RD2); 11218 } 11219 11220 /// \brief Check if two types are layout-compatible in C++11 sense. 11221 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 11222 if (T1.isNull() || T2.isNull()) 11223 return false; 11224 11225 // C++11 [basic.types] p11: 11226 // If two types T1 and T2 are the same type, then T1 and T2 are 11227 // layout-compatible types. 11228 if (C.hasSameType(T1, T2)) 11229 return true; 11230 11231 T1 = T1.getCanonicalType().getUnqualifiedType(); 11232 T2 = T2.getCanonicalType().getUnqualifiedType(); 11233 11234 const Type::TypeClass TC1 = T1->getTypeClass(); 11235 const Type::TypeClass TC2 = T2->getTypeClass(); 11236 11237 if (TC1 != TC2) 11238 return false; 11239 11240 if (TC1 == Type::Enum) { 11241 return isLayoutCompatible(C, 11242 cast<EnumType>(T1)->getDecl(), 11243 cast<EnumType>(T2)->getDecl()); 11244 } else if (TC1 == Type::Record) { 11245 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 11246 return false; 11247 11248 return isLayoutCompatible(C, 11249 cast<RecordType>(T1)->getDecl(), 11250 cast<RecordType>(T2)->getDecl()); 11251 } 11252 11253 return false; 11254 } 11255 } // end anonymous namespace 11256 11257 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 11258 11259 namespace { 11260 /// \brief Given a type tag expression find the type tag itself. 11261 /// 11262 /// \param TypeExpr Type tag expression, as it appears in user's code. 11263 /// 11264 /// \param VD Declaration of an identifier that appears in a type tag. 11265 /// 11266 /// \param MagicValue Type tag magic value. 11267 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 11268 const ValueDecl **VD, uint64_t *MagicValue) { 11269 while(true) { 11270 if (!TypeExpr) 11271 return false; 11272 11273 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 11274 11275 switch (TypeExpr->getStmtClass()) { 11276 case Stmt::UnaryOperatorClass: { 11277 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 11278 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 11279 TypeExpr = UO->getSubExpr(); 11280 continue; 11281 } 11282 return false; 11283 } 11284 11285 case Stmt::DeclRefExprClass: { 11286 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 11287 *VD = DRE->getDecl(); 11288 return true; 11289 } 11290 11291 case Stmt::IntegerLiteralClass: { 11292 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 11293 llvm::APInt MagicValueAPInt = IL->getValue(); 11294 if (MagicValueAPInt.getActiveBits() <= 64) { 11295 *MagicValue = MagicValueAPInt.getZExtValue(); 11296 return true; 11297 } else 11298 return false; 11299 } 11300 11301 case Stmt::BinaryConditionalOperatorClass: 11302 case Stmt::ConditionalOperatorClass: { 11303 const AbstractConditionalOperator *ACO = 11304 cast<AbstractConditionalOperator>(TypeExpr); 11305 bool Result; 11306 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 11307 if (Result) 11308 TypeExpr = ACO->getTrueExpr(); 11309 else 11310 TypeExpr = ACO->getFalseExpr(); 11311 continue; 11312 } 11313 return false; 11314 } 11315 11316 case Stmt::BinaryOperatorClass: { 11317 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 11318 if (BO->getOpcode() == BO_Comma) { 11319 TypeExpr = BO->getRHS(); 11320 continue; 11321 } 11322 return false; 11323 } 11324 11325 default: 11326 return false; 11327 } 11328 } 11329 } 11330 11331 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 11332 /// 11333 /// \param TypeExpr Expression that specifies a type tag. 11334 /// 11335 /// \param MagicValues Registered magic values. 11336 /// 11337 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 11338 /// kind. 11339 /// 11340 /// \param TypeInfo Information about the corresponding C type. 11341 /// 11342 /// \returns true if the corresponding C type was found. 11343 bool GetMatchingCType( 11344 const IdentifierInfo *ArgumentKind, 11345 const Expr *TypeExpr, const ASTContext &Ctx, 11346 const llvm::DenseMap<Sema::TypeTagMagicValue, 11347 Sema::TypeTagData> *MagicValues, 11348 bool &FoundWrongKind, 11349 Sema::TypeTagData &TypeInfo) { 11350 FoundWrongKind = false; 11351 11352 // Variable declaration that has type_tag_for_datatype attribute. 11353 const ValueDecl *VD = nullptr; 11354 11355 uint64_t MagicValue; 11356 11357 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 11358 return false; 11359 11360 if (VD) { 11361 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 11362 if (I->getArgumentKind() != ArgumentKind) { 11363 FoundWrongKind = true; 11364 return false; 11365 } 11366 TypeInfo.Type = I->getMatchingCType(); 11367 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 11368 TypeInfo.MustBeNull = I->getMustBeNull(); 11369 return true; 11370 } 11371 return false; 11372 } 11373 11374 if (!MagicValues) 11375 return false; 11376 11377 llvm::DenseMap<Sema::TypeTagMagicValue, 11378 Sema::TypeTagData>::const_iterator I = 11379 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 11380 if (I == MagicValues->end()) 11381 return false; 11382 11383 TypeInfo = I->second; 11384 return true; 11385 } 11386 } // end anonymous namespace 11387 11388 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 11389 uint64_t MagicValue, QualType Type, 11390 bool LayoutCompatible, 11391 bool MustBeNull) { 11392 if (!TypeTagForDatatypeMagicValues) 11393 TypeTagForDatatypeMagicValues.reset( 11394 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 11395 11396 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 11397 (*TypeTagForDatatypeMagicValues)[Magic] = 11398 TypeTagData(Type, LayoutCompatible, MustBeNull); 11399 } 11400 11401 namespace { 11402 bool IsSameCharType(QualType T1, QualType T2) { 11403 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 11404 if (!BT1) 11405 return false; 11406 11407 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 11408 if (!BT2) 11409 return false; 11410 11411 BuiltinType::Kind T1Kind = BT1->getKind(); 11412 BuiltinType::Kind T2Kind = BT2->getKind(); 11413 11414 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 11415 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 11416 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 11417 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 11418 } 11419 } // end anonymous namespace 11420 11421 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 11422 const Expr * const *ExprArgs) { 11423 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 11424 bool IsPointerAttr = Attr->getIsPointer(); 11425 11426 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 11427 bool FoundWrongKind; 11428 TypeTagData TypeInfo; 11429 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 11430 TypeTagForDatatypeMagicValues.get(), 11431 FoundWrongKind, TypeInfo)) { 11432 if (FoundWrongKind) 11433 Diag(TypeTagExpr->getExprLoc(), 11434 diag::warn_type_tag_for_datatype_wrong_kind) 11435 << TypeTagExpr->getSourceRange(); 11436 return; 11437 } 11438 11439 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 11440 if (IsPointerAttr) { 11441 // Skip implicit cast of pointer to `void *' (as a function argument). 11442 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 11443 if (ICE->getType()->isVoidPointerType() && 11444 ICE->getCastKind() == CK_BitCast) 11445 ArgumentExpr = ICE->getSubExpr(); 11446 } 11447 QualType ArgumentType = ArgumentExpr->getType(); 11448 11449 // Passing a `void*' pointer shouldn't trigger a warning. 11450 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 11451 return; 11452 11453 if (TypeInfo.MustBeNull) { 11454 // Type tag with matching void type requires a null pointer. 11455 if (!ArgumentExpr->isNullPointerConstant(Context, 11456 Expr::NPC_ValueDependentIsNotNull)) { 11457 Diag(ArgumentExpr->getExprLoc(), 11458 diag::warn_type_safety_null_pointer_required) 11459 << ArgumentKind->getName() 11460 << ArgumentExpr->getSourceRange() 11461 << TypeTagExpr->getSourceRange(); 11462 } 11463 return; 11464 } 11465 11466 QualType RequiredType = TypeInfo.Type; 11467 if (IsPointerAttr) 11468 RequiredType = Context.getPointerType(RequiredType); 11469 11470 bool mismatch = false; 11471 if (!TypeInfo.LayoutCompatible) { 11472 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 11473 11474 // C++11 [basic.fundamental] p1: 11475 // Plain char, signed char, and unsigned char are three distinct types. 11476 // 11477 // But we treat plain `char' as equivalent to `signed char' or `unsigned 11478 // char' depending on the current char signedness mode. 11479 if (mismatch) 11480 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 11481 RequiredType->getPointeeType())) || 11482 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 11483 mismatch = false; 11484 } else 11485 if (IsPointerAttr) 11486 mismatch = !isLayoutCompatible(Context, 11487 ArgumentType->getPointeeType(), 11488 RequiredType->getPointeeType()); 11489 else 11490 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 11491 11492 if (mismatch) 11493 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 11494 << ArgumentType << ArgumentKind 11495 << TypeInfo.LayoutCompatible << RequiredType 11496 << ArgumentExpr->getSourceRange() 11497 << TypeTagExpr->getSourceRange(); 11498 } 11499 11500 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 11501 CharUnits Alignment) { 11502 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 11503 } 11504 11505 void Sema::DiagnoseMisalignedMembers() { 11506 for (MisalignedMember &m : MisalignedMembers) { 11507 const NamedDecl *ND = m.RD; 11508 if (ND->getName().empty()) { 11509 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 11510 ND = TD; 11511 } 11512 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 11513 << m.MD << ND << m.E->getSourceRange(); 11514 } 11515 MisalignedMembers.clear(); 11516 } 11517 11518 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 11519 if (!T->isPointerType()) 11520 return; 11521 if (isa<UnaryOperator>(E) && 11522 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 11523 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 11524 if (isa<MemberExpr>(Op)) { 11525 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 11526 MisalignedMember(Op)); 11527 if (MA != MisalignedMembers.end() && 11528 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment) 11529 MisalignedMembers.erase(MA); 11530 } 11531 } 11532 } 11533 11534 void Sema::RefersToMemberWithReducedAlignment( 11535 Expr *E, 11536 std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) { 11537 const auto *ME = dyn_cast<MemberExpr>(E); 11538 while (ME && isa<FieldDecl>(ME->getMemberDecl())) { 11539 QualType BaseType = ME->getBase()->getType(); 11540 if (ME->isArrow()) 11541 BaseType = BaseType->getPointeeType(); 11542 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 11543 11544 ValueDecl *MD = ME->getMemberDecl(); 11545 bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne(); 11546 if (ByteAligned) // Attribute packed does not have any effect. 11547 break; 11548 11549 if (!ByteAligned && 11550 (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) { 11551 CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()), 11552 Context.getTypeAlignInChars(BaseType)); 11553 // Notify that this expression designates a member with reduced alignment 11554 Action(E, RD, MD, Alignment); 11555 break; 11556 } 11557 ME = dyn_cast<MemberExpr>(ME->getBase()); 11558 } 11559 } 11560 11561 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 11562 using namespace std::placeholders; 11563 RefersToMemberWithReducedAlignment( 11564 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 11565 _2, _3, _4)); 11566 } 11567 11568