1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements extra semantic analysis beyond what is enforced 11 // by the C type system. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CharUnits.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/EvaluatedExprVisitor.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/ExprObjC.h" 23 #include "clang/AST/ExprOpenMP.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/AST/StmtObjC.h" 26 #include "clang/Analysis/Analyses/FormatString.h" 27 #include "clang/Basic/CharInfo.h" 28 #include "clang/Basic/SyncScope.h" 29 #include "clang/Basic/TargetBuiltins.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 32 #include "clang/Sema/Initialization.h" 33 #include "clang/Sema/Lookup.h" 34 #include "clang/Sema/ScopeInfo.h" 35 #include "clang/Sema/Sema.h" 36 #include "clang/Sema/SemaInternal.h" 37 #include "llvm/ADT/STLExtras.h" 38 #include "llvm/ADT/SmallBitVector.h" 39 #include "llvm/ADT/SmallString.h" 40 #include "llvm/Support/ConvertUTF.h" 41 #include "llvm/Support/Format.h" 42 #include "llvm/Support/Locale.h" 43 #include "llvm/Support/raw_ostream.h" 44 45 using namespace clang; 46 using namespace sema; 47 48 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 49 unsigned ByteNo) const { 50 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 51 Context.getTargetInfo()); 52 } 53 54 /// Checks that a call expression's argument count is the desired number. 55 /// This is useful when doing custom type-checking. Returns true on error. 56 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 57 unsigned argCount = call->getNumArgs(); 58 if (argCount == desiredArgCount) return false; 59 60 if (argCount < desiredArgCount) 61 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 62 << 0 /*function call*/ << desiredArgCount << argCount 63 << call->getSourceRange(); 64 65 // Highlight all the excess arguments. 66 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 67 call->getArg(argCount - 1)->getLocEnd()); 68 69 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 70 << 0 /*function call*/ << desiredArgCount << argCount 71 << call->getArg(1)->getSourceRange(); 72 } 73 74 /// Check that the first argument to __builtin_annotation is an integer 75 /// and the second argument is a non-wide string literal. 76 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 77 if (checkArgCount(S, TheCall, 2)) 78 return true; 79 80 // First argument should be an integer. 81 Expr *ValArg = TheCall->getArg(0); 82 QualType Ty = ValArg->getType(); 83 if (!Ty->isIntegerType()) { 84 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 85 << ValArg->getSourceRange(); 86 return true; 87 } 88 89 // Second argument should be a constant string. 90 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 91 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 92 if (!Literal || !Literal->isAscii()) { 93 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 94 << StrArg->getSourceRange(); 95 return true; 96 } 97 98 TheCall->setType(Ty); 99 return false; 100 } 101 102 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 103 // We need at least one argument. 104 if (TheCall->getNumArgs() < 1) { 105 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 106 << 0 << 1 << TheCall->getNumArgs() 107 << TheCall->getCallee()->getSourceRange(); 108 return true; 109 } 110 111 // All arguments should be wide string literals. 112 for (Expr *Arg : TheCall->arguments()) { 113 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 114 if (!Literal || !Literal->isWide()) { 115 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str) 116 << Arg->getSourceRange(); 117 return true; 118 } 119 } 120 121 return false; 122 } 123 124 /// Check that the argument to __builtin_addressof is a glvalue, and set the 125 /// result type to the corresponding pointer type. 126 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 127 if (checkArgCount(S, TheCall, 1)) 128 return true; 129 130 ExprResult Arg(TheCall->getArg(0)); 131 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 132 if (ResultType.isNull()) 133 return true; 134 135 TheCall->setArg(0, Arg.get()); 136 TheCall->setType(ResultType); 137 return false; 138 } 139 140 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 141 if (checkArgCount(S, TheCall, 3)) 142 return true; 143 144 // First two arguments should be integers. 145 for (unsigned I = 0; I < 2; ++I) { 146 Expr *Arg = TheCall->getArg(I); 147 QualType Ty = Arg->getType(); 148 if (!Ty->isIntegerType()) { 149 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 150 << Ty << Arg->getSourceRange(); 151 return true; 152 } 153 } 154 155 // Third argument should be a pointer to a non-const integer. 156 // IRGen correctly handles volatile, restrict, and address spaces, and 157 // the other qualifiers aren't possible. 158 { 159 Expr *Arg = TheCall->getArg(2); 160 QualType Ty = Arg->getType(); 161 const auto *PtrTy = Ty->getAs<PointerType>(); 162 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 163 !PtrTy->getPointeeType().isConstQualified())) { 164 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 165 << Ty << Arg->getSourceRange(); 166 return true; 167 } 168 } 169 170 return false; 171 } 172 173 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 174 CallExpr *TheCall, unsigned SizeIdx, 175 unsigned DstSizeIdx) { 176 if (TheCall->getNumArgs() <= SizeIdx || 177 TheCall->getNumArgs() <= DstSizeIdx) 178 return; 179 180 const Expr *SizeArg = TheCall->getArg(SizeIdx); 181 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 182 183 llvm::APSInt Size, DstSize; 184 185 // find out if both sizes are known at compile time 186 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 187 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 188 return; 189 190 if (Size.ule(DstSize)) 191 return; 192 193 // confirmed overflow so generate the diagnostic. 194 IdentifierInfo *FnName = FDecl->getIdentifier(); 195 SourceLocation SL = TheCall->getLocStart(); 196 SourceRange SR = TheCall->getSourceRange(); 197 198 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 199 } 200 201 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 202 if (checkArgCount(S, BuiltinCall, 2)) 203 return true; 204 205 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 206 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 207 Expr *Call = BuiltinCall->getArg(0); 208 Expr *Chain = BuiltinCall->getArg(1); 209 210 if (Call->getStmtClass() != Stmt::CallExprClass) { 211 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 212 << Call->getSourceRange(); 213 return true; 214 } 215 216 auto CE = cast<CallExpr>(Call); 217 if (CE->getCallee()->getType()->isBlockPointerType()) { 218 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 219 << Call->getSourceRange(); 220 return true; 221 } 222 223 const Decl *TargetDecl = CE->getCalleeDecl(); 224 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 225 if (FD->getBuiltinID()) { 226 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 227 << Call->getSourceRange(); 228 return true; 229 } 230 231 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 232 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 233 << Call->getSourceRange(); 234 return true; 235 } 236 237 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 238 if (ChainResult.isInvalid()) 239 return true; 240 if (!ChainResult.get()->getType()->isPointerType()) { 241 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 242 << Chain->getSourceRange(); 243 return true; 244 } 245 246 QualType ReturnTy = CE->getCallReturnType(S.Context); 247 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 248 QualType BuiltinTy = S.Context.getFunctionType( 249 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 250 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 251 252 Builtin = 253 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 254 255 BuiltinCall->setType(CE->getType()); 256 BuiltinCall->setValueKind(CE->getValueKind()); 257 BuiltinCall->setObjectKind(CE->getObjectKind()); 258 BuiltinCall->setCallee(Builtin); 259 BuiltinCall->setArg(1, ChainResult.get()); 260 261 return false; 262 } 263 264 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 265 Scope::ScopeFlags NeededScopeFlags, 266 unsigned DiagID) { 267 // Scopes aren't available during instantiation. Fortunately, builtin 268 // functions cannot be template args so they cannot be formed through template 269 // instantiation. Therefore checking once during the parse is sufficient. 270 if (SemaRef.inTemplateInstantiation()) 271 return false; 272 273 Scope *S = SemaRef.getCurScope(); 274 while (S && !S->isSEHExceptScope()) 275 S = S->getParent(); 276 if (!S || !(S->getFlags() & NeededScopeFlags)) { 277 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 278 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 279 << DRE->getDecl()->getIdentifier(); 280 return true; 281 } 282 283 return false; 284 } 285 286 static inline bool isBlockPointer(Expr *Arg) { 287 return Arg->getType()->isBlockPointerType(); 288 } 289 290 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 291 /// void*, which is a requirement of device side enqueue. 292 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 293 const BlockPointerType *BPT = 294 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 295 ArrayRef<QualType> Params = 296 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 297 unsigned ArgCounter = 0; 298 bool IllegalParams = false; 299 // Iterate through the block parameters until either one is found that is not 300 // a local void*, or the block is valid. 301 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 302 I != E; ++I, ++ArgCounter) { 303 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 304 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 305 LangAS::opencl_local) { 306 // Get the location of the error. If a block literal has been passed 307 // (BlockExpr) then we can point straight to the offending argument, 308 // else we just point to the variable reference. 309 SourceLocation ErrorLoc; 310 if (isa<BlockExpr>(BlockArg)) { 311 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 312 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 313 } else if (isa<DeclRefExpr>(BlockArg)) { 314 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 315 } 316 S.Diag(ErrorLoc, 317 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 318 IllegalParams = true; 319 } 320 } 321 322 return IllegalParams; 323 } 324 325 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 326 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 327 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension) 328 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 329 return true; 330 } 331 return false; 332 } 333 334 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 335 if (checkArgCount(S, TheCall, 2)) 336 return true; 337 338 if (checkOpenCLSubgroupExt(S, TheCall)) 339 return true; 340 341 // First argument is an ndrange_t type. 342 Expr *NDRangeArg = TheCall->getArg(0); 343 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 344 S.Diag(NDRangeArg->getLocStart(), 345 diag::err_opencl_builtin_expected_type) 346 << TheCall->getDirectCallee() << "'ndrange_t'"; 347 return true; 348 } 349 350 Expr *BlockArg = TheCall->getArg(1); 351 if (!isBlockPointer(BlockArg)) { 352 S.Diag(BlockArg->getLocStart(), 353 diag::err_opencl_builtin_expected_type) 354 << TheCall->getDirectCallee() << "block"; 355 return true; 356 } 357 return checkOpenCLBlockArgs(S, BlockArg); 358 } 359 360 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 361 /// get_kernel_work_group_size 362 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 363 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 364 if (checkArgCount(S, TheCall, 1)) 365 return true; 366 367 Expr *BlockArg = TheCall->getArg(0); 368 if (!isBlockPointer(BlockArg)) { 369 S.Diag(BlockArg->getLocStart(), 370 diag::err_opencl_builtin_expected_type) 371 << TheCall->getDirectCallee() << "block"; 372 return true; 373 } 374 return checkOpenCLBlockArgs(S, BlockArg); 375 } 376 377 /// Diagnose integer type and any valid implicit conversion to it. 378 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 379 const QualType &IntType); 380 381 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 382 unsigned Start, unsigned End) { 383 bool IllegalParams = false; 384 for (unsigned I = Start; I <= End; ++I) 385 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 386 S.Context.getSizeType()); 387 return IllegalParams; 388 } 389 390 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 391 /// 'local void*' parameter of passed block. 392 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 393 Expr *BlockArg, 394 unsigned NumNonVarArgs) { 395 const BlockPointerType *BPT = 396 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 397 unsigned NumBlockParams = 398 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 399 unsigned TotalNumArgs = TheCall->getNumArgs(); 400 401 // For each argument passed to the block, a corresponding uint needs to 402 // be passed to describe the size of the local memory. 403 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 404 S.Diag(TheCall->getLocStart(), 405 diag::err_opencl_enqueue_kernel_local_size_args); 406 return true; 407 } 408 409 // Check that the sizes of the local memory are specified by integers. 410 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 411 TotalNumArgs - 1); 412 } 413 414 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 415 /// overload formats specified in Table 6.13.17.1. 416 /// int enqueue_kernel(queue_t queue, 417 /// kernel_enqueue_flags_t flags, 418 /// const ndrange_t ndrange, 419 /// void (^block)(void)) 420 /// int enqueue_kernel(queue_t queue, 421 /// kernel_enqueue_flags_t flags, 422 /// const ndrange_t ndrange, 423 /// uint num_events_in_wait_list, 424 /// clk_event_t *event_wait_list, 425 /// clk_event_t *event_ret, 426 /// void (^block)(void)) 427 /// int enqueue_kernel(queue_t queue, 428 /// kernel_enqueue_flags_t flags, 429 /// const ndrange_t ndrange, 430 /// void (^block)(local void*, ...), 431 /// uint size0, ...) 432 /// int enqueue_kernel(queue_t queue, 433 /// kernel_enqueue_flags_t flags, 434 /// const ndrange_t ndrange, 435 /// uint num_events_in_wait_list, 436 /// clk_event_t *event_wait_list, 437 /// clk_event_t *event_ret, 438 /// void (^block)(local void*, ...), 439 /// uint size0, ...) 440 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 441 unsigned NumArgs = TheCall->getNumArgs(); 442 443 if (NumArgs < 4) { 444 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 445 return true; 446 } 447 448 Expr *Arg0 = TheCall->getArg(0); 449 Expr *Arg1 = TheCall->getArg(1); 450 Expr *Arg2 = TheCall->getArg(2); 451 Expr *Arg3 = TheCall->getArg(3); 452 453 // First argument always needs to be a queue_t type. 454 if (!Arg0->getType()->isQueueT()) { 455 S.Diag(TheCall->getArg(0)->getLocStart(), 456 diag::err_opencl_builtin_expected_type) 457 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 458 return true; 459 } 460 461 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 462 if (!Arg1->getType()->isIntegerType()) { 463 S.Diag(TheCall->getArg(1)->getLocStart(), 464 diag::err_opencl_builtin_expected_type) 465 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 466 return true; 467 } 468 469 // Third argument is always an ndrange_t type. 470 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 471 S.Diag(TheCall->getArg(2)->getLocStart(), 472 diag::err_opencl_builtin_expected_type) 473 << TheCall->getDirectCallee() << "'ndrange_t'"; 474 return true; 475 } 476 477 // With four arguments, there is only one form that the function could be 478 // called in: no events and no variable arguments. 479 if (NumArgs == 4) { 480 // check that the last argument is the right block type. 481 if (!isBlockPointer(Arg3)) { 482 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type) 483 << TheCall->getDirectCallee() << "block"; 484 return true; 485 } 486 // we have a block type, check the prototype 487 const BlockPointerType *BPT = 488 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 489 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 490 S.Diag(Arg3->getLocStart(), 491 diag::err_opencl_enqueue_kernel_blocks_no_args); 492 return true; 493 } 494 return false; 495 } 496 // we can have block + varargs. 497 if (isBlockPointer(Arg3)) 498 return (checkOpenCLBlockArgs(S, Arg3) || 499 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 500 // last two cases with either exactly 7 args or 7 args and varargs. 501 if (NumArgs >= 7) { 502 // check common block argument. 503 Expr *Arg6 = TheCall->getArg(6); 504 if (!isBlockPointer(Arg6)) { 505 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type) 506 << TheCall->getDirectCallee() << "block"; 507 return true; 508 } 509 if (checkOpenCLBlockArgs(S, Arg6)) 510 return true; 511 512 // Forth argument has to be any integer type. 513 if (!Arg3->getType()->isIntegerType()) { 514 S.Diag(TheCall->getArg(3)->getLocStart(), 515 diag::err_opencl_builtin_expected_type) 516 << TheCall->getDirectCallee() << "integer"; 517 return true; 518 } 519 // check remaining common arguments. 520 Expr *Arg4 = TheCall->getArg(4); 521 Expr *Arg5 = TheCall->getArg(5); 522 523 // Fifth argument is always passed as a pointer to clk_event_t. 524 if (!Arg4->isNullPointerConstant(S.Context, 525 Expr::NPC_ValueDependentIsNotNull) && 526 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 527 S.Diag(TheCall->getArg(4)->getLocStart(), 528 diag::err_opencl_builtin_expected_type) 529 << TheCall->getDirectCallee() 530 << S.Context.getPointerType(S.Context.OCLClkEventTy); 531 return true; 532 } 533 534 // Sixth argument is always passed as a pointer to clk_event_t. 535 if (!Arg5->isNullPointerConstant(S.Context, 536 Expr::NPC_ValueDependentIsNotNull) && 537 !(Arg5->getType()->isPointerType() && 538 Arg5->getType()->getPointeeType()->isClkEventT())) { 539 S.Diag(TheCall->getArg(5)->getLocStart(), 540 diag::err_opencl_builtin_expected_type) 541 << TheCall->getDirectCallee() 542 << S.Context.getPointerType(S.Context.OCLClkEventTy); 543 return true; 544 } 545 546 if (NumArgs == 7) 547 return false; 548 549 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 550 } 551 552 // None of the specific case has been detected, give generic error 553 S.Diag(TheCall->getLocStart(), 554 diag::err_opencl_enqueue_kernel_incorrect_args); 555 return true; 556 } 557 558 /// Returns OpenCL access qual. 559 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 560 return D->getAttr<OpenCLAccessAttr>(); 561 } 562 563 /// Returns true if pipe element type is different from the pointer. 564 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 565 const Expr *Arg0 = Call->getArg(0); 566 // First argument type should always be pipe. 567 if (!Arg0->getType()->isPipeType()) { 568 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 569 << Call->getDirectCallee() << Arg0->getSourceRange(); 570 return true; 571 } 572 OpenCLAccessAttr *AccessQual = 573 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 574 // Validates the access qualifier is compatible with the call. 575 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 576 // read_only and write_only, and assumed to be read_only if no qualifier is 577 // specified. 578 switch (Call->getDirectCallee()->getBuiltinID()) { 579 case Builtin::BIread_pipe: 580 case Builtin::BIreserve_read_pipe: 581 case Builtin::BIcommit_read_pipe: 582 case Builtin::BIwork_group_reserve_read_pipe: 583 case Builtin::BIsub_group_reserve_read_pipe: 584 case Builtin::BIwork_group_commit_read_pipe: 585 case Builtin::BIsub_group_commit_read_pipe: 586 if (!(!AccessQual || AccessQual->isReadOnly())) { 587 S.Diag(Arg0->getLocStart(), 588 diag::err_opencl_builtin_pipe_invalid_access_modifier) 589 << "read_only" << Arg0->getSourceRange(); 590 return true; 591 } 592 break; 593 case Builtin::BIwrite_pipe: 594 case Builtin::BIreserve_write_pipe: 595 case Builtin::BIcommit_write_pipe: 596 case Builtin::BIwork_group_reserve_write_pipe: 597 case Builtin::BIsub_group_reserve_write_pipe: 598 case Builtin::BIwork_group_commit_write_pipe: 599 case Builtin::BIsub_group_commit_write_pipe: 600 if (!(AccessQual && AccessQual->isWriteOnly())) { 601 S.Diag(Arg0->getLocStart(), 602 diag::err_opencl_builtin_pipe_invalid_access_modifier) 603 << "write_only" << Arg0->getSourceRange(); 604 return true; 605 } 606 break; 607 default: 608 break; 609 } 610 return false; 611 } 612 613 /// Returns true if pipe element type is different from the pointer. 614 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 615 const Expr *Arg0 = Call->getArg(0); 616 const Expr *ArgIdx = Call->getArg(Idx); 617 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 618 const QualType EltTy = PipeTy->getElementType(); 619 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 620 // The Idx argument should be a pointer and the type of the pointer and 621 // the type of pipe element should also be the same. 622 if (!ArgTy || 623 !S.Context.hasSameType( 624 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 625 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 626 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 627 << ArgIdx->getType() << ArgIdx->getSourceRange(); 628 return true; 629 } 630 return false; 631 } 632 633 // \brief Performs semantic analysis for the read/write_pipe call. 634 // \param S Reference to the semantic analyzer. 635 // \param Call A pointer to the builtin call. 636 // \return True if a semantic error has been found, false otherwise. 637 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 638 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 639 // functions have two forms. 640 switch (Call->getNumArgs()) { 641 case 2: { 642 if (checkOpenCLPipeArg(S, Call)) 643 return true; 644 // The call with 2 arguments should be 645 // read/write_pipe(pipe T, T*). 646 // Check packet type T. 647 if (checkOpenCLPipePacketType(S, Call, 1)) 648 return true; 649 } break; 650 651 case 4: { 652 if (checkOpenCLPipeArg(S, Call)) 653 return true; 654 // The call with 4 arguments should be 655 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 656 // Check reserve_id_t. 657 if (!Call->getArg(1)->getType()->isReserveIDT()) { 658 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 659 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 660 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 661 return true; 662 } 663 664 // Check the index. 665 const Expr *Arg2 = Call->getArg(2); 666 if (!Arg2->getType()->isIntegerType() && 667 !Arg2->getType()->isUnsignedIntegerType()) { 668 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 669 << Call->getDirectCallee() << S.Context.UnsignedIntTy 670 << Arg2->getType() << Arg2->getSourceRange(); 671 return true; 672 } 673 674 // Check packet type T. 675 if (checkOpenCLPipePacketType(S, Call, 3)) 676 return true; 677 } break; 678 default: 679 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 680 << Call->getDirectCallee() << Call->getSourceRange(); 681 return true; 682 } 683 684 return false; 685 } 686 687 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 688 // /_}reserve_{read/write}_pipe 689 // \param S Reference to the semantic analyzer. 690 // \param Call The call to the builtin function to be analyzed. 691 // \return True if a semantic error was found, false otherwise. 692 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 693 if (checkArgCount(S, Call, 2)) 694 return true; 695 696 if (checkOpenCLPipeArg(S, Call)) 697 return true; 698 699 // Check the reserve size. 700 if (!Call->getArg(1)->getType()->isIntegerType() && 701 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 702 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 703 << Call->getDirectCallee() << S.Context.UnsignedIntTy 704 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 705 return true; 706 } 707 708 // Since return type of reserve_read/write_pipe built-in function is 709 // reserve_id_t, which is not defined in the builtin def file , we used int 710 // as return type and need to override the return type of these functions. 711 Call->setType(S.Context.OCLReserveIDTy); 712 713 return false; 714 } 715 716 // \brief Performs a semantic analysis on {work_group_/sub_group_ 717 // /_}commit_{read/write}_pipe 718 // \param S Reference to the semantic analyzer. 719 // \param Call The call to the builtin function to be analyzed. 720 // \return True if a semantic error was found, false otherwise. 721 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 722 if (checkArgCount(S, Call, 2)) 723 return true; 724 725 if (checkOpenCLPipeArg(S, Call)) 726 return true; 727 728 // Check reserve_id_t. 729 if (!Call->getArg(1)->getType()->isReserveIDT()) { 730 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 731 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 732 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 733 return true; 734 } 735 736 return false; 737 } 738 739 // \brief Performs a semantic analysis on the call to built-in Pipe 740 // Query Functions. 741 // \param S Reference to the semantic analyzer. 742 // \param Call The call to the builtin function to be analyzed. 743 // \return True if a semantic error was found, false otherwise. 744 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 745 if (checkArgCount(S, Call, 1)) 746 return true; 747 748 if (!Call->getArg(0)->getType()->isPipeType()) { 749 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 750 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 751 return true; 752 } 753 754 return false; 755 } 756 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 757 // \brief Performs semantic analysis for the to_global/local/private call. 758 // \param S Reference to the semantic analyzer. 759 // \param BuiltinID ID of the builtin function. 760 // \param Call A pointer to the builtin call. 761 // \return True if a semantic error has been found, false otherwise. 762 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 763 CallExpr *Call) { 764 if (Call->getNumArgs() != 1) { 765 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 766 << Call->getDirectCallee() << Call->getSourceRange(); 767 return true; 768 } 769 770 auto RT = Call->getArg(0)->getType(); 771 if (!RT->isPointerType() || RT->getPointeeType() 772 .getAddressSpace() == LangAS::opencl_constant) { 773 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 774 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 775 return true; 776 } 777 778 RT = RT->getPointeeType(); 779 auto Qual = RT.getQualifiers(); 780 switch (BuiltinID) { 781 case Builtin::BIto_global: 782 Qual.setAddressSpace(LangAS::opencl_global); 783 break; 784 case Builtin::BIto_local: 785 Qual.setAddressSpace(LangAS::opencl_local); 786 break; 787 case Builtin::BIto_private: 788 Qual.setAddressSpace(LangAS::opencl_private); 789 break; 790 default: 791 llvm_unreachable("Invalid builtin function"); 792 } 793 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 794 RT.getUnqualifiedType(), Qual))); 795 796 return false; 797 } 798 799 ExprResult 800 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 801 CallExpr *TheCall) { 802 ExprResult TheCallResult(TheCall); 803 804 // Find out if any arguments are required to be integer constant expressions. 805 unsigned ICEArguments = 0; 806 ASTContext::GetBuiltinTypeError Error; 807 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 808 if (Error != ASTContext::GE_None) 809 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 810 811 // If any arguments are required to be ICE's, check and diagnose. 812 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 813 // Skip arguments not required to be ICE's. 814 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 815 816 llvm::APSInt Result; 817 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 818 return true; 819 ICEArguments &= ~(1 << ArgNo); 820 } 821 822 switch (BuiltinID) { 823 case Builtin::BI__builtin___CFStringMakeConstantString: 824 assert(TheCall->getNumArgs() == 1 && 825 "Wrong # arguments to builtin CFStringMakeConstantString"); 826 if (CheckObjCString(TheCall->getArg(0))) 827 return ExprError(); 828 break; 829 case Builtin::BI__builtin_ms_va_start: 830 case Builtin::BI__builtin_stdarg_start: 831 case Builtin::BI__builtin_va_start: 832 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 833 return ExprError(); 834 break; 835 case Builtin::BI__va_start: { 836 switch (Context.getTargetInfo().getTriple().getArch()) { 837 case llvm::Triple::arm: 838 case llvm::Triple::thumb: 839 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 840 return ExprError(); 841 break; 842 default: 843 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 844 return ExprError(); 845 break; 846 } 847 break; 848 } 849 case Builtin::BI__builtin_isgreater: 850 case Builtin::BI__builtin_isgreaterequal: 851 case Builtin::BI__builtin_isless: 852 case Builtin::BI__builtin_islessequal: 853 case Builtin::BI__builtin_islessgreater: 854 case Builtin::BI__builtin_isunordered: 855 if (SemaBuiltinUnorderedCompare(TheCall)) 856 return ExprError(); 857 break; 858 case Builtin::BI__builtin_fpclassify: 859 if (SemaBuiltinFPClassification(TheCall, 6)) 860 return ExprError(); 861 break; 862 case Builtin::BI__builtin_isfinite: 863 case Builtin::BI__builtin_isinf: 864 case Builtin::BI__builtin_isinf_sign: 865 case Builtin::BI__builtin_isnan: 866 case Builtin::BI__builtin_isnormal: 867 if (SemaBuiltinFPClassification(TheCall, 1)) 868 return ExprError(); 869 break; 870 case Builtin::BI__builtin_shufflevector: 871 return SemaBuiltinShuffleVector(TheCall); 872 // TheCall will be freed by the smart pointer here, but that's fine, since 873 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 874 case Builtin::BI__builtin_prefetch: 875 if (SemaBuiltinPrefetch(TheCall)) 876 return ExprError(); 877 break; 878 case Builtin::BI__builtin_alloca_with_align: 879 if (SemaBuiltinAllocaWithAlign(TheCall)) 880 return ExprError(); 881 break; 882 case Builtin::BI__assume: 883 case Builtin::BI__builtin_assume: 884 if (SemaBuiltinAssume(TheCall)) 885 return ExprError(); 886 break; 887 case Builtin::BI__builtin_assume_aligned: 888 if (SemaBuiltinAssumeAligned(TheCall)) 889 return ExprError(); 890 break; 891 case Builtin::BI__builtin_object_size: 892 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 893 return ExprError(); 894 break; 895 case Builtin::BI__builtin_longjmp: 896 if (SemaBuiltinLongjmp(TheCall)) 897 return ExprError(); 898 break; 899 case Builtin::BI__builtin_setjmp: 900 if (SemaBuiltinSetjmp(TheCall)) 901 return ExprError(); 902 break; 903 case Builtin::BI_setjmp: 904 case Builtin::BI_setjmpex: 905 if (checkArgCount(*this, TheCall, 1)) 906 return true; 907 break; 908 909 case Builtin::BI__builtin_classify_type: 910 if (checkArgCount(*this, TheCall, 1)) return true; 911 TheCall->setType(Context.IntTy); 912 break; 913 case Builtin::BI__builtin_constant_p: 914 if (checkArgCount(*this, TheCall, 1)) return true; 915 TheCall->setType(Context.IntTy); 916 break; 917 case Builtin::BI__sync_fetch_and_add: 918 case Builtin::BI__sync_fetch_and_add_1: 919 case Builtin::BI__sync_fetch_and_add_2: 920 case Builtin::BI__sync_fetch_and_add_4: 921 case Builtin::BI__sync_fetch_and_add_8: 922 case Builtin::BI__sync_fetch_and_add_16: 923 case Builtin::BI__sync_fetch_and_sub: 924 case Builtin::BI__sync_fetch_and_sub_1: 925 case Builtin::BI__sync_fetch_and_sub_2: 926 case Builtin::BI__sync_fetch_and_sub_4: 927 case Builtin::BI__sync_fetch_and_sub_8: 928 case Builtin::BI__sync_fetch_and_sub_16: 929 case Builtin::BI__sync_fetch_and_or: 930 case Builtin::BI__sync_fetch_and_or_1: 931 case Builtin::BI__sync_fetch_and_or_2: 932 case Builtin::BI__sync_fetch_and_or_4: 933 case Builtin::BI__sync_fetch_and_or_8: 934 case Builtin::BI__sync_fetch_and_or_16: 935 case Builtin::BI__sync_fetch_and_and: 936 case Builtin::BI__sync_fetch_and_and_1: 937 case Builtin::BI__sync_fetch_and_and_2: 938 case Builtin::BI__sync_fetch_and_and_4: 939 case Builtin::BI__sync_fetch_and_and_8: 940 case Builtin::BI__sync_fetch_and_and_16: 941 case Builtin::BI__sync_fetch_and_xor: 942 case Builtin::BI__sync_fetch_and_xor_1: 943 case Builtin::BI__sync_fetch_and_xor_2: 944 case Builtin::BI__sync_fetch_and_xor_4: 945 case Builtin::BI__sync_fetch_and_xor_8: 946 case Builtin::BI__sync_fetch_and_xor_16: 947 case Builtin::BI__sync_fetch_and_nand: 948 case Builtin::BI__sync_fetch_and_nand_1: 949 case Builtin::BI__sync_fetch_and_nand_2: 950 case Builtin::BI__sync_fetch_and_nand_4: 951 case Builtin::BI__sync_fetch_and_nand_8: 952 case Builtin::BI__sync_fetch_and_nand_16: 953 case Builtin::BI__sync_add_and_fetch: 954 case Builtin::BI__sync_add_and_fetch_1: 955 case Builtin::BI__sync_add_and_fetch_2: 956 case Builtin::BI__sync_add_and_fetch_4: 957 case Builtin::BI__sync_add_and_fetch_8: 958 case Builtin::BI__sync_add_and_fetch_16: 959 case Builtin::BI__sync_sub_and_fetch: 960 case Builtin::BI__sync_sub_and_fetch_1: 961 case Builtin::BI__sync_sub_and_fetch_2: 962 case Builtin::BI__sync_sub_and_fetch_4: 963 case Builtin::BI__sync_sub_and_fetch_8: 964 case Builtin::BI__sync_sub_and_fetch_16: 965 case Builtin::BI__sync_and_and_fetch: 966 case Builtin::BI__sync_and_and_fetch_1: 967 case Builtin::BI__sync_and_and_fetch_2: 968 case Builtin::BI__sync_and_and_fetch_4: 969 case Builtin::BI__sync_and_and_fetch_8: 970 case Builtin::BI__sync_and_and_fetch_16: 971 case Builtin::BI__sync_or_and_fetch: 972 case Builtin::BI__sync_or_and_fetch_1: 973 case Builtin::BI__sync_or_and_fetch_2: 974 case Builtin::BI__sync_or_and_fetch_4: 975 case Builtin::BI__sync_or_and_fetch_8: 976 case Builtin::BI__sync_or_and_fetch_16: 977 case Builtin::BI__sync_xor_and_fetch: 978 case Builtin::BI__sync_xor_and_fetch_1: 979 case Builtin::BI__sync_xor_and_fetch_2: 980 case Builtin::BI__sync_xor_and_fetch_4: 981 case Builtin::BI__sync_xor_and_fetch_8: 982 case Builtin::BI__sync_xor_and_fetch_16: 983 case Builtin::BI__sync_nand_and_fetch: 984 case Builtin::BI__sync_nand_and_fetch_1: 985 case Builtin::BI__sync_nand_and_fetch_2: 986 case Builtin::BI__sync_nand_and_fetch_4: 987 case Builtin::BI__sync_nand_and_fetch_8: 988 case Builtin::BI__sync_nand_and_fetch_16: 989 case Builtin::BI__sync_val_compare_and_swap: 990 case Builtin::BI__sync_val_compare_and_swap_1: 991 case Builtin::BI__sync_val_compare_and_swap_2: 992 case Builtin::BI__sync_val_compare_and_swap_4: 993 case Builtin::BI__sync_val_compare_and_swap_8: 994 case Builtin::BI__sync_val_compare_and_swap_16: 995 case Builtin::BI__sync_bool_compare_and_swap: 996 case Builtin::BI__sync_bool_compare_and_swap_1: 997 case Builtin::BI__sync_bool_compare_and_swap_2: 998 case Builtin::BI__sync_bool_compare_and_swap_4: 999 case Builtin::BI__sync_bool_compare_and_swap_8: 1000 case Builtin::BI__sync_bool_compare_and_swap_16: 1001 case Builtin::BI__sync_lock_test_and_set: 1002 case Builtin::BI__sync_lock_test_and_set_1: 1003 case Builtin::BI__sync_lock_test_and_set_2: 1004 case Builtin::BI__sync_lock_test_and_set_4: 1005 case Builtin::BI__sync_lock_test_and_set_8: 1006 case Builtin::BI__sync_lock_test_and_set_16: 1007 case Builtin::BI__sync_lock_release: 1008 case Builtin::BI__sync_lock_release_1: 1009 case Builtin::BI__sync_lock_release_2: 1010 case Builtin::BI__sync_lock_release_4: 1011 case Builtin::BI__sync_lock_release_8: 1012 case Builtin::BI__sync_lock_release_16: 1013 case Builtin::BI__sync_swap: 1014 case Builtin::BI__sync_swap_1: 1015 case Builtin::BI__sync_swap_2: 1016 case Builtin::BI__sync_swap_4: 1017 case Builtin::BI__sync_swap_8: 1018 case Builtin::BI__sync_swap_16: 1019 return SemaBuiltinAtomicOverloaded(TheCallResult); 1020 case Builtin::BI__builtin_nontemporal_load: 1021 case Builtin::BI__builtin_nontemporal_store: 1022 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1023 #define BUILTIN(ID, TYPE, ATTRS) 1024 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1025 case Builtin::BI##ID: \ 1026 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1027 #include "clang/Basic/Builtins.def" 1028 case Builtin::BI__annotation: 1029 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1030 return ExprError(); 1031 break; 1032 case Builtin::BI__builtin_annotation: 1033 if (SemaBuiltinAnnotation(*this, TheCall)) 1034 return ExprError(); 1035 break; 1036 case Builtin::BI__builtin_addressof: 1037 if (SemaBuiltinAddressof(*this, TheCall)) 1038 return ExprError(); 1039 break; 1040 case Builtin::BI__builtin_add_overflow: 1041 case Builtin::BI__builtin_sub_overflow: 1042 case Builtin::BI__builtin_mul_overflow: 1043 if (SemaBuiltinOverflow(*this, TheCall)) 1044 return ExprError(); 1045 break; 1046 case Builtin::BI__builtin_operator_new: 1047 case Builtin::BI__builtin_operator_delete: 1048 if (!getLangOpts().CPlusPlus) { 1049 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 1050 << (BuiltinID == Builtin::BI__builtin_operator_new 1051 ? "__builtin_operator_new" 1052 : "__builtin_operator_delete") 1053 << "C++"; 1054 return ExprError(); 1055 } 1056 // CodeGen assumes it can find the global new and delete to call, 1057 // so ensure that they are declared. 1058 DeclareGlobalNewDelete(); 1059 break; 1060 1061 // check secure string manipulation functions where overflows 1062 // are detectable at compile time 1063 case Builtin::BI__builtin___memcpy_chk: 1064 case Builtin::BI__builtin___memmove_chk: 1065 case Builtin::BI__builtin___memset_chk: 1066 case Builtin::BI__builtin___strlcat_chk: 1067 case Builtin::BI__builtin___strlcpy_chk: 1068 case Builtin::BI__builtin___strncat_chk: 1069 case Builtin::BI__builtin___strncpy_chk: 1070 case Builtin::BI__builtin___stpncpy_chk: 1071 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1072 break; 1073 case Builtin::BI__builtin___memccpy_chk: 1074 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1075 break; 1076 case Builtin::BI__builtin___snprintf_chk: 1077 case Builtin::BI__builtin___vsnprintf_chk: 1078 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1079 break; 1080 case Builtin::BI__builtin_call_with_static_chain: 1081 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1082 return ExprError(); 1083 break; 1084 case Builtin::BI__exception_code: 1085 case Builtin::BI_exception_code: 1086 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1087 diag::err_seh___except_block)) 1088 return ExprError(); 1089 break; 1090 case Builtin::BI__exception_info: 1091 case Builtin::BI_exception_info: 1092 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1093 diag::err_seh___except_filter)) 1094 return ExprError(); 1095 break; 1096 case Builtin::BI__GetExceptionInfo: 1097 if (checkArgCount(*this, TheCall, 1)) 1098 return ExprError(); 1099 1100 if (CheckCXXThrowOperand( 1101 TheCall->getLocStart(), 1102 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1103 TheCall)) 1104 return ExprError(); 1105 1106 TheCall->setType(Context.VoidPtrTy); 1107 break; 1108 // OpenCL v2.0, s6.13.16 - Pipe functions 1109 case Builtin::BIread_pipe: 1110 case Builtin::BIwrite_pipe: 1111 // Since those two functions are declared with var args, we need a semantic 1112 // check for the argument. 1113 if (SemaBuiltinRWPipe(*this, TheCall)) 1114 return ExprError(); 1115 TheCall->setType(Context.IntTy); 1116 break; 1117 case Builtin::BIreserve_read_pipe: 1118 case Builtin::BIreserve_write_pipe: 1119 case Builtin::BIwork_group_reserve_read_pipe: 1120 case Builtin::BIwork_group_reserve_write_pipe: 1121 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1122 return ExprError(); 1123 break; 1124 case Builtin::BIsub_group_reserve_read_pipe: 1125 case Builtin::BIsub_group_reserve_write_pipe: 1126 if (checkOpenCLSubgroupExt(*this, TheCall) || 1127 SemaBuiltinReserveRWPipe(*this, TheCall)) 1128 return ExprError(); 1129 break; 1130 case Builtin::BIcommit_read_pipe: 1131 case Builtin::BIcommit_write_pipe: 1132 case Builtin::BIwork_group_commit_read_pipe: 1133 case Builtin::BIwork_group_commit_write_pipe: 1134 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1135 return ExprError(); 1136 break; 1137 case Builtin::BIsub_group_commit_read_pipe: 1138 case Builtin::BIsub_group_commit_write_pipe: 1139 if (checkOpenCLSubgroupExt(*this, TheCall) || 1140 SemaBuiltinCommitRWPipe(*this, TheCall)) 1141 return ExprError(); 1142 break; 1143 case Builtin::BIget_pipe_num_packets: 1144 case Builtin::BIget_pipe_max_packets: 1145 if (SemaBuiltinPipePackets(*this, TheCall)) 1146 return ExprError(); 1147 TheCall->setType(Context.UnsignedIntTy); 1148 break; 1149 case Builtin::BIto_global: 1150 case Builtin::BIto_local: 1151 case Builtin::BIto_private: 1152 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1153 return ExprError(); 1154 break; 1155 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1156 case Builtin::BIenqueue_kernel: 1157 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1158 return ExprError(); 1159 break; 1160 case Builtin::BIget_kernel_work_group_size: 1161 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1162 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1163 return ExprError(); 1164 break; 1165 break; 1166 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1167 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1168 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1169 return ExprError(); 1170 break; 1171 case Builtin::BI__builtin_os_log_format: 1172 case Builtin::BI__builtin_os_log_format_buffer_size: 1173 if (SemaBuiltinOSLogFormat(TheCall)) { 1174 return ExprError(); 1175 } 1176 break; 1177 } 1178 1179 // Since the target specific builtins for each arch overlap, only check those 1180 // of the arch we are compiling for. 1181 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1182 switch (Context.getTargetInfo().getTriple().getArch()) { 1183 case llvm::Triple::arm: 1184 case llvm::Triple::armeb: 1185 case llvm::Triple::thumb: 1186 case llvm::Triple::thumbeb: 1187 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1188 return ExprError(); 1189 break; 1190 case llvm::Triple::aarch64: 1191 case llvm::Triple::aarch64_be: 1192 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1193 return ExprError(); 1194 break; 1195 case llvm::Triple::mips: 1196 case llvm::Triple::mipsel: 1197 case llvm::Triple::mips64: 1198 case llvm::Triple::mips64el: 1199 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1200 return ExprError(); 1201 break; 1202 case llvm::Triple::systemz: 1203 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1204 return ExprError(); 1205 break; 1206 case llvm::Triple::x86: 1207 case llvm::Triple::x86_64: 1208 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1209 return ExprError(); 1210 break; 1211 case llvm::Triple::ppc: 1212 case llvm::Triple::ppc64: 1213 case llvm::Triple::ppc64le: 1214 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1215 return ExprError(); 1216 break; 1217 default: 1218 break; 1219 } 1220 } 1221 1222 return TheCallResult; 1223 } 1224 1225 // Get the valid immediate range for the specified NEON type code. 1226 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1227 NeonTypeFlags Type(t); 1228 int IsQuad = ForceQuad ? true : Type.isQuad(); 1229 switch (Type.getEltType()) { 1230 case NeonTypeFlags::Int8: 1231 case NeonTypeFlags::Poly8: 1232 return shift ? 7 : (8 << IsQuad) - 1; 1233 case NeonTypeFlags::Int16: 1234 case NeonTypeFlags::Poly16: 1235 return shift ? 15 : (4 << IsQuad) - 1; 1236 case NeonTypeFlags::Int32: 1237 return shift ? 31 : (2 << IsQuad) - 1; 1238 case NeonTypeFlags::Int64: 1239 case NeonTypeFlags::Poly64: 1240 return shift ? 63 : (1 << IsQuad) - 1; 1241 case NeonTypeFlags::Poly128: 1242 return shift ? 127 : (1 << IsQuad) - 1; 1243 case NeonTypeFlags::Float16: 1244 assert(!shift && "cannot shift float types!"); 1245 return (4 << IsQuad) - 1; 1246 case NeonTypeFlags::Float32: 1247 assert(!shift && "cannot shift float types!"); 1248 return (2 << IsQuad) - 1; 1249 case NeonTypeFlags::Float64: 1250 assert(!shift && "cannot shift float types!"); 1251 return (1 << IsQuad) - 1; 1252 } 1253 llvm_unreachable("Invalid NeonTypeFlag!"); 1254 } 1255 1256 /// getNeonEltType - Return the QualType corresponding to the elements of 1257 /// the vector type specified by the NeonTypeFlags. This is used to check 1258 /// the pointer arguments for Neon load/store intrinsics. 1259 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1260 bool IsPolyUnsigned, bool IsInt64Long) { 1261 switch (Flags.getEltType()) { 1262 case NeonTypeFlags::Int8: 1263 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1264 case NeonTypeFlags::Int16: 1265 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1266 case NeonTypeFlags::Int32: 1267 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1268 case NeonTypeFlags::Int64: 1269 if (IsInt64Long) 1270 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1271 else 1272 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1273 : Context.LongLongTy; 1274 case NeonTypeFlags::Poly8: 1275 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1276 case NeonTypeFlags::Poly16: 1277 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1278 case NeonTypeFlags::Poly64: 1279 if (IsInt64Long) 1280 return Context.UnsignedLongTy; 1281 else 1282 return Context.UnsignedLongLongTy; 1283 case NeonTypeFlags::Poly128: 1284 break; 1285 case NeonTypeFlags::Float16: 1286 return Context.HalfTy; 1287 case NeonTypeFlags::Float32: 1288 return Context.FloatTy; 1289 case NeonTypeFlags::Float64: 1290 return Context.DoubleTy; 1291 } 1292 llvm_unreachable("Invalid NeonTypeFlag!"); 1293 } 1294 1295 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1296 llvm::APSInt Result; 1297 uint64_t mask = 0; 1298 unsigned TV = 0; 1299 int PtrArgNum = -1; 1300 bool HasConstPtr = false; 1301 switch (BuiltinID) { 1302 #define GET_NEON_OVERLOAD_CHECK 1303 #include "clang/Basic/arm_neon.inc" 1304 #undef GET_NEON_OVERLOAD_CHECK 1305 } 1306 1307 // For NEON intrinsics which are overloaded on vector element type, validate 1308 // the immediate which specifies which variant to emit. 1309 unsigned ImmArg = TheCall->getNumArgs()-1; 1310 if (mask) { 1311 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1312 return true; 1313 1314 TV = Result.getLimitedValue(64); 1315 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1316 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1317 << TheCall->getArg(ImmArg)->getSourceRange(); 1318 } 1319 1320 if (PtrArgNum >= 0) { 1321 // Check that pointer arguments have the specified type. 1322 Expr *Arg = TheCall->getArg(PtrArgNum); 1323 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1324 Arg = ICE->getSubExpr(); 1325 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1326 QualType RHSTy = RHS.get()->getType(); 1327 1328 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1329 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1330 Arch == llvm::Triple::aarch64_be; 1331 bool IsInt64Long = 1332 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1333 QualType EltTy = 1334 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1335 if (HasConstPtr) 1336 EltTy = EltTy.withConst(); 1337 QualType LHSTy = Context.getPointerType(EltTy); 1338 AssignConvertType ConvTy; 1339 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1340 if (RHS.isInvalid()) 1341 return true; 1342 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1343 RHS.get(), AA_Assigning)) 1344 return true; 1345 } 1346 1347 // For NEON intrinsics which take an immediate value as part of the 1348 // instruction, range check them here. 1349 unsigned i = 0, l = 0, u = 0; 1350 switch (BuiltinID) { 1351 default: 1352 return false; 1353 #define GET_NEON_IMMEDIATE_CHECK 1354 #include "clang/Basic/arm_neon.inc" 1355 #undef GET_NEON_IMMEDIATE_CHECK 1356 } 1357 1358 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1359 } 1360 1361 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1362 unsigned MaxWidth) { 1363 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1364 BuiltinID == ARM::BI__builtin_arm_ldaex || 1365 BuiltinID == ARM::BI__builtin_arm_strex || 1366 BuiltinID == ARM::BI__builtin_arm_stlex || 1367 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1368 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1369 BuiltinID == AArch64::BI__builtin_arm_strex || 1370 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1371 "unexpected ARM builtin"); 1372 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1373 BuiltinID == ARM::BI__builtin_arm_ldaex || 1374 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1375 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1376 1377 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1378 1379 // Ensure that we have the proper number of arguments. 1380 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1381 return true; 1382 1383 // Inspect the pointer argument of the atomic builtin. This should always be 1384 // a pointer type, whose element is an integral scalar or pointer type. 1385 // Because it is a pointer type, we don't have to worry about any implicit 1386 // casts here. 1387 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1388 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1389 if (PointerArgRes.isInvalid()) 1390 return true; 1391 PointerArg = PointerArgRes.get(); 1392 1393 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1394 if (!pointerType) { 1395 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1396 << PointerArg->getType() << PointerArg->getSourceRange(); 1397 return true; 1398 } 1399 1400 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1401 // task is to insert the appropriate casts into the AST. First work out just 1402 // what the appropriate type is. 1403 QualType ValType = pointerType->getPointeeType(); 1404 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1405 if (IsLdrex) 1406 AddrType.addConst(); 1407 1408 // Issue a warning if the cast is dodgy. 1409 CastKind CastNeeded = CK_NoOp; 1410 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1411 CastNeeded = CK_BitCast; 1412 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1413 << PointerArg->getType() 1414 << Context.getPointerType(AddrType) 1415 << AA_Passing << PointerArg->getSourceRange(); 1416 } 1417 1418 // Finally, do the cast and replace the argument with the corrected version. 1419 AddrType = Context.getPointerType(AddrType); 1420 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1421 if (PointerArgRes.isInvalid()) 1422 return true; 1423 PointerArg = PointerArgRes.get(); 1424 1425 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1426 1427 // In general, we allow ints, floats and pointers to be loaded and stored. 1428 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1429 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1430 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1431 << PointerArg->getType() << PointerArg->getSourceRange(); 1432 return true; 1433 } 1434 1435 // But ARM doesn't have instructions to deal with 128-bit versions. 1436 if (Context.getTypeSize(ValType) > MaxWidth) { 1437 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1438 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1439 << PointerArg->getType() << PointerArg->getSourceRange(); 1440 return true; 1441 } 1442 1443 switch (ValType.getObjCLifetime()) { 1444 case Qualifiers::OCL_None: 1445 case Qualifiers::OCL_ExplicitNone: 1446 // okay 1447 break; 1448 1449 case Qualifiers::OCL_Weak: 1450 case Qualifiers::OCL_Strong: 1451 case Qualifiers::OCL_Autoreleasing: 1452 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1453 << ValType << PointerArg->getSourceRange(); 1454 return true; 1455 } 1456 1457 if (IsLdrex) { 1458 TheCall->setType(ValType); 1459 return false; 1460 } 1461 1462 // Initialize the argument to be stored. 1463 ExprResult ValArg = TheCall->getArg(0); 1464 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1465 Context, ValType, /*consume*/ false); 1466 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1467 if (ValArg.isInvalid()) 1468 return true; 1469 TheCall->setArg(0, ValArg.get()); 1470 1471 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1472 // but the custom checker bypasses all default analysis. 1473 TheCall->setType(Context.IntTy); 1474 return false; 1475 } 1476 1477 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1478 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1479 BuiltinID == ARM::BI__builtin_arm_ldaex || 1480 BuiltinID == ARM::BI__builtin_arm_strex || 1481 BuiltinID == ARM::BI__builtin_arm_stlex) { 1482 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1483 } 1484 1485 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1486 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1487 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1488 } 1489 1490 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1491 BuiltinID == ARM::BI__builtin_arm_wsr64) 1492 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1493 1494 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1495 BuiltinID == ARM::BI__builtin_arm_rsrp || 1496 BuiltinID == ARM::BI__builtin_arm_wsr || 1497 BuiltinID == ARM::BI__builtin_arm_wsrp) 1498 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1499 1500 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1501 return true; 1502 1503 // For intrinsics which take an immediate value as part of the instruction, 1504 // range check them here. 1505 unsigned i = 0, l = 0, u = 0; 1506 switch (BuiltinID) { 1507 default: return false; 1508 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1509 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1510 case ARM::BI__builtin_arm_vcvtr_f: 1511 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1512 case ARM::BI__builtin_arm_dmb: 1513 case ARM::BI__builtin_arm_dsb: 1514 case ARM::BI__builtin_arm_isb: 1515 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1516 } 1517 1518 // FIXME: VFP Intrinsics should error if VFP not present. 1519 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1520 } 1521 1522 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1523 CallExpr *TheCall) { 1524 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1525 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1526 BuiltinID == AArch64::BI__builtin_arm_strex || 1527 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1528 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1529 } 1530 1531 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1532 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1533 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1534 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1535 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1536 } 1537 1538 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1539 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1540 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1541 1542 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1543 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1544 BuiltinID == AArch64::BI__builtin_arm_wsr || 1545 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1546 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1547 1548 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1549 return true; 1550 1551 // For intrinsics which take an immediate value as part of the instruction, 1552 // range check them here. 1553 unsigned i = 0, l = 0, u = 0; 1554 switch (BuiltinID) { 1555 default: return false; 1556 case AArch64::BI__builtin_arm_dmb: 1557 case AArch64::BI__builtin_arm_dsb: 1558 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1559 } 1560 1561 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1562 } 1563 1564 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1565 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1566 // ordering for DSP is unspecified. MSA is ordered by the data format used 1567 // by the underlying instruction i.e., df/m, df/n and then by size. 1568 // 1569 // FIXME: The size tests here should instead be tablegen'd along with the 1570 // definitions from include/clang/Basic/BuiltinsMips.def. 1571 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1572 // be too. 1573 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1574 unsigned i = 0, l = 0, u = 0, m = 0; 1575 switch (BuiltinID) { 1576 default: return false; 1577 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1578 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1579 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1580 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1581 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1582 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1583 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1584 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1585 // df/m field. 1586 // These intrinsics take an unsigned 3 bit immediate. 1587 case Mips::BI__builtin_msa_bclri_b: 1588 case Mips::BI__builtin_msa_bnegi_b: 1589 case Mips::BI__builtin_msa_bseti_b: 1590 case Mips::BI__builtin_msa_sat_s_b: 1591 case Mips::BI__builtin_msa_sat_u_b: 1592 case Mips::BI__builtin_msa_slli_b: 1593 case Mips::BI__builtin_msa_srai_b: 1594 case Mips::BI__builtin_msa_srari_b: 1595 case Mips::BI__builtin_msa_srli_b: 1596 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1597 case Mips::BI__builtin_msa_binsli_b: 1598 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1599 // These intrinsics take an unsigned 4 bit immediate. 1600 case Mips::BI__builtin_msa_bclri_h: 1601 case Mips::BI__builtin_msa_bnegi_h: 1602 case Mips::BI__builtin_msa_bseti_h: 1603 case Mips::BI__builtin_msa_sat_s_h: 1604 case Mips::BI__builtin_msa_sat_u_h: 1605 case Mips::BI__builtin_msa_slli_h: 1606 case Mips::BI__builtin_msa_srai_h: 1607 case Mips::BI__builtin_msa_srari_h: 1608 case Mips::BI__builtin_msa_srli_h: 1609 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1610 case Mips::BI__builtin_msa_binsli_h: 1611 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1612 // These intrinsics take an unsigned 5 bit immedate. 1613 // The first block of intrinsics actually have an unsigned 5 bit field, 1614 // not a df/n field. 1615 case Mips::BI__builtin_msa_clei_u_b: 1616 case Mips::BI__builtin_msa_clei_u_h: 1617 case Mips::BI__builtin_msa_clei_u_w: 1618 case Mips::BI__builtin_msa_clei_u_d: 1619 case Mips::BI__builtin_msa_clti_u_b: 1620 case Mips::BI__builtin_msa_clti_u_h: 1621 case Mips::BI__builtin_msa_clti_u_w: 1622 case Mips::BI__builtin_msa_clti_u_d: 1623 case Mips::BI__builtin_msa_maxi_u_b: 1624 case Mips::BI__builtin_msa_maxi_u_h: 1625 case Mips::BI__builtin_msa_maxi_u_w: 1626 case Mips::BI__builtin_msa_maxi_u_d: 1627 case Mips::BI__builtin_msa_mini_u_b: 1628 case Mips::BI__builtin_msa_mini_u_h: 1629 case Mips::BI__builtin_msa_mini_u_w: 1630 case Mips::BI__builtin_msa_mini_u_d: 1631 case Mips::BI__builtin_msa_addvi_b: 1632 case Mips::BI__builtin_msa_addvi_h: 1633 case Mips::BI__builtin_msa_addvi_w: 1634 case Mips::BI__builtin_msa_addvi_d: 1635 case Mips::BI__builtin_msa_bclri_w: 1636 case Mips::BI__builtin_msa_bnegi_w: 1637 case Mips::BI__builtin_msa_bseti_w: 1638 case Mips::BI__builtin_msa_sat_s_w: 1639 case Mips::BI__builtin_msa_sat_u_w: 1640 case Mips::BI__builtin_msa_slli_w: 1641 case Mips::BI__builtin_msa_srai_w: 1642 case Mips::BI__builtin_msa_srari_w: 1643 case Mips::BI__builtin_msa_srli_w: 1644 case Mips::BI__builtin_msa_srlri_w: 1645 case Mips::BI__builtin_msa_subvi_b: 1646 case Mips::BI__builtin_msa_subvi_h: 1647 case Mips::BI__builtin_msa_subvi_w: 1648 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1649 case Mips::BI__builtin_msa_binsli_w: 1650 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1651 // These intrinsics take an unsigned 6 bit immediate. 1652 case Mips::BI__builtin_msa_bclri_d: 1653 case Mips::BI__builtin_msa_bnegi_d: 1654 case Mips::BI__builtin_msa_bseti_d: 1655 case Mips::BI__builtin_msa_sat_s_d: 1656 case Mips::BI__builtin_msa_sat_u_d: 1657 case Mips::BI__builtin_msa_slli_d: 1658 case Mips::BI__builtin_msa_srai_d: 1659 case Mips::BI__builtin_msa_srari_d: 1660 case Mips::BI__builtin_msa_srli_d: 1661 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1662 case Mips::BI__builtin_msa_binsli_d: 1663 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1664 // These intrinsics take a signed 5 bit immediate. 1665 case Mips::BI__builtin_msa_ceqi_b: 1666 case Mips::BI__builtin_msa_ceqi_h: 1667 case Mips::BI__builtin_msa_ceqi_w: 1668 case Mips::BI__builtin_msa_ceqi_d: 1669 case Mips::BI__builtin_msa_clti_s_b: 1670 case Mips::BI__builtin_msa_clti_s_h: 1671 case Mips::BI__builtin_msa_clti_s_w: 1672 case Mips::BI__builtin_msa_clti_s_d: 1673 case Mips::BI__builtin_msa_clei_s_b: 1674 case Mips::BI__builtin_msa_clei_s_h: 1675 case Mips::BI__builtin_msa_clei_s_w: 1676 case Mips::BI__builtin_msa_clei_s_d: 1677 case Mips::BI__builtin_msa_maxi_s_b: 1678 case Mips::BI__builtin_msa_maxi_s_h: 1679 case Mips::BI__builtin_msa_maxi_s_w: 1680 case Mips::BI__builtin_msa_maxi_s_d: 1681 case Mips::BI__builtin_msa_mini_s_b: 1682 case Mips::BI__builtin_msa_mini_s_h: 1683 case Mips::BI__builtin_msa_mini_s_w: 1684 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1685 // These intrinsics take an unsigned 8 bit immediate. 1686 case Mips::BI__builtin_msa_andi_b: 1687 case Mips::BI__builtin_msa_nori_b: 1688 case Mips::BI__builtin_msa_ori_b: 1689 case Mips::BI__builtin_msa_shf_b: 1690 case Mips::BI__builtin_msa_shf_h: 1691 case Mips::BI__builtin_msa_shf_w: 1692 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1693 case Mips::BI__builtin_msa_bseli_b: 1694 case Mips::BI__builtin_msa_bmnzi_b: 1695 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1696 // df/n format 1697 // These intrinsics take an unsigned 4 bit immediate. 1698 case Mips::BI__builtin_msa_copy_s_b: 1699 case Mips::BI__builtin_msa_copy_u_b: 1700 case Mips::BI__builtin_msa_insve_b: 1701 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1702 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1703 // These intrinsics take an unsigned 3 bit immediate. 1704 case Mips::BI__builtin_msa_copy_s_h: 1705 case Mips::BI__builtin_msa_copy_u_h: 1706 case Mips::BI__builtin_msa_insve_h: 1707 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1708 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1709 // These intrinsics take an unsigned 2 bit immediate. 1710 case Mips::BI__builtin_msa_copy_s_w: 1711 case Mips::BI__builtin_msa_copy_u_w: 1712 case Mips::BI__builtin_msa_insve_w: 1713 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1714 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1715 // These intrinsics take an unsigned 1 bit immediate. 1716 case Mips::BI__builtin_msa_copy_s_d: 1717 case Mips::BI__builtin_msa_copy_u_d: 1718 case Mips::BI__builtin_msa_insve_d: 1719 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1720 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1721 // Memory offsets and immediate loads. 1722 // These intrinsics take a signed 10 bit immediate. 1723 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 1724 case Mips::BI__builtin_msa_ldi_h: 1725 case Mips::BI__builtin_msa_ldi_w: 1726 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1727 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1728 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1729 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1730 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1731 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1732 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1733 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1734 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1735 } 1736 1737 if (!m) 1738 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1739 1740 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1741 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1742 } 1743 1744 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1745 unsigned i = 0, l = 0, u = 0; 1746 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1747 BuiltinID == PPC::BI__builtin_divdeu || 1748 BuiltinID == PPC::BI__builtin_bpermd; 1749 bool IsTarget64Bit = Context.getTargetInfo() 1750 .getTypeWidth(Context 1751 .getTargetInfo() 1752 .getIntPtrType()) == 64; 1753 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1754 BuiltinID == PPC::BI__builtin_divweu || 1755 BuiltinID == PPC::BI__builtin_divde || 1756 BuiltinID == PPC::BI__builtin_divdeu; 1757 1758 if (Is64BitBltin && !IsTarget64Bit) 1759 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1760 << TheCall->getSourceRange(); 1761 1762 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1763 (BuiltinID == PPC::BI__builtin_bpermd && 1764 !Context.getTargetInfo().hasFeature("bpermd"))) 1765 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1766 << TheCall->getSourceRange(); 1767 1768 switch (BuiltinID) { 1769 default: return false; 1770 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1771 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1772 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1773 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1774 case PPC::BI__builtin_tbegin: 1775 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1776 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1777 case PPC::BI__builtin_tabortwc: 1778 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1779 case PPC::BI__builtin_tabortwci: 1780 case PPC::BI__builtin_tabortdci: 1781 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1782 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1783 case PPC::BI__builtin_vsx_xxpermdi: 1784 case PPC::BI__builtin_vsx_xxsldwi: 1785 return SemaBuiltinVSX(TheCall); 1786 } 1787 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1788 } 1789 1790 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1791 CallExpr *TheCall) { 1792 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1793 Expr *Arg = TheCall->getArg(0); 1794 llvm::APSInt AbortCode(32); 1795 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1796 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1797 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1798 << Arg->getSourceRange(); 1799 } 1800 1801 // For intrinsics which take an immediate value as part of the instruction, 1802 // range check them here. 1803 unsigned i = 0, l = 0, u = 0; 1804 switch (BuiltinID) { 1805 default: return false; 1806 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1807 case SystemZ::BI__builtin_s390_verimb: 1808 case SystemZ::BI__builtin_s390_verimh: 1809 case SystemZ::BI__builtin_s390_verimf: 1810 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1811 case SystemZ::BI__builtin_s390_vfaeb: 1812 case SystemZ::BI__builtin_s390_vfaeh: 1813 case SystemZ::BI__builtin_s390_vfaef: 1814 case SystemZ::BI__builtin_s390_vfaebs: 1815 case SystemZ::BI__builtin_s390_vfaehs: 1816 case SystemZ::BI__builtin_s390_vfaefs: 1817 case SystemZ::BI__builtin_s390_vfaezb: 1818 case SystemZ::BI__builtin_s390_vfaezh: 1819 case SystemZ::BI__builtin_s390_vfaezf: 1820 case SystemZ::BI__builtin_s390_vfaezbs: 1821 case SystemZ::BI__builtin_s390_vfaezhs: 1822 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1823 case SystemZ::BI__builtin_s390_vfisb: 1824 case SystemZ::BI__builtin_s390_vfidb: 1825 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1826 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1827 case SystemZ::BI__builtin_s390_vftcisb: 1828 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1829 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1830 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1831 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1832 case SystemZ::BI__builtin_s390_vstrcb: 1833 case SystemZ::BI__builtin_s390_vstrch: 1834 case SystemZ::BI__builtin_s390_vstrcf: 1835 case SystemZ::BI__builtin_s390_vstrczb: 1836 case SystemZ::BI__builtin_s390_vstrczh: 1837 case SystemZ::BI__builtin_s390_vstrczf: 1838 case SystemZ::BI__builtin_s390_vstrcbs: 1839 case SystemZ::BI__builtin_s390_vstrchs: 1840 case SystemZ::BI__builtin_s390_vstrcfs: 1841 case SystemZ::BI__builtin_s390_vstrczbs: 1842 case SystemZ::BI__builtin_s390_vstrczhs: 1843 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1844 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 1845 case SystemZ::BI__builtin_s390_vfminsb: 1846 case SystemZ::BI__builtin_s390_vfmaxsb: 1847 case SystemZ::BI__builtin_s390_vfmindb: 1848 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 1849 } 1850 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1851 } 1852 1853 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1854 /// This checks that the target supports __builtin_cpu_supports and 1855 /// that the string argument is constant and valid. 1856 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1857 Expr *Arg = TheCall->getArg(0); 1858 1859 // Check if the argument is a string literal. 1860 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1861 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1862 << Arg->getSourceRange(); 1863 1864 // Check the contents of the string. 1865 StringRef Feature = 1866 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1867 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1868 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1869 << Arg->getSourceRange(); 1870 return false; 1871 } 1872 1873 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 1874 /// This checks that the target supports __builtin_cpu_is and 1875 /// that the string argument is constant and valid. 1876 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 1877 Expr *Arg = TheCall->getArg(0); 1878 1879 // Check if the argument is a string literal. 1880 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1881 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1882 << Arg->getSourceRange(); 1883 1884 // Check the contents of the string. 1885 StringRef Feature = 1886 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1887 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 1888 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is) 1889 << Arg->getSourceRange(); 1890 return false; 1891 } 1892 1893 // Check if the rounding mode is legal. 1894 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1895 // Indicates if this instruction has rounding control or just SAE. 1896 bool HasRC = false; 1897 1898 unsigned ArgNum = 0; 1899 switch (BuiltinID) { 1900 default: 1901 return false; 1902 case X86::BI__builtin_ia32_vcvttsd2si32: 1903 case X86::BI__builtin_ia32_vcvttsd2si64: 1904 case X86::BI__builtin_ia32_vcvttsd2usi32: 1905 case X86::BI__builtin_ia32_vcvttsd2usi64: 1906 case X86::BI__builtin_ia32_vcvttss2si32: 1907 case X86::BI__builtin_ia32_vcvttss2si64: 1908 case X86::BI__builtin_ia32_vcvttss2usi32: 1909 case X86::BI__builtin_ia32_vcvttss2usi64: 1910 ArgNum = 1; 1911 break; 1912 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1913 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1914 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1915 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1916 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1917 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1918 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1919 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1920 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1921 case X86::BI__builtin_ia32_exp2pd_mask: 1922 case X86::BI__builtin_ia32_exp2ps_mask: 1923 case X86::BI__builtin_ia32_getexppd512_mask: 1924 case X86::BI__builtin_ia32_getexpps512_mask: 1925 case X86::BI__builtin_ia32_rcp28pd_mask: 1926 case X86::BI__builtin_ia32_rcp28ps_mask: 1927 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1928 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1929 case X86::BI__builtin_ia32_vcomisd: 1930 case X86::BI__builtin_ia32_vcomiss: 1931 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1932 ArgNum = 3; 1933 break; 1934 case X86::BI__builtin_ia32_cmppd512_mask: 1935 case X86::BI__builtin_ia32_cmpps512_mask: 1936 case X86::BI__builtin_ia32_cmpsd_mask: 1937 case X86::BI__builtin_ia32_cmpss_mask: 1938 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1939 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1940 case X86::BI__builtin_ia32_getexpss128_round_mask: 1941 case X86::BI__builtin_ia32_maxpd512_mask: 1942 case X86::BI__builtin_ia32_maxps512_mask: 1943 case X86::BI__builtin_ia32_maxsd_round_mask: 1944 case X86::BI__builtin_ia32_maxss_round_mask: 1945 case X86::BI__builtin_ia32_minpd512_mask: 1946 case X86::BI__builtin_ia32_minps512_mask: 1947 case X86::BI__builtin_ia32_minsd_round_mask: 1948 case X86::BI__builtin_ia32_minss_round_mask: 1949 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1950 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1951 case X86::BI__builtin_ia32_reducepd512_mask: 1952 case X86::BI__builtin_ia32_reduceps512_mask: 1953 case X86::BI__builtin_ia32_rndscalepd_mask: 1954 case X86::BI__builtin_ia32_rndscaleps_mask: 1955 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1956 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1957 ArgNum = 4; 1958 break; 1959 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1960 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1961 case X86::BI__builtin_ia32_fixupimmps512_mask: 1962 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1963 case X86::BI__builtin_ia32_fixupimmsd_mask: 1964 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1965 case X86::BI__builtin_ia32_fixupimmss_mask: 1966 case X86::BI__builtin_ia32_fixupimmss_maskz: 1967 case X86::BI__builtin_ia32_rangepd512_mask: 1968 case X86::BI__builtin_ia32_rangeps512_mask: 1969 case X86::BI__builtin_ia32_rangesd128_round_mask: 1970 case X86::BI__builtin_ia32_rangess128_round_mask: 1971 case X86::BI__builtin_ia32_reducesd_mask: 1972 case X86::BI__builtin_ia32_reducess_mask: 1973 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1974 case X86::BI__builtin_ia32_rndscaless_round_mask: 1975 ArgNum = 5; 1976 break; 1977 case X86::BI__builtin_ia32_vcvtsd2si64: 1978 case X86::BI__builtin_ia32_vcvtsd2si32: 1979 case X86::BI__builtin_ia32_vcvtsd2usi32: 1980 case X86::BI__builtin_ia32_vcvtsd2usi64: 1981 case X86::BI__builtin_ia32_vcvtss2si32: 1982 case X86::BI__builtin_ia32_vcvtss2si64: 1983 case X86::BI__builtin_ia32_vcvtss2usi32: 1984 case X86::BI__builtin_ia32_vcvtss2usi64: 1985 ArgNum = 1; 1986 HasRC = true; 1987 break; 1988 case X86::BI__builtin_ia32_cvtsi2sd64: 1989 case X86::BI__builtin_ia32_cvtsi2ss32: 1990 case X86::BI__builtin_ia32_cvtsi2ss64: 1991 case X86::BI__builtin_ia32_cvtusi2sd64: 1992 case X86::BI__builtin_ia32_cvtusi2ss32: 1993 case X86::BI__builtin_ia32_cvtusi2ss64: 1994 ArgNum = 2; 1995 HasRC = true; 1996 break; 1997 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1998 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1999 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 2000 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 2001 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 2002 case X86::BI__builtin_ia32_cvtps2qq512_mask: 2003 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 2004 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 2005 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 2006 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 2007 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 2008 case X86::BI__builtin_ia32_sqrtpd512_mask: 2009 case X86::BI__builtin_ia32_sqrtps512_mask: 2010 ArgNum = 3; 2011 HasRC = true; 2012 break; 2013 case X86::BI__builtin_ia32_addpd512_mask: 2014 case X86::BI__builtin_ia32_addps512_mask: 2015 case X86::BI__builtin_ia32_divpd512_mask: 2016 case X86::BI__builtin_ia32_divps512_mask: 2017 case X86::BI__builtin_ia32_mulpd512_mask: 2018 case X86::BI__builtin_ia32_mulps512_mask: 2019 case X86::BI__builtin_ia32_subpd512_mask: 2020 case X86::BI__builtin_ia32_subps512_mask: 2021 case X86::BI__builtin_ia32_addss_round_mask: 2022 case X86::BI__builtin_ia32_addsd_round_mask: 2023 case X86::BI__builtin_ia32_divss_round_mask: 2024 case X86::BI__builtin_ia32_divsd_round_mask: 2025 case X86::BI__builtin_ia32_mulss_round_mask: 2026 case X86::BI__builtin_ia32_mulsd_round_mask: 2027 case X86::BI__builtin_ia32_subss_round_mask: 2028 case X86::BI__builtin_ia32_subsd_round_mask: 2029 case X86::BI__builtin_ia32_scalefpd512_mask: 2030 case X86::BI__builtin_ia32_scalefps512_mask: 2031 case X86::BI__builtin_ia32_scalefsd_round_mask: 2032 case X86::BI__builtin_ia32_scalefss_round_mask: 2033 case X86::BI__builtin_ia32_getmantpd512_mask: 2034 case X86::BI__builtin_ia32_getmantps512_mask: 2035 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 2036 case X86::BI__builtin_ia32_sqrtsd_round_mask: 2037 case X86::BI__builtin_ia32_sqrtss_round_mask: 2038 case X86::BI__builtin_ia32_vfmaddpd512_mask: 2039 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 2040 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 2041 case X86::BI__builtin_ia32_vfmaddps512_mask: 2042 case X86::BI__builtin_ia32_vfmaddps512_mask3: 2043 case X86::BI__builtin_ia32_vfmaddps512_maskz: 2044 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 2045 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 2046 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 2047 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 2048 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2049 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2050 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2051 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2052 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2053 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2054 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 2055 case X86::BI__builtin_ia32_vfnmaddps512_mask: 2056 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 2057 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 2058 case X86::BI__builtin_ia32_vfnmsubps512_mask: 2059 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 2060 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2061 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2062 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2063 case X86::BI__builtin_ia32_vfmaddss3_mask: 2064 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2065 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2066 ArgNum = 4; 2067 HasRC = true; 2068 break; 2069 case X86::BI__builtin_ia32_getmantsd_round_mask: 2070 case X86::BI__builtin_ia32_getmantss_round_mask: 2071 ArgNum = 5; 2072 HasRC = true; 2073 break; 2074 } 2075 2076 llvm::APSInt Result; 2077 2078 // We can't check the value of a dependent argument. 2079 Expr *Arg = TheCall->getArg(ArgNum); 2080 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2081 return false; 2082 2083 // Check constant-ness first. 2084 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2085 return true; 2086 2087 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2088 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2089 // combined with ROUND_NO_EXC. 2090 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2091 Result == 8/*ROUND_NO_EXC*/ || 2092 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2093 return false; 2094 2095 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2096 << Arg->getSourceRange(); 2097 } 2098 2099 // Check if the gather/scatter scale is legal. 2100 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2101 CallExpr *TheCall) { 2102 unsigned ArgNum = 0; 2103 switch (BuiltinID) { 2104 default: 2105 return false; 2106 case X86::BI__builtin_ia32_gatherpfdpd: 2107 case X86::BI__builtin_ia32_gatherpfdps: 2108 case X86::BI__builtin_ia32_gatherpfqpd: 2109 case X86::BI__builtin_ia32_gatherpfqps: 2110 case X86::BI__builtin_ia32_scatterpfdpd: 2111 case X86::BI__builtin_ia32_scatterpfdps: 2112 case X86::BI__builtin_ia32_scatterpfqpd: 2113 case X86::BI__builtin_ia32_scatterpfqps: 2114 ArgNum = 3; 2115 break; 2116 case X86::BI__builtin_ia32_gatherd_pd: 2117 case X86::BI__builtin_ia32_gatherd_pd256: 2118 case X86::BI__builtin_ia32_gatherq_pd: 2119 case X86::BI__builtin_ia32_gatherq_pd256: 2120 case X86::BI__builtin_ia32_gatherd_ps: 2121 case X86::BI__builtin_ia32_gatherd_ps256: 2122 case X86::BI__builtin_ia32_gatherq_ps: 2123 case X86::BI__builtin_ia32_gatherq_ps256: 2124 case X86::BI__builtin_ia32_gatherd_q: 2125 case X86::BI__builtin_ia32_gatherd_q256: 2126 case X86::BI__builtin_ia32_gatherq_q: 2127 case X86::BI__builtin_ia32_gatherq_q256: 2128 case X86::BI__builtin_ia32_gatherd_d: 2129 case X86::BI__builtin_ia32_gatherd_d256: 2130 case X86::BI__builtin_ia32_gatherq_d: 2131 case X86::BI__builtin_ia32_gatherq_d256: 2132 case X86::BI__builtin_ia32_gather3div2df: 2133 case X86::BI__builtin_ia32_gather3div2di: 2134 case X86::BI__builtin_ia32_gather3div4df: 2135 case X86::BI__builtin_ia32_gather3div4di: 2136 case X86::BI__builtin_ia32_gather3div4sf: 2137 case X86::BI__builtin_ia32_gather3div4si: 2138 case X86::BI__builtin_ia32_gather3div8sf: 2139 case X86::BI__builtin_ia32_gather3div8si: 2140 case X86::BI__builtin_ia32_gather3siv2df: 2141 case X86::BI__builtin_ia32_gather3siv2di: 2142 case X86::BI__builtin_ia32_gather3siv4df: 2143 case X86::BI__builtin_ia32_gather3siv4di: 2144 case X86::BI__builtin_ia32_gather3siv4sf: 2145 case X86::BI__builtin_ia32_gather3siv4si: 2146 case X86::BI__builtin_ia32_gather3siv8sf: 2147 case X86::BI__builtin_ia32_gather3siv8si: 2148 case X86::BI__builtin_ia32_gathersiv8df: 2149 case X86::BI__builtin_ia32_gathersiv16sf: 2150 case X86::BI__builtin_ia32_gatherdiv8df: 2151 case X86::BI__builtin_ia32_gatherdiv16sf: 2152 case X86::BI__builtin_ia32_gathersiv8di: 2153 case X86::BI__builtin_ia32_gathersiv16si: 2154 case X86::BI__builtin_ia32_gatherdiv8di: 2155 case X86::BI__builtin_ia32_gatherdiv16si: 2156 case X86::BI__builtin_ia32_scatterdiv2df: 2157 case X86::BI__builtin_ia32_scatterdiv2di: 2158 case X86::BI__builtin_ia32_scatterdiv4df: 2159 case X86::BI__builtin_ia32_scatterdiv4di: 2160 case X86::BI__builtin_ia32_scatterdiv4sf: 2161 case X86::BI__builtin_ia32_scatterdiv4si: 2162 case X86::BI__builtin_ia32_scatterdiv8sf: 2163 case X86::BI__builtin_ia32_scatterdiv8si: 2164 case X86::BI__builtin_ia32_scattersiv2df: 2165 case X86::BI__builtin_ia32_scattersiv2di: 2166 case X86::BI__builtin_ia32_scattersiv4df: 2167 case X86::BI__builtin_ia32_scattersiv4di: 2168 case X86::BI__builtin_ia32_scattersiv4sf: 2169 case X86::BI__builtin_ia32_scattersiv4si: 2170 case X86::BI__builtin_ia32_scattersiv8sf: 2171 case X86::BI__builtin_ia32_scattersiv8si: 2172 case X86::BI__builtin_ia32_scattersiv8df: 2173 case X86::BI__builtin_ia32_scattersiv16sf: 2174 case X86::BI__builtin_ia32_scatterdiv8df: 2175 case X86::BI__builtin_ia32_scatterdiv16sf: 2176 case X86::BI__builtin_ia32_scattersiv8di: 2177 case X86::BI__builtin_ia32_scattersiv16si: 2178 case X86::BI__builtin_ia32_scatterdiv8di: 2179 case X86::BI__builtin_ia32_scatterdiv16si: 2180 ArgNum = 4; 2181 break; 2182 } 2183 2184 llvm::APSInt Result; 2185 2186 // We can't check the value of a dependent argument. 2187 Expr *Arg = TheCall->getArg(ArgNum); 2188 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2189 return false; 2190 2191 // Check constant-ness first. 2192 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2193 return true; 2194 2195 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2196 return false; 2197 2198 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2199 << Arg->getSourceRange(); 2200 } 2201 2202 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2203 if (BuiltinID == X86::BI__builtin_cpu_supports) 2204 return SemaBuiltinCpuSupports(*this, TheCall); 2205 2206 if (BuiltinID == X86::BI__builtin_cpu_is) 2207 return SemaBuiltinCpuIs(*this, TheCall); 2208 2209 // If the intrinsic has rounding or SAE make sure its valid. 2210 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2211 return true; 2212 2213 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2214 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2215 return true; 2216 2217 // For intrinsics which take an immediate value as part of the instruction, 2218 // range check them here. 2219 int i = 0, l = 0, u = 0; 2220 switch (BuiltinID) { 2221 default: 2222 return false; 2223 case X86::BI_mm_prefetch: 2224 i = 1; l = 0; u = 3; 2225 break; 2226 case X86::BI__builtin_ia32_sha1rnds4: 2227 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2228 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2229 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2230 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2231 i = 2; l = 0; u = 3; 2232 break; 2233 case X86::BI__builtin_ia32_vpermil2pd: 2234 case X86::BI__builtin_ia32_vpermil2pd256: 2235 case X86::BI__builtin_ia32_vpermil2ps: 2236 case X86::BI__builtin_ia32_vpermil2ps256: 2237 i = 3; l = 0; u = 3; 2238 break; 2239 case X86::BI__builtin_ia32_cmpb128_mask: 2240 case X86::BI__builtin_ia32_cmpw128_mask: 2241 case X86::BI__builtin_ia32_cmpd128_mask: 2242 case X86::BI__builtin_ia32_cmpq128_mask: 2243 case X86::BI__builtin_ia32_cmpb256_mask: 2244 case X86::BI__builtin_ia32_cmpw256_mask: 2245 case X86::BI__builtin_ia32_cmpd256_mask: 2246 case X86::BI__builtin_ia32_cmpq256_mask: 2247 case X86::BI__builtin_ia32_cmpb512_mask: 2248 case X86::BI__builtin_ia32_cmpw512_mask: 2249 case X86::BI__builtin_ia32_cmpd512_mask: 2250 case X86::BI__builtin_ia32_cmpq512_mask: 2251 case X86::BI__builtin_ia32_ucmpb128_mask: 2252 case X86::BI__builtin_ia32_ucmpw128_mask: 2253 case X86::BI__builtin_ia32_ucmpd128_mask: 2254 case X86::BI__builtin_ia32_ucmpq128_mask: 2255 case X86::BI__builtin_ia32_ucmpb256_mask: 2256 case X86::BI__builtin_ia32_ucmpw256_mask: 2257 case X86::BI__builtin_ia32_ucmpd256_mask: 2258 case X86::BI__builtin_ia32_ucmpq256_mask: 2259 case X86::BI__builtin_ia32_ucmpb512_mask: 2260 case X86::BI__builtin_ia32_ucmpw512_mask: 2261 case X86::BI__builtin_ia32_ucmpd512_mask: 2262 case X86::BI__builtin_ia32_ucmpq512_mask: 2263 case X86::BI__builtin_ia32_vpcomub: 2264 case X86::BI__builtin_ia32_vpcomuw: 2265 case X86::BI__builtin_ia32_vpcomud: 2266 case X86::BI__builtin_ia32_vpcomuq: 2267 case X86::BI__builtin_ia32_vpcomb: 2268 case X86::BI__builtin_ia32_vpcomw: 2269 case X86::BI__builtin_ia32_vpcomd: 2270 case X86::BI__builtin_ia32_vpcomq: 2271 i = 2; l = 0; u = 7; 2272 break; 2273 case X86::BI__builtin_ia32_roundps: 2274 case X86::BI__builtin_ia32_roundpd: 2275 case X86::BI__builtin_ia32_roundps256: 2276 case X86::BI__builtin_ia32_roundpd256: 2277 i = 1; l = 0; u = 15; 2278 break; 2279 case X86::BI__builtin_ia32_roundss: 2280 case X86::BI__builtin_ia32_roundsd: 2281 case X86::BI__builtin_ia32_rangepd128_mask: 2282 case X86::BI__builtin_ia32_rangepd256_mask: 2283 case X86::BI__builtin_ia32_rangepd512_mask: 2284 case X86::BI__builtin_ia32_rangeps128_mask: 2285 case X86::BI__builtin_ia32_rangeps256_mask: 2286 case X86::BI__builtin_ia32_rangeps512_mask: 2287 case X86::BI__builtin_ia32_getmantsd_round_mask: 2288 case X86::BI__builtin_ia32_getmantss_round_mask: 2289 i = 2; l = 0; u = 15; 2290 break; 2291 case X86::BI__builtin_ia32_cmpps: 2292 case X86::BI__builtin_ia32_cmpss: 2293 case X86::BI__builtin_ia32_cmppd: 2294 case X86::BI__builtin_ia32_cmpsd: 2295 case X86::BI__builtin_ia32_cmpps256: 2296 case X86::BI__builtin_ia32_cmppd256: 2297 case X86::BI__builtin_ia32_cmpps128_mask: 2298 case X86::BI__builtin_ia32_cmppd128_mask: 2299 case X86::BI__builtin_ia32_cmpps256_mask: 2300 case X86::BI__builtin_ia32_cmppd256_mask: 2301 case X86::BI__builtin_ia32_cmpps512_mask: 2302 case X86::BI__builtin_ia32_cmppd512_mask: 2303 case X86::BI__builtin_ia32_cmpsd_mask: 2304 case X86::BI__builtin_ia32_cmpss_mask: 2305 i = 2; l = 0; u = 31; 2306 break; 2307 case X86::BI__builtin_ia32_xabort: 2308 i = 0; l = -128; u = 255; 2309 break; 2310 case X86::BI__builtin_ia32_pshufw: 2311 case X86::BI__builtin_ia32_aeskeygenassist128: 2312 i = 1; l = -128; u = 255; 2313 break; 2314 case X86::BI__builtin_ia32_vcvtps2ph: 2315 case X86::BI__builtin_ia32_vcvtps2ph256: 2316 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2317 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2318 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2319 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2320 case X86::BI__builtin_ia32_rndscaleps_mask: 2321 case X86::BI__builtin_ia32_rndscalepd_mask: 2322 case X86::BI__builtin_ia32_reducepd128_mask: 2323 case X86::BI__builtin_ia32_reducepd256_mask: 2324 case X86::BI__builtin_ia32_reducepd512_mask: 2325 case X86::BI__builtin_ia32_reduceps128_mask: 2326 case X86::BI__builtin_ia32_reduceps256_mask: 2327 case X86::BI__builtin_ia32_reduceps512_mask: 2328 case X86::BI__builtin_ia32_prold512_mask: 2329 case X86::BI__builtin_ia32_prolq512_mask: 2330 case X86::BI__builtin_ia32_prold128_mask: 2331 case X86::BI__builtin_ia32_prold256_mask: 2332 case X86::BI__builtin_ia32_prolq128_mask: 2333 case X86::BI__builtin_ia32_prolq256_mask: 2334 case X86::BI__builtin_ia32_prord128_mask: 2335 case X86::BI__builtin_ia32_prord256_mask: 2336 case X86::BI__builtin_ia32_prorq128_mask: 2337 case X86::BI__builtin_ia32_prorq256_mask: 2338 case X86::BI__builtin_ia32_fpclasspd128_mask: 2339 case X86::BI__builtin_ia32_fpclasspd256_mask: 2340 case X86::BI__builtin_ia32_fpclassps128_mask: 2341 case X86::BI__builtin_ia32_fpclassps256_mask: 2342 case X86::BI__builtin_ia32_fpclassps512_mask: 2343 case X86::BI__builtin_ia32_fpclasspd512_mask: 2344 case X86::BI__builtin_ia32_fpclasssd_mask: 2345 case X86::BI__builtin_ia32_fpclassss_mask: 2346 i = 1; l = 0; u = 255; 2347 break; 2348 case X86::BI__builtin_ia32_palignr: 2349 case X86::BI__builtin_ia32_insertps128: 2350 case X86::BI__builtin_ia32_dpps: 2351 case X86::BI__builtin_ia32_dppd: 2352 case X86::BI__builtin_ia32_dpps256: 2353 case X86::BI__builtin_ia32_mpsadbw128: 2354 case X86::BI__builtin_ia32_mpsadbw256: 2355 case X86::BI__builtin_ia32_pcmpistrm128: 2356 case X86::BI__builtin_ia32_pcmpistri128: 2357 case X86::BI__builtin_ia32_pcmpistria128: 2358 case X86::BI__builtin_ia32_pcmpistric128: 2359 case X86::BI__builtin_ia32_pcmpistrio128: 2360 case X86::BI__builtin_ia32_pcmpistris128: 2361 case X86::BI__builtin_ia32_pcmpistriz128: 2362 case X86::BI__builtin_ia32_pclmulqdq128: 2363 case X86::BI__builtin_ia32_vperm2f128_pd256: 2364 case X86::BI__builtin_ia32_vperm2f128_ps256: 2365 case X86::BI__builtin_ia32_vperm2f128_si256: 2366 case X86::BI__builtin_ia32_permti256: 2367 i = 2; l = -128; u = 255; 2368 break; 2369 case X86::BI__builtin_ia32_palignr128: 2370 case X86::BI__builtin_ia32_palignr256: 2371 case X86::BI__builtin_ia32_palignr512_mask: 2372 case X86::BI__builtin_ia32_vcomisd: 2373 case X86::BI__builtin_ia32_vcomiss: 2374 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2375 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2376 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2377 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2378 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2379 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2380 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2381 i = 2; l = 0; u = 255; 2382 break; 2383 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2384 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2385 case X86::BI__builtin_ia32_fixupimmps512_mask: 2386 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2387 case X86::BI__builtin_ia32_fixupimmsd_mask: 2388 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2389 case X86::BI__builtin_ia32_fixupimmss_mask: 2390 case X86::BI__builtin_ia32_fixupimmss_maskz: 2391 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2392 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2393 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2394 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2395 case X86::BI__builtin_ia32_fixupimmps128_mask: 2396 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2397 case X86::BI__builtin_ia32_fixupimmps256_mask: 2398 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2399 case X86::BI__builtin_ia32_pternlogd512_mask: 2400 case X86::BI__builtin_ia32_pternlogd512_maskz: 2401 case X86::BI__builtin_ia32_pternlogq512_mask: 2402 case X86::BI__builtin_ia32_pternlogq512_maskz: 2403 case X86::BI__builtin_ia32_pternlogd128_mask: 2404 case X86::BI__builtin_ia32_pternlogd128_maskz: 2405 case X86::BI__builtin_ia32_pternlogd256_mask: 2406 case X86::BI__builtin_ia32_pternlogd256_maskz: 2407 case X86::BI__builtin_ia32_pternlogq128_mask: 2408 case X86::BI__builtin_ia32_pternlogq128_maskz: 2409 case X86::BI__builtin_ia32_pternlogq256_mask: 2410 case X86::BI__builtin_ia32_pternlogq256_maskz: 2411 i = 3; l = 0; u = 255; 2412 break; 2413 case X86::BI__builtin_ia32_gatherpfdpd: 2414 case X86::BI__builtin_ia32_gatherpfdps: 2415 case X86::BI__builtin_ia32_gatherpfqpd: 2416 case X86::BI__builtin_ia32_gatherpfqps: 2417 case X86::BI__builtin_ia32_scatterpfdpd: 2418 case X86::BI__builtin_ia32_scatterpfdps: 2419 case X86::BI__builtin_ia32_scatterpfqpd: 2420 case X86::BI__builtin_ia32_scatterpfqps: 2421 i = 4; l = 2; u = 3; 2422 break; 2423 case X86::BI__builtin_ia32_pcmpestrm128: 2424 case X86::BI__builtin_ia32_pcmpestri128: 2425 case X86::BI__builtin_ia32_pcmpestria128: 2426 case X86::BI__builtin_ia32_pcmpestric128: 2427 case X86::BI__builtin_ia32_pcmpestrio128: 2428 case X86::BI__builtin_ia32_pcmpestris128: 2429 case X86::BI__builtin_ia32_pcmpestriz128: 2430 i = 4; l = -128; u = 255; 2431 break; 2432 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2433 case X86::BI__builtin_ia32_rndscaless_round_mask: 2434 i = 4; l = 0; u = 255; 2435 break; 2436 } 2437 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2438 } 2439 2440 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2441 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2442 /// Returns true when the format fits the function and the FormatStringInfo has 2443 /// been populated. 2444 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2445 FormatStringInfo *FSI) { 2446 FSI->HasVAListArg = Format->getFirstArg() == 0; 2447 FSI->FormatIdx = Format->getFormatIdx() - 1; 2448 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2449 2450 // The way the format attribute works in GCC, the implicit this argument 2451 // of member functions is counted. However, it doesn't appear in our own 2452 // lists, so decrement format_idx in that case. 2453 if (IsCXXMember) { 2454 if(FSI->FormatIdx == 0) 2455 return false; 2456 --FSI->FormatIdx; 2457 if (FSI->FirstDataArg != 0) 2458 --FSI->FirstDataArg; 2459 } 2460 return true; 2461 } 2462 2463 /// Checks if a the given expression evaluates to null. 2464 /// 2465 /// \brief Returns true if the value evaluates to null. 2466 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2467 // If the expression has non-null type, it doesn't evaluate to null. 2468 if (auto nullability 2469 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2470 if (*nullability == NullabilityKind::NonNull) 2471 return false; 2472 } 2473 2474 // As a special case, transparent unions initialized with zero are 2475 // considered null for the purposes of the nonnull attribute. 2476 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2477 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2478 if (const CompoundLiteralExpr *CLE = 2479 dyn_cast<CompoundLiteralExpr>(Expr)) 2480 if (const InitListExpr *ILE = 2481 dyn_cast<InitListExpr>(CLE->getInitializer())) 2482 Expr = ILE->getInit(0); 2483 } 2484 2485 bool Result; 2486 return (!Expr->isValueDependent() && 2487 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2488 !Result); 2489 } 2490 2491 static void CheckNonNullArgument(Sema &S, 2492 const Expr *ArgExpr, 2493 SourceLocation CallSiteLoc) { 2494 if (CheckNonNullExpr(S, ArgExpr)) 2495 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2496 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2497 } 2498 2499 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2500 FormatStringInfo FSI; 2501 if ((GetFormatStringType(Format) == FST_NSString) && 2502 getFormatStringInfo(Format, false, &FSI)) { 2503 Idx = FSI.FormatIdx; 2504 return true; 2505 } 2506 return false; 2507 } 2508 /// \brief Diagnose use of %s directive in an NSString which is being passed 2509 /// as formatting string to formatting method. 2510 static void 2511 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2512 const NamedDecl *FDecl, 2513 Expr **Args, 2514 unsigned NumArgs) { 2515 unsigned Idx = 0; 2516 bool Format = false; 2517 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2518 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2519 Idx = 2; 2520 Format = true; 2521 } 2522 else 2523 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2524 if (S.GetFormatNSStringIdx(I, Idx)) { 2525 Format = true; 2526 break; 2527 } 2528 } 2529 if (!Format || NumArgs <= Idx) 2530 return; 2531 const Expr *FormatExpr = Args[Idx]; 2532 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2533 FormatExpr = CSCE->getSubExpr(); 2534 const StringLiteral *FormatString; 2535 if (const ObjCStringLiteral *OSL = 2536 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2537 FormatString = OSL->getString(); 2538 else 2539 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2540 if (!FormatString) 2541 return; 2542 if (S.FormatStringHasSArg(FormatString)) { 2543 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2544 << "%s" << 1 << 1; 2545 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2546 << FDecl->getDeclName(); 2547 } 2548 } 2549 2550 /// Determine whether the given type has a non-null nullability annotation. 2551 static bool isNonNullType(ASTContext &ctx, QualType type) { 2552 if (auto nullability = type->getNullability(ctx)) 2553 return *nullability == NullabilityKind::NonNull; 2554 2555 return false; 2556 } 2557 2558 static void CheckNonNullArguments(Sema &S, 2559 const NamedDecl *FDecl, 2560 const FunctionProtoType *Proto, 2561 ArrayRef<const Expr *> Args, 2562 SourceLocation CallSiteLoc) { 2563 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2564 2565 // Check the attributes attached to the method/function itself. 2566 llvm::SmallBitVector NonNullArgs; 2567 if (FDecl) { 2568 // Handle the nonnull attribute on the function/method declaration itself. 2569 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2570 if (!NonNull->args_size()) { 2571 // Easy case: all pointer arguments are nonnull. 2572 for (const auto *Arg : Args) 2573 if (S.isValidPointerAttrType(Arg->getType())) 2574 CheckNonNullArgument(S, Arg, CallSiteLoc); 2575 return; 2576 } 2577 2578 for (unsigned Val : NonNull->args()) { 2579 if (Val >= Args.size()) 2580 continue; 2581 if (NonNullArgs.empty()) 2582 NonNullArgs.resize(Args.size()); 2583 NonNullArgs.set(Val); 2584 } 2585 } 2586 } 2587 2588 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2589 // Handle the nonnull attribute on the parameters of the 2590 // function/method. 2591 ArrayRef<ParmVarDecl*> parms; 2592 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2593 parms = FD->parameters(); 2594 else 2595 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2596 2597 unsigned ParamIndex = 0; 2598 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2599 I != E; ++I, ++ParamIndex) { 2600 const ParmVarDecl *PVD = *I; 2601 if (PVD->hasAttr<NonNullAttr>() || 2602 isNonNullType(S.Context, PVD->getType())) { 2603 if (NonNullArgs.empty()) 2604 NonNullArgs.resize(Args.size()); 2605 2606 NonNullArgs.set(ParamIndex); 2607 } 2608 } 2609 } else { 2610 // If we have a non-function, non-method declaration but no 2611 // function prototype, try to dig out the function prototype. 2612 if (!Proto) { 2613 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2614 QualType type = VD->getType().getNonReferenceType(); 2615 if (auto pointerType = type->getAs<PointerType>()) 2616 type = pointerType->getPointeeType(); 2617 else if (auto blockType = type->getAs<BlockPointerType>()) 2618 type = blockType->getPointeeType(); 2619 // FIXME: data member pointers? 2620 2621 // Dig out the function prototype, if there is one. 2622 Proto = type->getAs<FunctionProtoType>(); 2623 } 2624 } 2625 2626 // Fill in non-null argument information from the nullability 2627 // information on the parameter types (if we have them). 2628 if (Proto) { 2629 unsigned Index = 0; 2630 for (auto paramType : Proto->getParamTypes()) { 2631 if (isNonNullType(S.Context, paramType)) { 2632 if (NonNullArgs.empty()) 2633 NonNullArgs.resize(Args.size()); 2634 2635 NonNullArgs.set(Index); 2636 } 2637 2638 ++Index; 2639 } 2640 } 2641 } 2642 2643 // Check for non-null arguments. 2644 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2645 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2646 if (NonNullArgs[ArgIndex]) 2647 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2648 } 2649 } 2650 2651 /// Handles the checks for format strings, non-POD arguments to vararg 2652 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2653 /// attributes. 2654 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2655 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2656 bool IsMemberFunction, SourceLocation Loc, 2657 SourceRange Range, VariadicCallType CallType) { 2658 // FIXME: We should check as much as we can in the template definition. 2659 if (CurContext->isDependentContext()) 2660 return; 2661 2662 // Printf and scanf checking. 2663 llvm::SmallBitVector CheckedVarArgs; 2664 if (FDecl) { 2665 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2666 // Only create vector if there are format attributes. 2667 CheckedVarArgs.resize(Args.size()); 2668 2669 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2670 CheckedVarArgs); 2671 } 2672 } 2673 2674 // Refuse POD arguments that weren't caught by the format string 2675 // checks above. 2676 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2677 if (CallType != VariadicDoesNotApply && 2678 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2679 unsigned NumParams = Proto ? Proto->getNumParams() 2680 : FDecl && isa<FunctionDecl>(FDecl) 2681 ? cast<FunctionDecl>(FDecl)->getNumParams() 2682 : FDecl && isa<ObjCMethodDecl>(FDecl) 2683 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2684 : 0; 2685 2686 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2687 // Args[ArgIdx] can be null in malformed code. 2688 if (const Expr *Arg = Args[ArgIdx]) { 2689 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2690 checkVariadicArgument(Arg, CallType); 2691 } 2692 } 2693 } 2694 2695 if (FDecl || Proto) { 2696 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2697 2698 // Type safety checking. 2699 if (FDecl) { 2700 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2701 CheckArgumentWithTypeTag(I, Args.data()); 2702 } 2703 } 2704 2705 if (FD) 2706 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 2707 } 2708 2709 /// CheckConstructorCall - Check a constructor call for correctness and safety 2710 /// properties not enforced by the C type system. 2711 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2712 ArrayRef<const Expr *> Args, 2713 const FunctionProtoType *Proto, 2714 SourceLocation Loc) { 2715 VariadicCallType CallType = 2716 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2717 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 2718 Loc, SourceRange(), CallType); 2719 } 2720 2721 /// CheckFunctionCall - Check a direct function call for various correctness 2722 /// and safety properties not strictly enforced by the C type system. 2723 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2724 const FunctionProtoType *Proto) { 2725 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2726 isa<CXXMethodDecl>(FDecl); 2727 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2728 IsMemberOperatorCall; 2729 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2730 TheCall->getCallee()); 2731 Expr** Args = TheCall->getArgs(); 2732 unsigned NumArgs = TheCall->getNumArgs(); 2733 2734 Expr *ImplicitThis = nullptr; 2735 if (IsMemberOperatorCall) { 2736 // If this is a call to a member operator, hide the first argument 2737 // from checkCall. 2738 // FIXME: Our choice of AST representation here is less than ideal. 2739 ImplicitThis = Args[0]; 2740 ++Args; 2741 --NumArgs; 2742 } else if (IsMemberFunction) 2743 ImplicitThis = 2744 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 2745 2746 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 2747 IsMemberFunction, TheCall->getRParenLoc(), 2748 TheCall->getCallee()->getSourceRange(), CallType); 2749 2750 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2751 // None of the checks below are needed for functions that don't have 2752 // simple names (e.g., C++ conversion functions). 2753 if (!FnInfo) 2754 return false; 2755 2756 CheckAbsoluteValueFunction(TheCall, FDecl); 2757 CheckMaxUnsignedZero(TheCall, FDecl); 2758 2759 if (getLangOpts().ObjC1) 2760 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2761 2762 unsigned CMId = FDecl->getMemoryFunctionKind(); 2763 if (CMId == 0) 2764 return false; 2765 2766 // Handle memory setting and copying functions. 2767 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2768 CheckStrlcpycatArguments(TheCall, FnInfo); 2769 else if (CMId == Builtin::BIstrncat) 2770 CheckStrncatArguments(TheCall, FnInfo); 2771 else 2772 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2773 2774 return false; 2775 } 2776 2777 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2778 ArrayRef<const Expr *> Args) { 2779 VariadicCallType CallType = 2780 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2781 2782 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 2783 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2784 CallType); 2785 2786 return false; 2787 } 2788 2789 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2790 const FunctionProtoType *Proto) { 2791 QualType Ty; 2792 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2793 Ty = V->getType().getNonReferenceType(); 2794 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2795 Ty = F->getType().getNonReferenceType(); 2796 else 2797 return false; 2798 2799 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2800 !Ty->isFunctionProtoType()) 2801 return false; 2802 2803 VariadicCallType CallType; 2804 if (!Proto || !Proto->isVariadic()) { 2805 CallType = VariadicDoesNotApply; 2806 } else if (Ty->isBlockPointerType()) { 2807 CallType = VariadicBlock; 2808 } else { // Ty->isFunctionPointerType() 2809 CallType = VariadicFunction; 2810 } 2811 2812 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 2813 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2814 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2815 TheCall->getCallee()->getSourceRange(), CallType); 2816 2817 return false; 2818 } 2819 2820 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2821 /// such as function pointers returned from functions. 2822 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2823 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2824 TheCall->getCallee()); 2825 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 2826 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2827 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2828 TheCall->getCallee()->getSourceRange(), CallType); 2829 2830 return false; 2831 } 2832 2833 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2834 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2835 return false; 2836 2837 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2838 switch (Op) { 2839 case AtomicExpr::AO__c11_atomic_init: 2840 case AtomicExpr::AO__opencl_atomic_init: 2841 llvm_unreachable("There is no ordering argument for an init"); 2842 2843 case AtomicExpr::AO__c11_atomic_load: 2844 case AtomicExpr::AO__opencl_atomic_load: 2845 case AtomicExpr::AO__atomic_load_n: 2846 case AtomicExpr::AO__atomic_load: 2847 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2848 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2849 2850 case AtomicExpr::AO__c11_atomic_store: 2851 case AtomicExpr::AO__opencl_atomic_store: 2852 case AtomicExpr::AO__atomic_store: 2853 case AtomicExpr::AO__atomic_store_n: 2854 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2855 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2856 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2857 2858 default: 2859 return true; 2860 } 2861 } 2862 2863 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2864 AtomicExpr::AtomicOp Op) { 2865 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2866 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2867 2868 // All the non-OpenCL operations take one of the following forms. 2869 // The OpenCL operations take the __c11 forms with one extra argument for 2870 // synchronization scope. 2871 enum { 2872 // C __c11_atomic_init(A *, C) 2873 Init, 2874 // C __c11_atomic_load(A *, int) 2875 Load, 2876 // void __atomic_load(A *, CP, int) 2877 LoadCopy, 2878 // void __atomic_store(A *, CP, int) 2879 Copy, 2880 // C __c11_atomic_add(A *, M, int) 2881 Arithmetic, 2882 // C __atomic_exchange_n(A *, CP, int) 2883 Xchg, 2884 // void __atomic_exchange(A *, C *, CP, int) 2885 GNUXchg, 2886 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2887 C11CmpXchg, 2888 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2889 GNUCmpXchg 2890 } Form = Init; 2891 const unsigned NumForm = GNUCmpXchg + 1; 2892 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2893 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2894 // where: 2895 // C is an appropriate type, 2896 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2897 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2898 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2899 // the int parameters are for orderings. 2900 2901 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 2902 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 2903 "need to update code for modified forms"); 2904 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2905 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2906 AtomicExpr::AO__atomic_load, 2907 "need to update code for modified C11 atomics"); 2908 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 2909 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 2910 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 2911 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 2912 IsOpenCL; 2913 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2914 Op == AtomicExpr::AO__atomic_store_n || 2915 Op == AtomicExpr::AO__atomic_exchange_n || 2916 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2917 bool IsAddSub = false; 2918 2919 switch (Op) { 2920 case AtomicExpr::AO__c11_atomic_init: 2921 case AtomicExpr::AO__opencl_atomic_init: 2922 Form = Init; 2923 break; 2924 2925 case AtomicExpr::AO__c11_atomic_load: 2926 case AtomicExpr::AO__opencl_atomic_load: 2927 case AtomicExpr::AO__atomic_load_n: 2928 Form = Load; 2929 break; 2930 2931 case AtomicExpr::AO__atomic_load: 2932 Form = LoadCopy; 2933 break; 2934 2935 case AtomicExpr::AO__c11_atomic_store: 2936 case AtomicExpr::AO__opencl_atomic_store: 2937 case AtomicExpr::AO__atomic_store: 2938 case AtomicExpr::AO__atomic_store_n: 2939 Form = Copy; 2940 break; 2941 2942 case AtomicExpr::AO__c11_atomic_fetch_add: 2943 case AtomicExpr::AO__c11_atomic_fetch_sub: 2944 case AtomicExpr::AO__opencl_atomic_fetch_add: 2945 case AtomicExpr::AO__opencl_atomic_fetch_sub: 2946 case AtomicExpr::AO__opencl_atomic_fetch_min: 2947 case AtomicExpr::AO__opencl_atomic_fetch_max: 2948 case AtomicExpr::AO__atomic_fetch_add: 2949 case AtomicExpr::AO__atomic_fetch_sub: 2950 case AtomicExpr::AO__atomic_add_fetch: 2951 case AtomicExpr::AO__atomic_sub_fetch: 2952 IsAddSub = true; 2953 // Fall through. 2954 case AtomicExpr::AO__c11_atomic_fetch_and: 2955 case AtomicExpr::AO__c11_atomic_fetch_or: 2956 case AtomicExpr::AO__c11_atomic_fetch_xor: 2957 case AtomicExpr::AO__opencl_atomic_fetch_and: 2958 case AtomicExpr::AO__opencl_atomic_fetch_or: 2959 case AtomicExpr::AO__opencl_atomic_fetch_xor: 2960 case AtomicExpr::AO__atomic_fetch_and: 2961 case AtomicExpr::AO__atomic_fetch_or: 2962 case AtomicExpr::AO__atomic_fetch_xor: 2963 case AtomicExpr::AO__atomic_fetch_nand: 2964 case AtomicExpr::AO__atomic_and_fetch: 2965 case AtomicExpr::AO__atomic_or_fetch: 2966 case AtomicExpr::AO__atomic_xor_fetch: 2967 case AtomicExpr::AO__atomic_nand_fetch: 2968 Form = Arithmetic; 2969 break; 2970 2971 case AtomicExpr::AO__c11_atomic_exchange: 2972 case AtomicExpr::AO__opencl_atomic_exchange: 2973 case AtomicExpr::AO__atomic_exchange_n: 2974 Form = Xchg; 2975 break; 2976 2977 case AtomicExpr::AO__atomic_exchange: 2978 Form = GNUXchg; 2979 break; 2980 2981 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2982 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2983 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 2984 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 2985 Form = C11CmpXchg; 2986 break; 2987 2988 case AtomicExpr::AO__atomic_compare_exchange: 2989 case AtomicExpr::AO__atomic_compare_exchange_n: 2990 Form = GNUCmpXchg; 2991 break; 2992 } 2993 2994 unsigned AdjustedNumArgs = NumArgs[Form]; 2995 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 2996 ++AdjustedNumArgs; 2997 // Check we have the right number of arguments. 2998 if (TheCall->getNumArgs() < AdjustedNumArgs) { 2999 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3000 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3001 << TheCall->getCallee()->getSourceRange(); 3002 return ExprError(); 3003 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 3004 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 3005 diag::err_typecheck_call_too_many_args) 3006 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3007 << TheCall->getCallee()->getSourceRange(); 3008 return ExprError(); 3009 } 3010 3011 // Inspect the first argument of the atomic operation. 3012 Expr *Ptr = TheCall->getArg(0); 3013 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 3014 if (ConvertedPtr.isInvalid()) 3015 return ExprError(); 3016 3017 Ptr = ConvertedPtr.get(); 3018 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 3019 if (!pointerType) { 3020 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3021 << Ptr->getType() << Ptr->getSourceRange(); 3022 return ExprError(); 3023 } 3024 3025 // For a __c11 builtin, this should be a pointer to an _Atomic type. 3026 QualType AtomTy = pointerType->getPointeeType(); // 'A' 3027 QualType ValType = AtomTy; // 'C' 3028 if (IsC11) { 3029 if (!AtomTy->isAtomicType()) { 3030 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 3031 << Ptr->getType() << Ptr->getSourceRange(); 3032 return ExprError(); 3033 } 3034 if (AtomTy.isConstQualified() || 3035 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3036 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 3037 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3038 << Ptr->getSourceRange(); 3039 return ExprError(); 3040 } 3041 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 3042 } else if (Form != Load && Form != LoadCopy) { 3043 if (ValType.isConstQualified()) { 3044 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 3045 << Ptr->getType() << Ptr->getSourceRange(); 3046 return ExprError(); 3047 } 3048 } 3049 3050 // For an arithmetic operation, the implied arithmetic must be well-formed. 3051 if (Form == Arithmetic) { 3052 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3053 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 3054 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3055 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3056 return ExprError(); 3057 } 3058 if (!IsAddSub && !ValType->isIntegerType()) { 3059 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3060 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3061 return ExprError(); 3062 } 3063 if (IsC11 && ValType->isPointerType() && 3064 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3065 diag::err_incomplete_type)) { 3066 return ExprError(); 3067 } 3068 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3069 // For __atomic_*_n operations, the value type must be a scalar integral or 3070 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3071 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3072 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3073 return ExprError(); 3074 } 3075 3076 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3077 !AtomTy->isScalarType()) { 3078 // For GNU atomics, require a trivially-copyable type. This is not part of 3079 // the GNU atomics specification, but we enforce it for sanity. 3080 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3081 << Ptr->getType() << Ptr->getSourceRange(); 3082 return ExprError(); 3083 } 3084 3085 switch (ValType.getObjCLifetime()) { 3086 case Qualifiers::OCL_None: 3087 case Qualifiers::OCL_ExplicitNone: 3088 // okay 3089 break; 3090 3091 case Qualifiers::OCL_Weak: 3092 case Qualifiers::OCL_Strong: 3093 case Qualifiers::OCL_Autoreleasing: 3094 // FIXME: Can this happen? By this point, ValType should be known 3095 // to be trivially copyable. 3096 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3097 << ValType << Ptr->getSourceRange(); 3098 return ExprError(); 3099 } 3100 3101 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 3102 // volatile-ness of the pointee-type inject itself into the result or the 3103 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 3104 ValType.removeLocalVolatile(); 3105 ValType.removeLocalConst(); 3106 QualType ResultType = ValType; 3107 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3108 Form == Init) 3109 ResultType = Context.VoidTy; 3110 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3111 ResultType = Context.BoolTy; 3112 3113 // The type of a parameter passed 'by value'. In the GNU atomics, such 3114 // arguments are actually passed as pointers. 3115 QualType ByValType = ValType; // 'CP' 3116 if (!IsC11 && !IsN) 3117 ByValType = Ptr->getType(); 3118 3119 // The first argument --- the pointer --- has a fixed type; we 3120 // deduce the types of the rest of the arguments accordingly. Walk 3121 // the remaining arguments, converting them to the deduced value type. 3122 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) { 3123 QualType Ty; 3124 if (i < NumVals[Form] + 1) { 3125 switch (i) { 3126 case 1: 3127 // The second argument is the non-atomic operand. For arithmetic, this 3128 // is always passed by value, and for a compare_exchange it is always 3129 // passed by address. For the rest, GNU uses by-address and C11 uses 3130 // by-value. 3131 assert(Form != Load); 3132 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3133 Ty = ValType; 3134 else if (Form == Copy || Form == Xchg) 3135 Ty = ByValType; 3136 else if (Form == Arithmetic) 3137 Ty = Context.getPointerDiffType(); 3138 else { 3139 Expr *ValArg = TheCall->getArg(i); 3140 // Treat this argument as _Nonnull as we want to show a warning if 3141 // NULL is passed into it. 3142 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3143 LangAS AS = LangAS::Default; 3144 // Keep address space of non-atomic pointer type. 3145 if (const PointerType *PtrTy = 3146 ValArg->getType()->getAs<PointerType>()) { 3147 AS = PtrTy->getPointeeType().getAddressSpace(); 3148 } 3149 Ty = Context.getPointerType( 3150 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3151 } 3152 break; 3153 case 2: 3154 // The third argument to compare_exchange / GNU exchange is a 3155 // (pointer to a) desired value. 3156 Ty = ByValType; 3157 break; 3158 case 3: 3159 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3160 Ty = Context.BoolTy; 3161 break; 3162 } 3163 } else { 3164 // The order(s) and scope are always converted to int. 3165 Ty = Context.IntTy; 3166 } 3167 3168 InitializedEntity Entity = 3169 InitializedEntity::InitializeParameter(Context, Ty, false); 3170 ExprResult Arg = TheCall->getArg(i); 3171 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3172 if (Arg.isInvalid()) 3173 return true; 3174 TheCall->setArg(i, Arg.get()); 3175 } 3176 3177 // Permute the arguments into a 'consistent' order. 3178 SmallVector<Expr*, 5> SubExprs; 3179 SubExprs.push_back(Ptr); 3180 switch (Form) { 3181 case Init: 3182 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3183 SubExprs.push_back(TheCall->getArg(1)); // Val1 3184 break; 3185 case Load: 3186 SubExprs.push_back(TheCall->getArg(1)); // Order 3187 break; 3188 case LoadCopy: 3189 case Copy: 3190 case Arithmetic: 3191 case Xchg: 3192 SubExprs.push_back(TheCall->getArg(2)); // Order 3193 SubExprs.push_back(TheCall->getArg(1)); // Val1 3194 break; 3195 case GNUXchg: 3196 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3197 SubExprs.push_back(TheCall->getArg(3)); // Order 3198 SubExprs.push_back(TheCall->getArg(1)); // Val1 3199 SubExprs.push_back(TheCall->getArg(2)); // Val2 3200 break; 3201 case C11CmpXchg: 3202 SubExprs.push_back(TheCall->getArg(3)); // Order 3203 SubExprs.push_back(TheCall->getArg(1)); // Val1 3204 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3205 SubExprs.push_back(TheCall->getArg(2)); // Val2 3206 break; 3207 case GNUCmpXchg: 3208 SubExprs.push_back(TheCall->getArg(4)); // Order 3209 SubExprs.push_back(TheCall->getArg(1)); // Val1 3210 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3211 SubExprs.push_back(TheCall->getArg(2)); // Val2 3212 SubExprs.push_back(TheCall->getArg(3)); // Weak 3213 break; 3214 } 3215 3216 if (SubExprs.size() >= 2 && Form != Init) { 3217 llvm::APSInt Result(32); 3218 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3219 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3220 Diag(SubExprs[1]->getLocStart(), 3221 diag::warn_atomic_op_has_invalid_memory_order) 3222 << SubExprs[1]->getSourceRange(); 3223 } 3224 3225 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 3226 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3227 llvm::APSInt Result(32); 3228 if (Scope->isIntegerConstantExpr(Result, Context) && 3229 !ScopeModel->isValid(Result.getZExtValue())) { 3230 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3231 << Scope->getSourceRange(); 3232 } 3233 SubExprs.push_back(Scope); 3234 } 3235 3236 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3237 SubExprs, ResultType, Op, 3238 TheCall->getRParenLoc()); 3239 3240 if ((Op == AtomicExpr::AO__c11_atomic_load || 3241 Op == AtomicExpr::AO__c11_atomic_store || 3242 Op == AtomicExpr::AO__opencl_atomic_load || 3243 Op == AtomicExpr::AO__opencl_atomic_store ) && 3244 Context.AtomicUsesUnsupportedLibcall(AE)) 3245 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3246 << ((Op == AtomicExpr::AO__c11_atomic_load || 3247 Op == AtomicExpr::AO__opencl_atomic_load) 3248 ? 0 : 1); 3249 3250 return AE; 3251 } 3252 3253 /// checkBuiltinArgument - Given a call to a builtin function, perform 3254 /// normal type-checking on the given argument, updating the call in 3255 /// place. This is useful when a builtin function requires custom 3256 /// type-checking for some of its arguments but not necessarily all of 3257 /// them. 3258 /// 3259 /// Returns true on error. 3260 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3261 FunctionDecl *Fn = E->getDirectCallee(); 3262 assert(Fn && "builtin call without direct callee!"); 3263 3264 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3265 InitializedEntity Entity = 3266 InitializedEntity::InitializeParameter(S.Context, Param); 3267 3268 ExprResult Arg = E->getArg(0); 3269 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3270 if (Arg.isInvalid()) 3271 return true; 3272 3273 E->setArg(ArgIndex, Arg.get()); 3274 return false; 3275 } 3276 3277 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3278 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3279 /// type of its first argument. The main ActOnCallExpr routines have already 3280 /// promoted the types of arguments because all of these calls are prototyped as 3281 /// void(...). 3282 /// 3283 /// This function goes through and does final semantic checking for these 3284 /// builtins, 3285 ExprResult 3286 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3287 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3288 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3289 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3290 3291 // Ensure that we have at least one argument to do type inference from. 3292 if (TheCall->getNumArgs() < 1) { 3293 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3294 << 0 << 1 << TheCall->getNumArgs() 3295 << TheCall->getCallee()->getSourceRange(); 3296 return ExprError(); 3297 } 3298 3299 // Inspect the first argument of the atomic builtin. This should always be 3300 // a pointer type, whose element is an integral scalar or pointer type. 3301 // Because it is a pointer type, we don't have to worry about any implicit 3302 // casts here. 3303 // FIXME: We don't allow floating point scalars as input. 3304 Expr *FirstArg = TheCall->getArg(0); 3305 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3306 if (FirstArgResult.isInvalid()) 3307 return ExprError(); 3308 FirstArg = FirstArgResult.get(); 3309 TheCall->setArg(0, FirstArg); 3310 3311 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3312 if (!pointerType) { 3313 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3314 << FirstArg->getType() << FirstArg->getSourceRange(); 3315 return ExprError(); 3316 } 3317 3318 QualType ValType = pointerType->getPointeeType(); 3319 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3320 !ValType->isBlockPointerType()) { 3321 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3322 << FirstArg->getType() << FirstArg->getSourceRange(); 3323 return ExprError(); 3324 } 3325 3326 switch (ValType.getObjCLifetime()) { 3327 case Qualifiers::OCL_None: 3328 case Qualifiers::OCL_ExplicitNone: 3329 // okay 3330 break; 3331 3332 case Qualifiers::OCL_Weak: 3333 case Qualifiers::OCL_Strong: 3334 case Qualifiers::OCL_Autoreleasing: 3335 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3336 << ValType << FirstArg->getSourceRange(); 3337 return ExprError(); 3338 } 3339 3340 // Strip any qualifiers off ValType. 3341 ValType = ValType.getUnqualifiedType(); 3342 3343 // The majority of builtins return a value, but a few have special return 3344 // types, so allow them to override appropriately below. 3345 QualType ResultType = ValType; 3346 3347 // We need to figure out which concrete builtin this maps onto. For example, 3348 // __sync_fetch_and_add with a 2 byte object turns into 3349 // __sync_fetch_and_add_2. 3350 #define BUILTIN_ROW(x) \ 3351 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3352 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3353 3354 static const unsigned BuiltinIndices[][5] = { 3355 BUILTIN_ROW(__sync_fetch_and_add), 3356 BUILTIN_ROW(__sync_fetch_and_sub), 3357 BUILTIN_ROW(__sync_fetch_and_or), 3358 BUILTIN_ROW(__sync_fetch_and_and), 3359 BUILTIN_ROW(__sync_fetch_and_xor), 3360 BUILTIN_ROW(__sync_fetch_and_nand), 3361 3362 BUILTIN_ROW(__sync_add_and_fetch), 3363 BUILTIN_ROW(__sync_sub_and_fetch), 3364 BUILTIN_ROW(__sync_and_and_fetch), 3365 BUILTIN_ROW(__sync_or_and_fetch), 3366 BUILTIN_ROW(__sync_xor_and_fetch), 3367 BUILTIN_ROW(__sync_nand_and_fetch), 3368 3369 BUILTIN_ROW(__sync_val_compare_and_swap), 3370 BUILTIN_ROW(__sync_bool_compare_and_swap), 3371 BUILTIN_ROW(__sync_lock_test_and_set), 3372 BUILTIN_ROW(__sync_lock_release), 3373 BUILTIN_ROW(__sync_swap) 3374 }; 3375 #undef BUILTIN_ROW 3376 3377 // Determine the index of the size. 3378 unsigned SizeIndex; 3379 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3380 case 1: SizeIndex = 0; break; 3381 case 2: SizeIndex = 1; break; 3382 case 4: SizeIndex = 2; break; 3383 case 8: SizeIndex = 3; break; 3384 case 16: SizeIndex = 4; break; 3385 default: 3386 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3387 << FirstArg->getType() << FirstArg->getSourceRange(); 3388 return ExprError(); 3389 } 3390 3391 // Each of these builtins has one pointer argument, followed by some number of 3392 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3393 // that we ignore. Find out which row of BuiltinIndices to read from as well 3394 // as the number of fixed args. 3395 unsigned BuiltinID = FDecl->getBuiltinID(); 3396 unsigned BuiltinIndex, NumFixed = 1; 3397 bool WarnAboutSemanticsChange = false; 3398 switch (BuiltinID) { 3399 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3400 case Builtin::BI__sync_fetch_and_add: 3401 case Builtin::BI__sync_fetch_and_add_1: 3402 case Builtin::BI__sync_fetch_and_add_2: 3403 case Builtin::BI__sync_fetch_and_add_4: 3404 case Builtin::BI__sync_fetch_and_add_8: 3405 case Builtin::BI__sync_fetch_and_add_16: 3406 BuiltinIndex = 0; 3407 break; 3408 3409 case Builtin::BI__sync_fetch_and_sub: 3410 case Builtin::BI__sync_fetch_and_sub_1: 3411 case Builtin::BI__sync_fetch_and_sub_2: 3412 case Builtin::BI__sync_fetch_and_sub_4: 3413 case Builtin::BI__sync_fetch_and_sub_8: 3414 case Builtin::BI__sync_fetch_and_sub_16: 3415 BuiltinIndex = 1; 3416 break; 3417 3418 case Builtin::BI__sync_fetch_and_or: 3419 case Builtin::BI__sync_fetch_and_or_1: 3420 case Builtin::BI__sync_fetch_and_or_2: 3421 case Builtin::BI__sync_fetch_and_or_4: 3422 case Builtin::BI__sync_fetch_and_or_8: 3423 case Builtin::BI__sync_fetch_and_or_16: 3424 BuiltinIndex = 2; 3425 break; 3426 3427 case Builtin::BI__sync_fetch_and_and: 3428 case Builtin::BI__sync_fetch_and_and_1: 3429 case Builtin::BI__sync_fetch_and_and_2: 3430 case Builtin::BI__sync_fetch_and_and_4: 3431 case Builtin::BI__sync_fetch_and_and_8: 3432 case Builtin::BI__sync_fetch_and_and_16: 3433 BuiltinIndex = 3; 3434 break; 3435 3436 case Builtin::BI__sync_fetch_and_xor: 3437 case Builtin::BI__sync_fetch_and_xor_1: 3438 case Builtin::BI__sync_fetch_and_xor_2: 3439 case Builtin::BI__sync_fetch_and_xor_4: 3440 case Builtin::BI__sync_fetch_and_xor_8: 3441 case Builtin::BI__sync_fetch_and_xor_16: 3442 BuiltinIndex = 4; 3443 break; 3444 3445 case Builtin::BI__sync_fetch_and_nand: 3446 case Builtin::BI__sync_fetch_and_nand_1: 3447 case Builtin::BI__sync_fetch_and_nand_2: 3448 case Builtin::BI__sync_fetch_and_nand_4: 3449 case Builtin::BI__sync_fetch_and_nand_8: 3450 case Builtin::BI__sync_fetch_and_nand_16: 3451 BuiltinIndex = 5; 3452 WarnAboutSemanticsChange = true; 3453 break; 3454 3455 case Builtin::BI__sync_add_and_fetch: 3456 case Builtin::BI__sync_add_and_fetch_1: 3457 case Builtin::BI__sync_add_and_fetch_2: 3458 case Builtin::BI__sync_add_and_fetch_4: 3459 case Builtin::BI__sync_add_and_fetch_8: 3460 case Builtin::BI__sync_add_and_fetch_16: 3461 BuiltinIndex = 6; 3462 break; 3463 3464 case Builtin::BI__sync_sub_and_fetch: 3465 case Builtin::BI__sync_sub_and_fetch_1: 3466 case Builtin::BI__sync_sub_and_fetch_2: 3467 case Builtin::BI__sync_sub_and_fetch_4: 3468 case Builtin::BI__sync_sub_and_fetch_8: 3469 case Builtin::BI__sync_sub_and_fetch_16: 3470 BuiltinIndex = 7; 3471 break; 3472 3473 case Builtin::BI__sync_and_and_fetch: 3474 case Builtin::BI__sync_and_and_fetch_1: 3475 case Builtin::BI__sync_and_and_fetch_2: 3476 case Builtin::BI__sync_and_and_fetch_4: 3477 case Builtin::BI__sync_and_and_fetch_8: 3478 case Builtin::BI__sync_and_and_fetch_16: 3479 BuiltinIndex = 8; 3480 break; 3481 3482 case Builtin::BI__sync_or_and_fetch: 3483 case Builtin::BI__sync_or_and_fetch_1: 3484 case Builtin::BI__sync_or_and_fetch_2: 3485 case Builtin::BI__sync_or_and_fetch_4: 3486 case Builtin::BI__sync_or_and_fetch_8: 3487 case Builtin::BI__sync_or_and_fetch_16: 3488 BuiltinIndex = 9; 3489 break; 3490 3491 case Builtin::BI__sync_xor_and_fetch: 3492 case Builtin::BI__sync_xor_and_fetch_1: 3493 case Builtin::BI__sync_xor_and_fetch_2: 3494 case Builtin::BI__sync_xor_and_fetch_4: 3495 case Builtin::BI__sync_xor_and_fetch_8: 3496 case Builtin::BI__sync_xor_and_fetch_16: 3497 BuiltinIndex = 10; 3498 break; 3499 3500 case Builtin::BI__sync_nand_and_fetch: 3501 case Builtin::BI__sync_nand_and_fetch_1: 3502 case Builtin::BI__sync_nand_and_fetch_2: 3503 case Builtin::BI__sync_nand_and_fetch_4: 3504 case Builtin::BI__sync_nand_and_fetch_8: 3505 case Builtin::BI__sync_nand_and_fetch_16: 3506 BuiltinIndex = 11; 3507 WarnAboutSemanticsChange = true; 3508 break; 3509 3510 case Builtin::BI__sync_val_compare_and_swap: 3511 case Builtin::BI__sync_val_compare_and_swap_1: 3512 case Builtin::BI__sync_val_compare_and_swap_2: 3513 case Builtin::BI__sync_val_compare_and_swap_4: 3514 case Builtin::BI__sync_val_compare_and_swap_8: 3515 case Builtin::BI__sync_val_compare_and_swap_16: 3516 BuiltinIndex = 12; 3517 NumFixed = 2; 3518 break; 3519 3520 case Builtin::BI__sync_bool_compare_and_swap: 3521 case Builtin::BI__sync_bool_compare_and_swap_1: 3522 case Builtin::BI__sync_bool_compare_and_swap_2: 3523 case Builtin::BI__sync_bool_compare_and_swap_4: 3524 case Builtin::BI__sync_bool_compare_and_swap_8: 3525 case Builtin::BI__sync_bool_compare_and_swap_16: 3526 BuiltinIndex = 13; 3527 NumFixed = 2; 3528 ResultType = Context.BoolTy; 3529 break; 3530 3531 case Builtin::BI__sync_lock_test_and_set: 3532 case Builtin::BI__sync_lock_test_and_set_1: 3533 case Builtin::BI__sync_lock_test_and_set_2: 3534 case Builtin::BI__sync_lock_test_and_set_4: 3535 case Builtin::BI__sync_lock_test_and_set_8: 3536 case Builtin::BI__sync_lock_test_and_set_16: 3537 BuiltinIndex = 14; 3538 break; 3539 3540 case Builtin::BI__sync_lock_release: 3541 case Builtin::BI__sync_lock_release_1: 3542 case Builtin::BI__sync_lock_release_2: 3543 case Builtin::BI__sync_lock_release_4: 3544 case Builtin::BI__sync_lock_release_8: 3545 case Builtin::BI__sync_lock_release_16: 3546 BuiltinIndex = 15; 3547 NumFixed = 0; 3548 ResultType = Context.VoidTy; 3549 break; 3550 3551 case Builtin::BI__sync_swap: 3552 case Builtin::BI__sync_swap_1: 3553 case Builtin::BI__sync_swap_2: 3554 case Builtin::BI__sync_swap_4: 3555 case Builtin::BI__sync_swap_8: 3556 case Builtin::BI__sync_swap_16: 3557 BuiltinIndex = 16; 3558 break; 3559 } 3560 3561 // Now that we know how many fixed arguments we expect, first check that we 3562 // have at least that many. 3563 if (TheCall->getNumArgs() < 1+NumFixed) { 3564 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3565 << 0 << 1+NumFixed << TheCall->getNumArgs() 3566 << TheCall->getCallee()->getSourceRange(); 3567 return ExprError(); 3568 } 3569 3570 if (WarnAboutSemanticsChange) { 3571 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3572 << TheCall->getCallee()->getSourceRange(); 3573 } 3574 3575 // Get the decl for the concrete builtin from this, we can tell what the 3576 // concrete integer type we should convert to is. 3577 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3578 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3579 FunctionDecl *NewBuiltinDecl; 3580 if (NewBuiltinID == BuiltinID) 3581 NewBuiltinDecl = FDecl; 3582 else { 3583 // Perform builtin lookup to avoid redeclaring it. 3584 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3585 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3586 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3587 assert(Res.getFoundDecl()); 3588 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3589 if (!NewBuiltinDecl) 3590 return ExprError(); 3591 } 3592 3593 // The first argument --- the pointer --- has a fixed type; we 3594 // deduce the types of the rest of the arguments accordingly. Walk 3595 // the remaining arguments, converting them to the deduced value type. 3596 for (unsigned i = 0; i != NumFixed; ++i) { 3597 ExprResult Arg = TheCall->getArg(i+1); 3598 3599 // GCC does an implicit conversion to the pointer or integer ValType. This 3600 // can fail in some cases (1i -> int**), check for this error case now. 3601 // Initialize the argument. 3602 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3603 ValType, /*consume*/ false); 3604 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3605 if (Arg.isInvalid()) 3606 return ExprError(); 3607 3608 // Okay, we have something that *can* be converted to the right type. Check 3609 // to see if there is a potentially weird extension going on here. This can 3610 // happen when you do an atomic operation on something like an char* and 3611 // pass in 42. The 42 gets converted to char. This is even more strange 3612 // for things like 45.123 -> char, etc. 3613 // FIXME: Do this check. 3614 TheCall->setArg(i+1, Arg.get()); 3615 } 3616 3617 ASTContext& Context = this->getASTContext(); 3618 3619 // Create a new DeclRefExpr to refer to the new decl. 3620 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3621 Context, 3622 DRE->getQualifierLoc(), 3623 SourceLocation(), 3624 NewBuiltinDecl, 3625 /*enclosing*/ false, 3626 DRE->getLocation(), 3627 Context.BuiltinFnTy, 3628 DRE->getValueKind()); 3629 3630 // Set the callee in the CallExpr. 3631 // FIXME: This loses syntactic information. 3632 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3633 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3634 CK_BuiltinFnToFnPtr); 3635 TheCall->setCallee(PromotedCall.get()); 3636 3637 // Change the result type of the call to match the original value type. This 3638 // is arbitrary, but the codegen for these builtins ins design to handle it 3639 // gracefully. 3640 TheCall->setType(ResultType); 3641 3642 return TheCallResult; 3643 } 3644 3645 /// SemaBuiltinNontemporalOverloaded - We have a call to 3646 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3647 /// overloaded function based on the pointer type of its last argument. 3648 /// 3649 /// This function goes through and does final semantic checking for these 3650 /// builtins. 3651 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3652 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3653 DeclRefExpr *DRE = 3654 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3655 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3656 unsigned BuiltinID = FDecl->getBuiltinID(); 3657 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3658 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3659 "Unexpected nontemporal load/store builtin!"); 3660 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3661 unsigned numArgs = isStore ? 2 : 1; 3662 3663 // Ensure that we have the proper number of arguments. 3664 if (checkArgCount(*this, TheCall, numArgs)) 3665 return ExprError(); 3666 3667 // Inspect the last argument of the nontemporal builtin. This should always 3668 // be a pointer type, from which we imply the type of the memory access. 3669 // Because it is a pointer type, we don't have to worry about any implicit 3670 // casts here. 3671 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3672 ExprResult PointerArgResult = 3673 DefaultFunctionArrayLvalueConversion(PointerArg); 3674 3675 if (PointerArgResult.isInvalid()) 3676 return ExprError(); 3677 PointerArg = PointerArgResult.get(); 3678 TheCall->setArg(numArgs - 1, PointerArg); 3679 3680 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3681 if (!pointerType) { 3682 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3683 << PointerArg->getType() << PointerArg->getSourceRange(); 3684 return ExprError(); 3685 } 3686 3687 QualType ValType = pointerType->getPointeeType(); 3688 3689 // Strip any qualifiers off ValType. 3690 ValType = ValType.getUnqualifiedType(); 3691 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3692 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3693 !ValType->isVectorType()) { 3694 Diag(DRE->getLocStart(), 3695 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3696 << PointerArg->getType() << PointerArg->getSourceRange(); 3697 return ExprError(); 3698 } 3699 3700 if (!isStore) { 3701 TheCall->setType(ValType); 3702 return TheCallResult; 3703 } 3704 3705 ExprResult ValArg = TheCall->getArg(0); 3706 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3707 Context, ValType, /*consume*/ false); 3708 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3709 if (ValArg.isInvalid()) 3710 return ExprError(); 3711 3712 TheCall->setArg(0, ValArg.get()); 3713 TheCall->setType(Context.VoidTy); 3714 return TheCallResult; 3715 } 3716 3717 /// CheckObjCString - Checks that the argument to the builtin 3718 /// CFString constructor is correct 3719 /// Note: It might also make sense to do the UTF-16 conversion here (would 3720 /// simplify the backend). 3721 bool Sema::CheckObjCString(Expr *Arg) { 3722 Arg = Arg->IgnoreParenCasts(); 3723 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3724 3725 if (!Literal || !Literal->isAscii()) { 3726 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3727 << Arg->getSourceRange(); 3728 return true; 3729 } 3730 3731 if (Literal->containsNonAsciiOrNull()) { 3732 StringRef String = Literal->getString(); 3733 unsigned NumBytes = String.size(); 3734 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3735 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3736 llvm::UTF16 *ToPtr = &ToBuf[0]; 3737 3738 llvm::ConversionResult Result = 3739 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3740 ToPtr + NumBytes, llvm::strictConversion); 3741 // Check for conversion failure. 3742 if (Result != llvm::conversionOK) 3743 Diag(Arg->getLocStart(), 3744 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3745 } 3746 return false; 3747 } 3748 3749 /// CheckObjCString - Checks that the format string argument to the os_log() 3750 /// and os_trace() functions is correct, and converts it to const char *. 3751 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3752 Arg = Arg->IgnoreParenCasts(); 3753 auto *Literal = dyn_cast<StringLiteral>(Arg); 3754 if (!Literal) { 3755 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3756 Literal = ObjcLiteral->getString(); 3757 } 3758 } 3759 3760 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3761 return ExprError( 3762 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3763 << Arg->getSourceRange()); 3764 } 3765 3766 ExprResult Result(Literal); 3767 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3768 InitializedEntity Entity = 3769 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3770 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3771 return Result; 3772 } 3773 3774 /// Check that the user is calling the appropriate va_start builtin for the 3775 /// target and calling convention. 3776 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 3777 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 3778 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 3779 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 3780 bool IsWindows = TT.isOSWindows(); 3781 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 3782 if (IsX64 || IsAArch64) { 3783 clang::CallingConv CC = CC_C; 3784 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 3785 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3786 if (IsMSVAStart) { 3787 // Don't allow this in System V ABI functions. 3788 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 3789 return S.Diag(Fn->getLocStart(), 3790 diag::err_ms_va_start_used_in_sysv_function); 3791 } else { 3792 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 3793 // On x64 Windows, don't allow this in System V ABI functions. 3794 // (Yes, that means there's no corresponding way to support variadic 3795 // System V ABI functions on Windows.) 3796 if ((IsWindows && CC == CC_X86_64SysV) || 3797 (!IsWindows && CC == CC_Win64)) 3798 return S.Diag(Fn->getLocStart(), 3799 diag::err_va_start_used_in_wrong_abi_function) 3800 << !IsWindows; 3801 } 3802 return false; 3803 } 3804 3805 if (IsMSVAStart) 3806 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 3807 return false; 3808 } 3809 3810 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 3811 ParmVarDecl **LastParam = nullptr) { 3812 // Determine whether the current function, block, or obj-c method is variadic 3813 // and get its parameter list. 3814 bool IsVariadic = false; 3815 ArrayRef<ParmVarDecl *> Params; 3816 DeclContext *Caller = S.CurContext; 3817 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 3818 IsVariadic = Block->isVariadic(); 3819 Params = Block->parameters(); 3820 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 3821 IsVariadic = FD->isVariadic(); 3822 Params = FD->parameters(); 3823 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 3824 IsVariadic = MD->isVariadic(); 3825 // FIXME: This isn't correct for methods (results in bogus warning). 3826 Params = MD->parameters(); 3827 } else if (isa<CapturedDecl>(Caller)) { 3828 // We don't support va_start in a CapturedDecl. 3829 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 3830 return true; 3831 } else { 3832 // This must be some other declcontext that parses exprs. 3833 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 3834 return true; 3835 } 3836 3837 if (!IsVariadic) { 3838 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 3839 return true; 3840 } 3841 3842 if (LastParam) 3843 *LastParam = Params.empty() ? nullptr : Params.back(); 3844 3845 return false; 3846 } 3847 3848 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3849 /// for validity. Emit an error and return true on failure; return false 3850 /// on success. 3851 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 3852 Expr *Fn = TheCall->getCallee(); 3853 3854 if (checkVAStartABI(*this, BuiltinID, Fn)) 3855 return true; 3856 3857 if (TheCall->getNumArgs() > 2) { 3858 Diag(TheCall->getArg(2)->getLocStart(), 3859 diag::err_typecheck_call_too_many_args) 3860 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3861 << Fn->getSourceRange() 3862 << SourceRange(TheCall->getArg(2)->getLocStart(), 3863 (*(TheCall->arg_end()-1))->getLocEnd()); 3864 return true; 3865 } 3866 3867 if (TheCall->getNumArgs() < 2) { 3868 return Diag(TheCall->getLocEnd(), 3869 diag::err_typecheck_call_too_few_args_at_least) 3870 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3871 } 3872 3873 // Type-check the first argument normally. 3874 if (checkBuiltinArgument(*this, TheCall, 0)) 3875 return true; 3876 3877 // Check that the current function is variadic, and get its last parameter. 3878 ParmVarDecl *LastParam; 3879 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 3880 return true; 3881 3882 // Verify that the second argument to the builtin is the last argument of the 3883 // current function or method. 3884 bool SecondArgIsLastNamedArgument = false; 3885 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3886 3887 // These are valid if SecondArgIsLastNamedArgument is false after the next 3888 // block. 3889 QualType Type; 3890 SourceLocation ParamLoc; 3891 bool IsCRegister = false; 3892 3893 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3894 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3895 SecondArgIsLastNamedArgument = PV == LastParam; 3896 3897 Type = PV->getType(); 3898 ParamLoc = PV->getLocation(); 3899 IsCRegister = 3900 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3901 } 3902 } 3903 3904 if (!SecondArgIsLastNamedArgument) 3905 Diag(TheCall->getArg(1)->getLocStart(), 3906 diag::warn_second_arg_of_va_start_not_last_named_param); 3907 else if (IsCRegister || Type->isReferenceType() || 3908 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3909 // Promotable integers are UB, but enumerations need a bit of 3910 // extra checking to see what their promotable type actually is. 3911 if (!Type->isPromotableIntegerType()) 3912 return false; 3913 if (!Type->isEnumeralType()) 3914 return true; 3915 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3916 return !(ED && 3917 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3918 }()) { 3919 unsigned Reason = 0; 3920 if (Type->isReferenceType()) Reason = 1; 3921 else if (IsCRegister) Reason = 2; 3922 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3923 Diag(ParamLoc, diag::note_parameter_type) << Type; 3924 } 3925 3926 TheCall->setType(Context.VoidTy); 3927 return false; 3928 } 3929 3930 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 3931 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3932 // const char *named_addr); 3933 3934 Expr *Func = Call->getCallee(); 3935 3936 if (Call->getNumArgs() < 3) 3937 return Diag(Call->getLocEnd(), 3938 diag::err_typecheck_call_too_few_args_at_least) 3939 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3940 3941 // Type-check the first argument normally. 3942 if (checkBuiltinArgument(*this, Call, 0)) 3943 return true; 3944 3945 // Check that the current function is variadic. 3946 if (checkVAStartIsInVariadicFunction(*this, Func)) 3947 return true; 3948 3949 // __va_start on Windows does not validate the parameter qualifiers 3950 3951 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 3952 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 3953 3954 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 3955 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 3956 3957 const QualType &ConstCharPtrTy = 3958 Context.getPointerType(Context.CharTy.withConst()); 3959 if (!Arg1Ty->isPointerType() || 3960 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 3961 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible) 3962 << Arg1->getType() << ConstCharPtrTy 3963 << 1 /* different class */ 3964 << 0 /* qualifier difference */ 3965 << 3 /* parameter mismatch */ 3966 << 2 << Arg1->getType() << ConstCharPtrTy; 3967 3968 const QualType SizeTy = Context.getSizeType(); 3969 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 3970 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible) 3971 << Arg2->getType() << SizeTy 3972 << 1 /* different class */ 3973 << 0 /* qualifier difference */ 3974 << 3 /* parameter mismatch */ 3975 << 3 << Arg2->getType() << SizeTy; 3976 3977 return false; 3978 } 3979 3980 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3981 /// friends. This is declared to take (...), so we have to check everything. 3982 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3983 if (TheCall->getNumArgs() < 2) 3984 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3985 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3986 if (TheCall->getNumArgs() > 2) 3987 return Diag(TheCall->getArg(2)->getLocStart(), 3988 diag::err_typecheck_call_too_many_args) 3989 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3990 << SourceRange(TheCall->getArg(2)->getLocStart(), 3991 (*(TheCall->arg_end()-1))->getLocEnd()); 3992 3993 ExprResult OrigArg0 = TheCall->getArg(0); 3994 ExprResult OrigArg1 = TheCall->getArg(1); 3995 3996 // Do standard promotions between the two arguments, returning their common 3997 // type. 3998 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3999 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 4000 return true; 4001 4002 // Make sure any conversions are pushed back into the call; this is 4003 // type safe since unordered compare builtins are declared as "_Bool 4004 // foo(...)". 4005 TheCall->setArg(0, OrigArg0.get()); 4006 TheCall->setArg(1, OrigArg1.get()); 4007 4008 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 4009 return false; 4010 4011 // If the common type isn't a real floating type, then the arguments were 4012 // invalid for this operation. 4013 if (Res.isNull() || !Res->isRealFloatingType()) 4014 return Diag(OrigArg0.get()->getLocStart(), 4015 diag::err_typecheck_call_invalid_ordered_compare) 4016 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 4017 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 4018 4019 return false; 4020 } 4021 4022 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 4023 /// __builtin_isnan and friends. This is declared to take (...), so we have 4024 /// to check everything. We expect the last argument to be a floating point 4025 /// value. 4026 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 4027 if (TheCall->getNumArgs() < NumArgs) 4028 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4029 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 4030 if (TheCall->getNumArgs() > NumArgs) 4031 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 4032 diag::err_typecheck_call_too_many_args) 4033 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 4034 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 4035 (*(TheCall->arg_end()-1))->getLocEnd()); 4036 4037 Expr *OrigArg = TheCall->getArg(NumArgs-1); 4038 4039 if (OrigArg->isTypeDependent()) 4040 return false; 4041 4042 // This operation requires a non-_Complex floating-point number. 4043 if (!OrigArg->getType()->isRealFloatingType()) 4044 return Diag(OrigArg->getLocStart(), 4045 diag::err_typecheck_call_invalid_unary_fp) 4046 << OrigArg->getType() << OrigArg->getSourceRange(); 4047 4048 // If this is an implicit conversion from float -> float or double, remove it. 4049 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4050 // Only remove standard FloatCasts, leaving other casts inplace 4051 if (Cast->getCastKind() == CK_FloatingCast) { 4052 Expr *CastArg = Cast->getSubExpr(); 4053 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4054 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4055 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 4056 "promotion from float to either float or double is the only expected cast here"); 4057 Cast->setSubExpr(nullptr); 4058 TheCall->setArg(NumArgs-1, CastArg); 4059 } 4060 } 4061 } 4062 4063 return false; 4064 } 4065 4066 // Customized Sema Checking for VSX builtins that have the following signature: 4067 // vector [...] builtinName(vector [...], vector [...], const int); 4068 // Which takes the same type of vectors (any legal vector type) for the first 4069 // two arguments and takes compile time constant for the third argument. 4070 // Example builtins are : 4071 // vector double vec_xxpermdi(vector double, vector double, int); 4072 // vector short vec_xxsldwi(vector short, vector short, int); 4073 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4074 unsigned ExpectedNumArgs = 3; 4075 if (TheCall->getNumArgs() < ExpectedNumArgs) 4076 return Diag(TheCall->getLocEnd(), 4077 diag::err_typecheck_call_too_few_args_at_least) 4078 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4079 << TheCall->getSourceRange(); 4080 4081 if (TheCall->getNumArgs() > ExpectedNumArgs) 4082 return Diag(TheCall->getLocEnd(), 4083 diag::err_typecheck_call_too_many_args_at_most) 4084 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4085 << TheCall->getSourceRange(); 4086 4087 // Check the third argument is a compile time constant 4088 llvm::APSInt Value; 4089 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4090 return Diag(TheCall->getLocStart(), 4091 diag::err_vsx_builtin_nonconstant_argument) 4092 << 3 /* argument index */ << TheCall->getDirectCallee() 4093 << SourceRange(TheCall->getArg(2)->getLocStart(), 4094 TheCall->getArg(2)->getLocEnd()); 4095 4096 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4097 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4098 4099 // Check the type of argument 1 and argument 2 are vectors. 4100 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4101 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4102 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4103 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4104 << TheCall->getDirectCallee() 4105 << SourceRange(TheCall->getArg(0)->getLocStart(), 4106 TheCall->getArg(1)->getLocEnd()); 4107 } 4108 4109 // Check the first two arguments are the same type. 4110 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4111 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4112 << TheCall->getDirectCallee() 4113 << SourceRange(TheCall->getArg(0)->getLocStart(), 4114 TheCall->getArg(1)->getLocEnd()); 4115 } 4116 4117 // When default clang type checking is turned off and the customized type 4118 // checking is used, the returning type of the function must be explicitly 4119 // set. Otherwise it is _Bool by default. 4120 TheCall->setType(Arg1Ty); 4121 4122 return false; 4123 } 4124 4125 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4126 // This is declared to take (...), so we have to check everything. 4127 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4128 if (TheCall->getNumArgs() < 2) 4129 return ExprError(Diag(TheCall->getLocEnd(), 4130 diag::err_typecheck_call_too_few_args_at_least) 4131 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4132 << TheCall->getSourceRange()); 4133 4134 // Determine which of the following types of shufflevector we're checking: 4135 // 1) unary, vector mask: (lhs, mask) 4136 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4137 QualType resType = TheCall->getArg(0)->getType(); 4138 unsigned numElements = 0; 4139 4140 if (!TheCall->getArg(0)->isTypeDependent() && 4141 !TheCall->getArg(1)->isTypeDependent()) { 4142 QualType LHSType = TheCall->getArg(0)->getType(); 4143 QualType RHSType = TheCall->getArg(1)->getType(); 4144 4145 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4146 return ExprError(Diag(TheCall->getLocStart(), 4147 diag::err_vec_builtin_non_vector) 4148 << TheCall->getDirectCallee() 4149 << SourceRange(TheCall->getArg(0)->getLocStart(), 4150 TheCall->getArg(1)->getLocEnd())); 4151 4152 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4153 unsigned numResElements = TheCall->getNumArgs() - 2; 4154 4155 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4156 // with mask. If so, verify that RHS is an integer vector type with the 4157 // same number of elts as lhs. 4158 if (TheCall->getNumArgs() == 2) { 4159 if (!RHSType->hasIntegerRepresentation() || 4160 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4161 return ExprError(Diag(TheCall->getLocStart(), 4162 diag::err_vec_builtin_incompatible_vector) 4163 << TheCall->getDirectCallee() 4164 << SourceRange(TheCall->getArg(1)->getLocStart(), 4165 TheCall->getArg(1)->getLocEnd())); 4166 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4167 return ExprError(Diag(TheCall->getLocStart(), 4168 diag::err_vec_builtin_incompatible_vector) 4169 << TheCall->getDirectCallee() 4170 << SourceRange(TheCall->getArg(0)->getLocStart(), 4171 TheCall->getArg(1)->getLocEnd())); 4172 } else if (numElements != numResElements) { 4173 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4174 resType = Context.getVectorType(eltType, numResElements, 4175 VectorType::GenericVector); 4176 } 4177 } 4178 4179 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4180 if (TheCall->getArg(i)->isTypeDependent() || 4181 TheCall->getArg(i)->isValueDependent()) 4182 continue; 4183 4184 llvm::APSInt Result(32); 4185 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4186 return ExprError(Diag(TheCall->getLocStart(), 4187 diag::err_shufflevector_nonconstant_argument) 4188 << TheCall->getArg(i)->getSourceRange()); 4189 4190 // Allow -1 which will be translated to undef in the IR. 4191 if (Result.isSigned() && Result.isAllOnesValue()) 4192 continue; 4193 4194 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4195 return ExprError(Diag(TheCall->getLocStart(), 4196 diag::err_shufflevector_argument_too_large) 4197 << TheCall->getArg(i)->getSourceRange()); 4198 } 4199 4200 SmallVector<Expr*, 32> exprs; 4201 4202 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4203 exprs.push_back(TheCall->getArg(i)); 4204 TheCall->setArg(i, nullptr); 4205 } 4206 4207 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4208 TheCall->getCallee()->getLocStart(), 4209 TheCall->getRParenLoc()); 4210 } 4211 4212 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4213 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4214 SourceLocation BuiltinLoc, 4215 SourceLocation RParenLoc) { 4216 ExprValueKind VK = VK_RValue; 4217 ExprObjectKind OK = OK_Ordinary; 4218 QualType DstTy = TInfo->getType(); 4219 QualType SrcTy = E->getType(); 4220 4221 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4222 return ExprError(Diag(BuiltinLoc, 4223 diag::err_convertvector_non_vector) 4224 << E->getSourceRange()); 4225 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4226 return ExprError(Diag(BuiltinLoc, 4227 diag::err_convertvector_non_vector_type)); 4228 4229 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4230 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4231 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4232 if (SrcElts != DstElts) 4233 return ExprError(Diag(BuiltinLoc, 4234 diag::err_convertvector_incompatible_vector) 4235 << E->getSourceRange()); 4236 } 4237 4238 return new (Context) 4239 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4240 } 4241 4242 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4243 // This is declared to take (const void*, ...) and can take two 4244 // optional constant int args. 4245 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4246 unsigned NumArgs = TheCall->getNumArgs(); 4247 4248 if (NumArgs > 3) 4249 return Diag(TheCall->getLocEnd(), 4250 diag::err_typecheck_call_too_many_args_at_most) 4251 << 0 /*function call*/ << 3 << NumArgs 4252 << TheCall->getSourceRange(); 4253 4254 // Argument 0 is checked for us and the remaining arguments must be 4255 // constant integers. 4256 for (unsigned i = 1; i != NumArgs; ++i) 4257 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4258 return true; 4259 4260 return false; 4261 } 4262 4263 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4264 // __assume does not evaluate its arguments, and should warn if its argument 4265 // has side effects. 4266 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4267 Expr *Arg = TheCall->getArg(0); 4268 if (Arg->isInstantiationDependent()) return false; 4269 4270 if (Arg->HasSideEffects(Context)) 4271 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4272 << Arg->getSourceRange() 4273 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4274 4275 return false; 4276 } 4277 4278 /// Handle __builtin_alloca_with_align. This is declared 4279 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4280 /// than 8. 4281 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4282 // The alignment must be a constant integer. 4283 Expr *Arg = TheCall->getArg(1); 4284 4285 // We can't check the value of a dependent argument. 4286 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4287 if (const auto *UE = 4288 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4289 if (UE->getKind() == UETT_AlignOf) 4290 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4291 << Arg->getSourceRange(); 4292 4293 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4294 4295 if (!Result.isPowerOf2()) 4296 return Diag(TheCall->getLocStart(), 4297 diag::err_alignment_not_power_of_two) 4298 << Arg->getSourceRange(); 4299 4300 if (Result < Context.getCharWidth()) 4301 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4302 << (unsigned)Context.getCharWidth() 4303 << Arg->getSourceRange(); 4304 4305 if (Result > INT32_MAX) 4306 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4307 << INT32_MAX 4308 << Arg->getSourceRange(); 4309 } 4310 4311 return false; 4312 } 4313 4314 /// Handle __builtin_assume_aligned. This is declared 4315 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4316 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4317 unsigned NumArgs = TheCall->getNumArgs(); 4318 4319 if (NumArgs > 3) 4320 return Diag(TheCall->getLocEnd(), 4321 diag::err_typecheck_call_too_many_args_at_most) 4322 << 0 /*function call*/ << 3 << NumArgs 4323 << TheCall->getSourceRange(); 4324 4325 // The alignment must be a constant integer. 4326 Expr *Arg = TheCall->getArg(1); 4327 4328 // We can't check the value of a dependent argument. 4329 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4330 llvm::APSInt Result; 4331 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4332 return true; 4333 4334 if (!Result.isPowerOf2()) 4335 return Diag(TheCall->getLocStart(), 4336 diag::err_alignment_not_power_of_two) 4337 << Arg->getSourceRange(); 4338 } 4339 4340 if (NumArgs > 2) { 4341 ExprResult Arg(TheCall->getArg(2)); 4342 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4343 Context.getSizeType(), false); 4344 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4345 if (Arg.isInvalid()) return true; 4346 TheCall->setArg(2, Arg.get()); 4347 } 4348 4349 return false; 4350 } 4351 4352 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4353 unsigned BuiltinID = 4354 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4355 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4356 4357 unsigned NumArgs = TheCall->getNumArgs(); 4358 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4359 if (NumArgs < NumRequiredArgs) { 4360 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4361 << 0 /* function call */ << NumRequiredArgs << NumArgs 4362 << TheCall->getSourceRange(); 4363 } 4364 if (NumArgs >= NumRequiredArgs + 0x100) { 4365 return Diag(TheCall->getLocEnd(), 4366 diag::err_typecheck_call_too_many_args_at_most) 4367 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4368 << TheCall->getSourceRange(); 4369 } 4370 unsigned i = 0; 4371 4372 // For formatting call, check buffer arg. 4373 if (!IsSizeCall) { 4374 ExprResult Arg(TheCall->getArg(i)); 4375 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4376 Context, Context.VoidPtrTy, false); 4377 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4378 if (Arg.isInvalid()) 4379 return true; 4380 TheCall->setArg(i, Arg.get()); 4381 i++; 4382 } 4383 4384 // Check string literal arg. 4385 unsigned FormatIdx = i; 4386 { 4387 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4388 if (Arg.isInvalid()) 4389 return true; 4390 TheCall->setArg(i, Arg.get()); 4391 i++; 4392 } 4393 4394 // Make sure variadic args are scalar. 4395 unsigned FirstDataArg = i; 4396 while (i < NumArgs) { 4397 ExprResult Arg = DefaultVariadicArgumentPromotion( 4398 TheCall->getArg(i), VariadicFunction, nullptr); 4399 if (Arg.isInvalid()) 4400 return true; 4401 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4402 if (ArgSize.getQuantity() >= 0x100) { 4403 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4404 << i << (int)ArgSize.getQuantity() << 0xff 4405 << TheCall->getSourceRange(); 4406 } 4407 TheCall->setArg(i, Arg.get()); 4408 i++; 4409 } 4410 4411 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4412 // call to avoid duplicate diagnostics. 4413 if (!IsSizeCall) { 4414 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4415 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4416 bool Success = CheckFormatArguments( 4417 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4418 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4419 CheckedVarArgs); 4420 if (!Success) 4421 return true; 4422 } 4423 4424 if (IsSizeCall) { 4425 TheCall->setType(Context.getSizeType()); 4426 } else { 4427 TheCall->setType(Context.VoidPtrTy); 4428 } 4429 return false; 4430 } 4431 4432 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4433 /// TheCall is a constant expression. 4434 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4435 llvm::APSInt &Result) { 4436 Expr *Arg = TheCall->getArg(ArgNum); 4437 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4438 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4439 4440 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4441 4442 if (!Arg->isIntegerConstantExpr(Result, Context)) 4443 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4444 << FDecl->getDeclName() << Arg->getSourceRange(); 4445 4446 return false; 4447 } 4448 4449 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4450 /// TheCall is a constant expression in the range [Low, High]. 4451 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4452 int Low, int High) { 4453 llvm::APSInt Result; 4454 4455 // We can't check the value of a dependent argument. 4456 Expr *Arg = TheCall->getArg(ArgNum); 4457 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4458 return false; 4459 4460 // Check constant-ness first. 4461 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4462 return true; 4463 4464 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4465 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4466 << Low << High << Arg->getSourceRange(); 4467 4468 return false; 4469 } 4470 4471 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4472 /// TheCall is a constant expression is a multiple of Num.. 4473 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4474 unsigned Num) { 4475 llvm::APSInt Result; 4476 4477 // We can't check the value of a dependent argument. 4478 Expr *Arg = TheCall->getArg(ArgNum); 4479 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4480 return false; 4481 4482 // Check constant-ness first. 4483 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4484 return true; 4485 4486 if (Result.getSExtValue() % Num != 0) 4487 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4488 << Num << Arg->getSourceRange(); 4489 4490 return false; 4491 } 4492 4493 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4494 /// TheCall is an ARM/AArch64 special register string literal. 4495 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4496 int ArgNum, unsigned ExpectedFieldNum, 4497 bool AllowName) { 4498 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4499 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4500 BuiltinID == ARM::BI__builtin_arm_rsr || 4501 BuiltinID == ARM::BI__builtin_arm_rsrp || 4502 BuiltinID == ARM::BI__builtin_arm_wsr || 4503 BuiltinID == ARM::BI__builtin_arm_wsrp; 4504 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4505 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4506 BuiltinID == AArch64::BI__builtin_arm_rsr || 4507 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4508 BuiltinID == AArch64::BI__builtin_arm_wsr || 4509 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4510 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4511 4512 // We can't check the value of a dependent argument. 4513 Expr *Arg = TheCall->getArg(ArgNum); 4514 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4515 return false; 4516 4517 // Check if the argument is a string literal. 4518 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4519 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4520 << Arg->getSourceRange(); 4521 4522 // Check the type of special register given. 4523 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4524 SmallVector<StringRef, 6> Fields; 4525 Reg.split(Fields, ":"); 4526 4527 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4528 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4529 << Arg->getSourceRange(); 4530 4531 // If the string is the name of a register then we cannot check that it is 4532 // valid here but if the string is of one the forms described in ACLE then we 4533 // can check that the supplied fields are integers and within the valid 4534 // ranges. 4535 if (Fields.size() > 1) { 4536 bool FiveFields = Fields.size() == 5; 4537 4538 bool ValidString = true; 4539 if (IsARMBuiltin) { 4540 ValidString &= Fields[0].startswith_lower("cp") || 4541 Fields[0].startswith_lower("p"); 4542 if (ValidString) 4543 Fields[0] = 4544 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4545 4546 ValidString &= Fields[2].startswith_lower("c"); 4547 if (ValidString) 4548 Fields[2] = Fields[2].drop_front(1); 4549 4550 if (FiveFields) { 4551 ValidString &= Fields[3].startswith_lower("c"); 4552 if (ValidString) 4553 Fields[3] = Fields[3].drop_front(1); 4554 } 4555 } 4556 4557 SmallVector<int, 5> Ranges; 4558 if (FiveFields) 4559 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4560 else 4561 Ranges.append({15, 7, 15}); 4562 4563 for (unsigned i=0; i<Fields.size(); ++i) { 4564 int IntField; 4565 ValidString &= !Fields[i].getAsInteger(10, IntField); 4566 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4567 } 4568 4569 if (!ValidString) 4570 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4571 << Arg->getSourceRange(); 4572 4573 } else if (IsAArch64Builtin && Fields.size() == 1) { 4574 // If the register name is one of those that appear in the condition below 4575 // and the special register builtin being used is one of the write builtins, 4576 // then we require that the argument provided for writing to the register 4577 // is an integer constant expression. This is because it will be lowered to 4578 // an MSR (immediate) instruction, so we need to know the immediate at 4579 // compile time. 4580 if (TheCall->getNumArgs() != 2) 4581 return false; 4582 4583 std::string RegLower = Reg.lower(); 4584 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4585 RegLower != "pan" && RegLower != "uao") 4586 return false; 4587 4588 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4589 } 4590 4591 return false; 4592 } 4593 4594 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4595 /// This checks that the target supports __builtin_longjmp and 4596 /// that val is a constant 1. 4597 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4598 if (!Context.getTargetInfo().hasSjLjLowering()) 4599 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4600 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4601 4602 Expr *Arg = TheCall->getArg(1); 4603 llvm::APSInt Result; 4604 4605 // TODO: This is less than ideal. Overload this to take a value. 4606 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4607 return true; 4608 4609 if (Result != 1) 4610 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4611 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4612 4613 return false; 4614 } 4615 4616 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4617 /// This checks that the target supports __builtin_setjmp. 4618 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4619 if (!Context.getTargetInfo().hasSjLjLowering()) 4620 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4621 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4622 return false; 4623 } 4624 4625 namespace { 4626 class UncoveredArgHandler { 4627 enum { Unknown = -1, AllCovered = -2 }; 4628 signed FirstUncoveredArg; 4629 SmallVector<const Expr *, 4> DiagnosticExprs; 4630 4631 public: 4632 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4633 4634 bool hasUncoveredArg() const { 4635 return (FirstUncoveredArg >= 0); 4636 } 4637 4638 unsigned getUncoveredArg() const { 4639 assert(hasUncoveredArg() && "no uncovered argument"); 4640 return FirstUncoveredArg; 4641 } 4642 4643 void setAllCovered() { 4644 // A string has been found with all arguments covered, so clear out 4645 // the diagnostics. 4646 DiagnosticExprs.clear(); 4647 FirstUncoveredArg = AllCovered; 4648 } 4649 4650 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4651 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4652 4653 // Don't update if a previous string covers all arguments. 4654 if (FirstUncoveredArg == AllCovered) 4655 return; 4656 4657 // UncoveredArgHandler tracks the highest uncovered argument index 4658 // and with it all the strings that match this index. 4659 if (NewFirstUncoveredArg == FirstUncoveredArg) 4660 DiagnosticExprs.push_back(StrExpr); 4661 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4662 DiagnosticExprs.clear(); 4663 DiagnosticExprs.push_back(StrExpr); 4664 FirstUncoveredArg = NewFirstUncoveredArg; 4665 } 4666 } 4667 4668 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4669 }; 4670 4671 enum StringLiteralCheckType { 4672 SLCT_NotALiteral, 4673 SLCT_UncheckedLiteral, 4674 SLCT_CheckedLiteral 4675 }; 4676 } // end anonymous namespace 4677 4678 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4679 BinaryOperatorKind BinOpKind, 4680 bool AddendIsRight) { 4681 unsigned BitWidth = Offset.getBitWidth(); 4682 unsigned AddendBitWidth = Addend.getBitWidth(); 4683 // There might be negative interim results. 4684 if (Addend.isUnsigned()) { 4685 Addend = Addend.zext(++AddendBitWidth); 4686 Addend.setIsSigned(true); 4687 } 4688 // Adjust the bit width of the APSInts. 4689 if (AddendBitWidth > BitWidth) { 4690 Offset = Offset.sext(AddendBitWidth); 4691 BitWidth = AddendBitWidth; 4692 } else if (BitWidth > AddendBitWidth) { 4693 Addend = Addend.sext(BitWidth); 4694 } 4695 4696 bool Ov = false; 4697 llvm::APSInt ResOffset = Offset; 4698 if (BinOpKind == BO_Add) 4699 ResOffset = Offset.sadd_ov(Addend, Ov); 4700 else { 4701 assert(AddendIsRight && BinOpKind == BO_Sub && 4702 "operator must be add or sub with addend on the right"); 4703 ResOffset = Offset.ssub_ov(Addend, Ov); 4704 } 4705 4706 // We add an offset to a pointer here so we should support an offset as big as 4707 // possible. 4708 if (Ov) { 4709 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4710 Offset = Offset.sext(2 * BitWidth); 4711 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4712 return; 4713 } 4714 4715 Offset = ResOffset; 4716 } 4717 4718 namespace { 4719 // This is a wrapper class around StringLiteral to support offsetted string 4720 // literals as format strings. It takes the offset into account when returning 4721 // the string and its length or the source locations to display notes correctly. 4722 class FormatStringLiteral { 4723 const StringLiteral *FExpr; 4724 int64_t Offset; 4725 4726 public: 4727 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4728 : FExpr(fexpr), Offset(Offset) {} 4729 4730 StringRef getString() const { 4731 return FExpr->getString().drop_front(Offset); 4732 } 4733 4734 unsigned getByteLength() const { 4735 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4736 } 4737 unsigned getLength() const { return FExpr->getLength() - Offset; } 4738 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4739 4740 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4741 4742 QualType getType() const { return FExpr->getType(); } 4743 4744 bool isAscii() const { return FExpr->isAscii(); } 4745 bool isWide() const { return FExpr->isWide(); } 4746 bool isUTF8() const { return FExpr->isUTF8(); } 4747 bool isUTF16() const { return FExpr->isUTF16(); } 4748 bool isUTF32() const { return FExpr->isUTF32(); } 4749 bool isPascal() const { return FExpr->isPascal(); } 4750 4751 SourceLocation getLocationOfByte( 4752 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4753 const TargetInfo &Target, unsigned *StartToken = nullptr, 4754 unsigned *StartTokenByteOffset = nullptr) const { 4755 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4756 StartToken, StartTokenByteOffset); 4757 } 4758 4759 SourceLocation getLocStart() const LLVM_READONLY { 4760 return FExpr->getLocStart().getLocWithOffset(Offset); 4761 } 4762 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4763 }; 4764 } // end anonymous namespace 4765 4766 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4767 const Expr *OrigFormatExpr, 4768 ArrayRef<const Expr *> Args, 4769 bool HasVAListArg, unsigned format_idx, 4770 unsigned firstDataArg, 4771 Sema::FormatStringType Type, 4772 bool inFunctionCall, 4773 Sema::VariadicCallType CallType, 4774 llvm::SmallBitVector &CheckedVarArgs, 4775 UncoveredArgHandler &UncoveredArg); 4776 4777 // Determine if an expression is a string literal or constant string. 4778 // If this function returns false on the arguments to a function expecting a 4779 // format string, we will usually need to emit a warning. 4780 // True string literals are then checked by CheckFormatString. 4781 static StringLiteralCheckType 4782 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4783 bool HasVAListArg, unsigned format_idx, 4784 unsigned firstDataArg, Sema::FormatStringType Type, 4785 Sema::VariadicCallType CallType, bool InFunctionCall, 4786 llvm::SmallBitVector &CheckedVarArgs, 4787 UncoveredArgHandler &UncoveredArg, 4788 llvm::APSInt Offset) { 4789 tryAgain: 4790 assert(Offset.isSigned() && "invalid offset"); 4791 4792 if (E->isTypeDependent() || E->isValueDependent()) 4793 return SLCT_NotALiteral; 4794 4795 E = E->IgnoreParenCasts(); 4796 4797 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4798 // Technically -Wformat-nonliteral does not warn about this case. 4799 // The behavior of printf and friends in this case is implementation 4800 // dependent. Ideally if the format string cannot be null then 4801 // it should have a 'nonnull' attribute in the function prototype. 4802 return SLCT_UncheckedLiteral; 4803 4804 switch (E->getStmtClass()) { 4805 case Stmt::BinaryConditionalOperatorClass: 4806 case Stmt::ConditionalOperatorClass: { 4807 // The expression is a literal if both sub-expressions were, and it was 4808 // completely checked only if both sub-expressions were checked. 4809 const AbstractConditionalOperator *C = 4810 cast<AbstractConditionalOperator>(E); 4811 4812 // Determine whether it is necessary to check both sub-expressions, for 4813 // example, because the condition expression is a constant that can be 4814 // evaluated at compile time. 4815 bool CheckLeft = true, CheckRight = true; 4816 4817 bool Cond; 4818 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4819 if (Cond) 4820 CheckRight = false; 4821 else 4822 CheckLeft = false; 4823 } 4824 4825 // We need to maintain the offsets for the right and the left hand side 4826 // separately to check if every possible indexed expression is a valid 4827 // string literal. They might have different offsets for different string 4828 // literals in the end. 4829 StringLiteralCheckType Left; 4830 if (!CheckLeft) 4831 Left = SLCT_UncheckedLiteral; 4832 else { 4833 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4834 HasVAListArg, format_idx, firstDataArg, 4835 Type, CallType, InFunctionCall, 4836 CheckedVarArgs, UncoveredArg, Offset); 4837 if (Left == SLCT_NotALiteral || !CheckRight) { 4838 return Left; 4839 } 4840 } 4841 4842 StringLiteralCheckType Right = 4843 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4844 HasVAListArg, format_idx, firstDataArg, 4845 Type, CallType, InFunctionCall, CheckedVarArgs, 4846 UncoveredArg, Offset); 4847 4848 return (CheckLeft && Left < Right) ? Left : Right; 4849 } 4850 4851 case Stmt::ImplicitCastExprClass: { 4852 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4853 goto tryAgain; 4854 } 4855 4856 case Stmt::OpaqueValueExprClass: 4857 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4858 E = src; 4859 goto tryAgain; 4860 } 4861 return SLCT_NotALiteral; 4862 4863 case Stmt::PredefinedExprClass: 4864 // While __func__, etc., are technically not string literals, they 4865 // cannot contain format specifiers and thus are not a security 4866 // liability. 4867 return SLCT_UncheckedLiteral; 4868 4869 case Stmt::DeclRefExprClass: { 4870 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4871 4872 // As an exception, do not flag errors for variables binding to 4873 // const string literals. 4874 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4875 bool isConstant = false; 4876 QualType T = DR->getType(); 4877 4878 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4879 isConstant = AT->getElementType().isConstant(S.Context); 4880 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4881 isConstant = T.isConstant(S.Context) && 4882 PT->getPointeeType().isConstant(S.Context); 4883 } else if (T->isObjCObjectPointerType()) { 4884 // In ObjC, there is usually no "const ObjectPointer" type, 4885 // so don't check if the pointee type is constant. 4886 isConstant = T.isConstant(S.Context); 4887 } 4888 4889 if (isConstant) { 4890 if (const Expr *Init = VD->getAnyInitializer()) { 4891 // Look through initializers like const char c[] = { "foo" } 4892 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4893 if (InitList->isStringLiteralInit()) 4894 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4895 } 4896 return checkFormatStringExpr(S, Init, Args, 4897 HasVAListArg, format_idx, 4898 firstDataArg, Type, CallType, 4899 /*InFunctionCall*/ false, CheckedVarArgs, 4900 UncoveredArg, Offset); 4901 } 4902 } 4903 4904 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4905 // special check to see if the format string is a function parameter 4906 // of the function calling the printf function. If the function 4907 // has an attribute indicating it is a printf-like function, then we 4908 // should suppress warnings concerning non-literals being used in a call 4909 // to a vprintf function. For example: 4910 // 4911 // void 4912 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4913 // va_list ap; 4914 // va_start(ap, fmt); 4915 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4916 // ... 4917 // } 4918 if (HasVAListArg) { 4919 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4920 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4921 int PVIndex = PV->getFunctionScopeIndex() + 1; 4922 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4923 // adjust for implicit parameter 4924 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4925 if (MD->isInstance()) 4926 ++PVIndex; 4927 // We also check if the formats are compatible. 4928 // We can't pass a 'scanf' string to a 'printf' function. 4929 if (PVIndex == PVFormat->getFormatIdx() && 4930 Type == S.GetFormatStringType(PVFormat)) 4931 return SLCT_UncheckedLiteral; 4932 } 4933 } 4934 } 4935 } 4936 } 4937 4938 return SLCT_NotALiteral; 4939 } 4940 4941 case Stmt::CallExprClass: 4942 case Stmt::CXXMemberCallExprClass: { 4943 const CallExpr *CE = cast<CallExpr>(E); 4944 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4945 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4946 unsigned ArgIndex = FA->getFormatIdx(); 4947 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4948 if (MD->isInstance()) 4949 --ArgIndex; 4950 const Expr *Arg = CE->getArg(ArgIndex - 1); 4951 4952 return checkFormatStringExpr(S, Arg, Args, 4953 HasVAListArg, format_idx, firstDataArg, 4954 Type, CallType, InFunctionCall, 4955 CheckedVarArgs, UncoveredArg, Offset); 4956 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4957 unsigned BuiltinID = FD->getBuiltinID(); 4958 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4959 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4960 const Expr *Arg = CE->getArg(0); 4961 return checkFormatStringExpr(S, Arg, Args, 4962 HasVAListArg, format_idx, 4963 firstDataArg, Type, CallType, 4964 InFunctionCall, CheckedVarArgs, 4965 UncoveredArg, Offset); 4966 } 4967 } 4968 } 4969 4970 return SLCT_NotALiteral; 4971 } 4972 case Stmt::ObjCMessageExprClass: { 4973 const auto *ME = cast<ObjCMessageExpr>(E); 4974 if (const auto *ND = ME->getMethodDecl()) { 4975 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4976 unsigned ArgIndex = FA->getFormatIdx(); 4977 const Expr *Arg = ME->getArg(ArgIndex - 1); 4978 return checkFormatStringExpr( 4979 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4980 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4981 } 4982 } 4983 4984 return SLCT_NotALiteral; 4985 } 4986 case Stmt::ObjCStringLiteralClass: 4987 case Stmt::StringLiteralClass: { 4988 const StringLiteral *StrE = nullptr; 4989 4990 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4991 StrE = ObjCFExpr->getString(); 4992 else 4993 StrE = cast<StringLiteral>(E); 4994 4995 if (StrE) { 4996 if (Offset.isNegative() || Offset > StrE->getLength()) { 4997 // TODO: It would be better to have an explicit warning for out of 4998 // bounds literals. 4999 return SLCT_NotALiteral; 5000 } 5001 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 5002 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 5003 firstDataArg, Type, InFunctionCall, CallType, 5004 CheckedVarArgs, UncoveredArg); 5005 return SLCT_CheckedLiteral; 5006 } 5007 5008 return SLCT_NotALiteral; 5009 } 5010 case Stmt::BinaryOperatorClass: { 5011 llvm::APSInt LResult; 5012 llvm::APSInt RResult; 5013 5014 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 5015 5016 // A string literal + an int offset is still a string literal. 5017 if (BinOp->isAdditiveOp()) { 5018 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 5019 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 5020 5021 if (LIsInt != RIsInt) { 5022 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 5023 5024 if (LIsInt) { 5025 if (BinOpKind == BO_Add) { 5026 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 5027 E = BinOp->getRHS(); 5028 goto tryAgain; 5029 } 5030 } else { 5031 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 5032 E = BinOp->getLHS(); 5033 goto tryAgain; 5034 } 5035 } 5036 } 5037 5038 return SLCT_NotALiteral; 5039 } 5040 case Stmt::UnaryOperatorClass: { 5041 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 5042 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 5043 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 5044 llvm::APSInt IndexResult; 5045 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5046 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5047 E = ASE->getBase(); 5048 goto tryAgain; 5049 } 5050 } 5051 5052 return SLCT_NotALiteral; 5053 } 5054 5055 default: 5056 return SLCT_NotALiteral; 5057 } 5058 } 5059 5060 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5061 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5062 .Case("scanf", FST_Scanf) 5063 .Cases("printf", "printf0", FST_Printf) 5064 .Cases("NSString", "CFString", FST_NSString) 5065 .Case("strftime", FST_Strftime) 5066 .Case("strfmon", FST_Strfmon) 5067 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5068 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5069 .Case("os_trace", FST_OSLog) 5070 .Case("os_log", FST_OSLog) 5071 .Default(FST_Unknown); 5072 } 5073 5074 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5075 /// functions) for correct use of format strings. 5076 /// Returns true if a format string has been fully checked. 5077 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5078 ArrayRef<const Expr *> Args, 5079 bool IsCXXMember, 5080 VariadicCallType CallType, 5081 SourceLocation Loc, SourceRange Range, 5082 llvm::SmallBitVector &CheckedVarArgs) { 5083 FormatStringInfo FSI; 5084 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5085 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5086 FSI.FirstDataArg, GetFormatStringType(Format), 5087 CallType, Loc, Range, CheckedVarArgs); 5088 return false; 5089 } 5090 5091 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5092 bool HasVAListArg, unsigned format_idx, 5093 unsigned firstDataArg, FormatStringType Type, 5094 VariadicCallType CallType, 5095 SourceLocation Loc, SourceRange Range, 5096 llvm::SmallBitVector &CheckedVarArgs) { 5097 // CHECK: printf/scanf-like function is called with no format string. 5098 if (format_idx >= Args.size()) { 5099 Diag(Loc, diag::warn_missing_format_string) << Range; 5100 return false; 5101 } 5102 5103 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5104 5105 // CHECK: format string is not a string literal. 5106 // 5107 // Dynamically generated format strings are difficult to 5108 // automatically vet at compile time. Requiring that format strings 5109 // are string literals: (1) permits the checking of format strings by 5110 // the compiler and thereby (2) can practically remove the source of 5111 // many format string exploits. 5112 5113 // Format string can be either ObjC string (e.g. @"%d") or 5114 // C string (e.g. "%d") 5115 // ObjC string uses the same format specifiers as C string, so we can use 5116 // the same format string checking logic for both ObjC and C strings. 5117 UncoveredArgHandler UncoveredArg; 5118 StringLiteralCheckType CT = 5119 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5120 format_idx, firstDataArg, Type, CallType, 5121 /*IsFunctionCall*/ true, CheckedVarArgs, 5122 UncoveredArg, 5123 /*no string offset*/ llvm::APSInt(64, false) = 0); 5124 5125 // Generate a diagnostic where an uncovered argument is detected. 5126 if (UncoveredArg.hasUncoveredArg()) { 5127 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5128 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5129 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5130 } 5131 5132 if (CT != SLCT_NotALiteral) 5133 // Literal format string found, check done! 5134 return CT == SLCT_CheckedLiteral; 5135 5136 // Strftime is particular as it always uses a single 'time' argument, 5137 // so it is safe to pass a non-literal string. 5138 if (Type == FST_Strftime) 5139 return false; 5140 5141 // Do not emit diag when the string param is a macro expansion and the 5142 // format is either NSString or CFString. This is a hack to prevent 5143 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5144 // which are usually used in place of NS and CF string literals. 5145 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5146 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5147 return false; 5148 5149 // If there are no arguments specified, warn with -Wformat-security, otherwise 5150 // warn only with -Wformat-nonliteral. 5151 if (Args.size() == firstDataArg) { 5152 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5153 << OrigFormatExpr->getSourceRange(); 5154 switch (Type) { 5155 default: 5156 break; 5157 case FST_Kprintf: 5158 case FST_FreeBSDKPrintf: 5159 case FST_Printf: 5160 Diag(FormatLoc, diag::note_format_security_fixit) 5161 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5162 break; 5163 case FST_NSString: 5164 Diag(FormatLoc, diag::note_format_security_fixit) 5165 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5166 break; 5167 } 5168 } else { 5169 Diag(FormatLoc, diag::warn_format_nonliteral) 5170 << OrigFormatExpr->getSourceRange(); 5171 } 5172 return false; 5173 } 5174 5175 namespace { 5176 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5177 protected: 5178 Sema &S; 5179 const FormatStringLiteral *FExpr; 5180 const Expr *OrigFormatExpr; 5181 const Sema::FormatStringType FSType; 5182 const unsigned FirstDataArg; 5183 const unsigned NumDataArgs; 5184 const char *Beg; // Start of format string. 5185 const bool HasVAListArg; 5186 ArrayRef<const Expr *> Args; 5187 unsigned FormatIdx; 5188 llvm::SmallBitVector CoveredArgs; 5189 bool usesPositionalArgs; 5190 bool atFirstArg; 5191 bool inFunctionCall; 5192 Sema::VariadicCallType CallType; 5193 llvm::SmallBitVector &CheckedVarArgs; 5194 UncoveredArgHandler &UncoveredArg; 5195 5196 public: 5197 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5198 const Expr *origFormatExpr, 5199 const Sema::FormatStringType type, unsigned firstDataArg, 5200 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5201 ArrayRef<const Expr *> Args, unsigned formatIdx, 5202 bool inFunctionCall, Sema::VariadicCallType callType, 5203 llvm::SmallBitVector &CheckedVarArgs, 5204 UncoveredArgHandler &UncoveredArg) 5205 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5206 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5207 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5208 usesPositionalArgs(false), atFirstArg(true), 5209 inFunctionCall(inFunctionCall), CallType(callType), 5210 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5211 CoveredArgs.resize(numDataArgs); 5212 CoveredArgs.reset(); 5213 } 5214 5215 void DoneProcessing(); 5216 5217 void HandleIncompleteSpecifier(const char *startSpecifier, 5218 unsigned specifierLen) override; 5219 5220 void HandleInvalidLengthModifier( 5221 const analyze_format_string::FormatSpecifier &FS, 5222 const analyze_format_string::ConversionSpecifier &CS, 5223 const char *startSpecifier, unsigned specifierLen, 5224 unsigned DiagID); 5225 5226 void HandleNonStandardLengthModifier( 5227 const analyze_format_string::FormatSpecifier &FS, 5228 const char *startSpecifier, unsigned specifierLen); 5229 5230 void HandleNonStandardConversionSpecifier( 5231 const analyze_format_string::ConversionSpecifier &CS, 5232 const char *startSpecifier, unsigned specifierLen); 5233 5234 void HandlePosition(const char *startPos, unsigned posLen) override; 5235 5236 void HandleInvalidPosition(const char *startSpecifier, 5237 unsigned specifierLen, 5238 analyze_format_string::PositionContext p) override; 5239 5240 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5241 5242 void HandleNullChar(const char *nullCharacter) override; 5243 5244 template <typename Range> 5245 static void 5246 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5247 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5248 bool IsStringLocation, Range StringRange, 5249 ArrayRef<FixItHint> Fixit = None); 5250 5251 protected: 5252 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5253 const char *startSpec, 5254 unsigned specifierLen, 5255 const char *csStart, unsigned csLen); 5256 5257 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5258 const char *startSpec, 5259 unsigned specifierLen); 5260 5261 SourceRange getFormatStringRange(); 5262 CharSourceRange getSpecifierRange(const char *startSpecifier, 5263 unsigned specifierLen); 5264 SourceLocation getLocationOfByte(const char *x); 5265 5266 const Expr *getDataArg(unsigned i) const; 5267 5268 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5269 const analyze_format_string::ConversionSpecifier &CS, 5270 const char *startSpecifier, unsigned specifierLen, 5271 unsigned argIndex); 5272 5273 template <typename Range> 5274 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5275 bool IsStringLocation, Range StringRange, 5276 ArrayRef<FixItHint> Fixit = None); 5277 }; 5278 } // end anonymous namespace 5279 5280 SourceRange CheckFormatHandler::getFormatStringRange() { 5281 return OrigFormatExpr->getSourceRange(); 5282 } 5283 5284 CharSourceRange CheckFormatHandler:: 5285 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5286 SourceLocation Start = getLocationOfByte(startSpecifier); 5287 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5288 5289 // Advance the end SourceLocation by one due to half-open ranges. 5290 End = End.getLocWithOffset(1); 5291 5292 return CharSourceRange::getCharRange(Start, End); 5293 } 5294 5295 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5296 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5297 S.getLangOpts(), S.Context.getTargetInfo()); 5298 } 5299 5300 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5301 unsigned specifierLen){ 5302 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5303 getLocationOfByte(startSpecifier), 5304 /*IsStringLocation*/true, 5305 getSpecifierRange(startSpecifier, specifierLen)); 5306 } 5307 5308 void CheckFormatHandler::HandleInvalidLengthModifier( 5309 const analyze_format_string::FormatSpecifier &FS, 5310 const analyze_format_string::ConversionSpecifier &CS, 5311 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5312 using namespace analyze_format_string; 5313 5314 const LengthModifier &LM = FS.getLengthModifier(); 5315 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5316 5317 // See if we know how to fix this length modifier. 5318 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5319 if (FixedLM) { 5320 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5321 getLocationOfByte(LM.getStart()), 5322 /*IsStringLocation*/true, 5323 getSpecifierRange(startSpecifier, specifierLen)); 5324 5325 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5326 << FixedLM->toString() 5327 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5328 5329 } else { 5330 FixItHint Hint; 5331 if (DiagID == diag::warn_format_nonsensical_length) 5332 Hint = FixItHint::CreateRemoval(LMRange); 5333 5334 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5335 getLocationOfByte(LM.getStart()), 5336 /*IsStringLocation*/true, 5337 getSpecifierRange(startSpecifier, specifierLen), 5338 Hint); 5339 } 5340 } 5341 5342 void CheckFormatHandler::HandleNonStandardLengthModifier( 5343 const analyze_format_string::FormatSpecifier &FS, 5344 const char *startSpecifier, unsigned specifierLen) { 5345 using namespace analyze_format_string; 5346 5347 const LengthModifier &LM = FS.getLengthModifier(); 5348 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5349 5350 // See if we know how to fix this length modifier. 5351 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5352 if (FixedLM) { 5353 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5354 << LM.toString() << 0, 5355 getLocationOfByte(LM.getStart()), 5356 /*IsStringLocation*/true, 5357 getSpecifierRange(startSpecifier, specifierLen)); 5358 5359 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5360 << FixedLM->toString() 5361 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5362 5363 } else { 5364 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5365 << LM.toString() << 0, 5366 getLocationOfByte(LM.getStart()), 5367 /*IsStringLocation*/true, 5368 getSpecifierRange(startSpecifier, specifierLen)); 5369 } 5370 } 5371 5372 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5373 const analyze_format_string::ConversionSpecifier &CS, 5374 const char *startSpecifier, unsigned specifierLen) { 5375 using namespace analyze_format_string; 5376 5377 // See if we know how to fix this conversion specifier. 5378 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5379 if (FixedCS) { 5380 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5381 << CS.toString() << /*conversion specifier*/1, 5382 getLocationOfByte(CS.getStart()), 5383 /*IsStringLocation*/true, 5384 getSpecifierRange(startSpecifier, specifierLen)); 5385 5386 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5387 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5388 << FixedCS->toString() 5389 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5390 } else { 5391 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5392 << CS.toString() << /*conversion specifier*/1, 5393 getLocationOfByte(CS.getStart()), 5394 /*IsStringLocation*/true, 5395 getSpecifierRange(startSpecifier, specifierLen)); 5396 } 5397 } 5398 5399 void CheckFormatHandler::HandlePosition(const char *startPos, 5400 unsigned posLen) { 5401 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5402 getLocationOfByte(startPos), 5403 /*IsStringLocation*/true, 5404 getSpecifierRange(startPos, posLen)); 5405 } 5406 5407 void 5408 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5409 analyze_format_string::PositionContext p) { 5410 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5411 << (unsigned) p, 5412 getLocationOfByte(startPos), /*IsStringLocation*/true, 5413 getSpecifierRange(startPos, posLen)); 5414 } 5415 5416 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5417 unsigned posLen) { 5418 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5419 getLocationOfByte(startPos), 5420 /*IsStringLocation*/true, 5421 getSpecifierRange(startPos, posLen)); 5422 } 5423 5424 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5425 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5426 // The presence of a null character is likely an error. 5427 EmitFormatDiagnostic( 5428 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5429 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5430 getFormatStringRange()); 5431 } 5432 } 5433 5434 // Note that this may return NULL if there was an error parsing or building 5435 // one of the argument expressions. 5436 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5437 return Args[FirstDataArg + i]; 5438 } 5439 5440 void CheckFormatHandler::DoneProcessing() { 5441 // Does the number of data arguments exceed the number of 5442 // format conversions in the format string? 5443 if (!HasVAListArg) { 5444 // Find any arguments that weren't covered. 5445 CoveredArgs.flip(); 5446 signed notCoveredArg = CoveredArgs.find_first(); 5447 if (notCoveredArg >= 0) { 5448 assert((unsigned)notCoveredArg < NumDataArgs); 5449 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5450 } else { 5451 UncoveredArg.setAllCovered(); 5452 } 5453 } 5454 } 5455 5456 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5457 const Expr *ArgExpr) { 5458 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5459 "Invalid state"); 5460 5461 if (!ArgExpr) 5462 return; 5463 5464 SourceLocation Loc = ArgExpr->getLocStart(); 5465 5466 if (S.getSourceManager().isInSystemMacro(Loc)) 5467 return; 5468 5469 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5470 for (auto E : DiagnosticExprs) 5471 PDiag << E->getSourceRange(); 5472 5473 CheckFormatHandler::EmitFormatDiagnostic( 5474 S, IsFunctionCall, DiagnosticExprs[0], 5475 PDiag, Loc, /*IsStringLocation*/false, 5476 DiagnosticExprs[0]->getSourceRange()); 5477 } 5478 5479 bool 5480 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5481 SourceLocation Loc, 5482 const char *startSpec, 5483 unsigned specifierLen, 5484 const char *csStart, 5485 unsigned csLen) { 5486 bool keepGoing = true; 5487 if (argIndex < NumDataArgs) { 5488 // Consider the argument coverered, even though the specifier doesn't 5489 // make sense. 5490 CoveredArgs.set(argIndex); 5491 } 5492 else { 5493 // If argIndex exceeds the number of data arguments we 5494 // don't issue a warning because that is just a cascade of warnings (and 5495 // they may have intended '%%' anyway). We don't want to continue processing 5496 // the format string after this point, however, as we will like just get 5497 // gibberish when trying to match arguments. 5498 keepGoing = false; 5499 } 5500 5501 StringRef Specifier(csStart, csLen); 5502 5503 // If the specifier in non-printable, it could be the first byte of a UTF-8 5504 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5505 // hex value. 5506 std::string CodePointStr; 5507 if (!llvm::sys::locale::isPrint(*csStart)) { 5508 llvm::UTF32 CodePoint; 5509 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5510 const llvm::UTF8 *E = 5511 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5512 llvm::ConversionResult Result = 5513 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5514 5515 if (Result != llvm::conversionOK) { 5516 unsigned char FirstChar = *csStart; 5517 CodePoint = (llvm::UTF32)FirstChar; 5518 } 5519 5520 llvm::raw_string_ostream OS(CodePointStr); 5521 if (CodePoint < 256) 5522 OS << "\\x" << llvm::format("%02x", CodePoint); 5523 else if (CodePoint <= 0xFFFF) 5524 OS << "\\u" << llvm::format("%04x", CodePoint); 5525 else 5526 OS << "\\U" << llvm::format("%08x", CodePoint); 5527 OS.flush(); 5528 Specifier = CodePointStr; 5529 } 5530 5531 EmitFormatDiagnostic( 5532 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5533 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5534 5535 return keepGoing; 5536 } 5537 5538 void 5539 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5540 const char *startSpec, 5541 unsigned specifierLen) { 5542 EmitFormatDiagnostic( 5543 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5544 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5545 } 5546 5547 bool 5548 CheckFormatHandler::CheckNumArgs( 5549 const analyze_format_string::FormatSpecifier &FS, 5550 const analyze_format_string::ConversionSpecifier &CS, 5551 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5552 5553 if (argIndex >= NumDataArgs) { 5554 PartialDiagnostic PDiag = FS.usesPositionalArg() 5555 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5556 << (argIndex+1) << NumDataArgs) 5557 : S.PDiag(diag::warn_printf_insufficient_data_args); 5558 EmitFormatDiagnostic( 5559 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5560 getSpecifierRange(startSpecifier, specifierLen)); 5561 5562 // Since more arguments than conversion tokens are given, by extension 5563 // all arguments are covered, so mark this as so. 5564 UncoveredArg.setAllCovered(); 5565 return false; 5566 } 5567 return true; 5568 } 5569 5570 template<typename Range> 5571 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5572 SourceLocation Loc, 5573 bool IsStringLocation, 5574 Range StringRange, 5575 ArrayRef<FixItHint> FixIt) { 5576 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5577 Loc, IsStringLocation, StringRange, FixIt); 5578 } 5579 5580 /// \brief If the format string is not within the funcion call, emit a note 5581 /// so that the function call and string are in diagnostic messages. 5582 /// 5583 /// \param InFunctionCall if true, the format string is within the function 5584 /// call and only one diagnostic message will be produced. Otherwise, an 5585 /// extra note will be emitted pointing to location of the format string. 5586 /// 5587 /// \param ArgumentExpr the expression that is passed as the format string 5588 /// argument in the function call. Used for getting locations when two 5589 /// diagnostics are emitted. 5590 /// 5591 /// \param PDiag the callee should already have provided any strings for the 5592 /// diagnostic message. This function only adds locations and fixits 5593 /// to diagnostics. 5594 /// 5595 /// \param Loc primary location for diagnostic. If two diagnostics are 5596 /// required, one will be at Loc and a new SourceLocation will be created for 5597 /// the other one. 5598 /// 5599 /// \param IsStringLocation if true, Loc points to the format string should be 5600 /// used for the note. Otherwise, Loc points to the argument list and will 5601 /// be used with PDiag. 5602 /// 5603 /// \param StringRange some or all of the string to highlight. This is 5604 /// templated so it can accept either a CharSourceRange or a SourceRange. 5605 /// 5606 /// \param FixIt optional fix it hint for the format string. 5607 template <typename Range> 5608 void CheckFormatHandler::EmitFormatDiagnostic( 5609 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5610 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5611 Range StringRange, ArrayRef<FixItHint> FixIt) { 5612 if (InFunctionCall) { 5613 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5614 D << StringRange; 5615 D << FixIt; 5616 } else { 5617 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5618 << ArgumentExpr->getSourceRange(); 5619 5620 const Sema::SemaDiagnosticBuilder &Note = 5621 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5622 diag::note_format_string_defined); 5623 5624 Note << StringRange; 5625 Note << FixIt; 5626 } 5627 } 5628 5629 //===--- CHECK: Printf format string checking ------------------------------===// 5630 5631 namespace { 5632 class CheckPrintfHandler : public CheckFormatHandler { 5633 public: 5634 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5635 const Expr *origFormatExpr, 5636 const Sema::FormatStringType type, unsigned firstDataArg, 5637 unsigned numDataArgs, bool isObjC, const char *beg, 5638 bool hasVAListArg, ArrayRef<const Expr *> Args, 5639 unsigned formatIdx, bool inFunctionCall, 5640 Sema::VariadicCallType CallType, 5641 llvm::SmallBitVector &CheckedVarArgs, 5642 UncoveredArgHandler &UncoveredArg) 5643 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5644 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5645 inFunctionCall, CallType, CheckedVarArgs, 5646 UncoveredArg) {} 5647 5648 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5649 5650 /// Returns true if '%@' specifiers are allowed in the format string. 5651 bool allowsObjCArg() const { 5652 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5653 FSType == Sema::FST_OSTrace; 5654 } 5655 5656 bool HandleInvalidPrintfConversionSpecifier( 5657 const analyze_printf::PrintfSpecifier &FS, 5658 const char *startSpecifier, 5659 unsigned specifierLen) override; 5660 5661 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5662 const char *startSpecifier, 5663 unsigned specifierLen) override; 5664 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5665 const char *StartSpecifier, 5666 unsigned SpecifierLen, 5667 const Expr *E); 5668 5669 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5670 const char *startSpecifier, unsigned specifierLen); 5671 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5672 const analyze_printf::OptionalAmount &Amt, 5673 unsigned type, 5674 const char *startSpecifier, unsigned specifierLen); 5675 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5676 const analyze_printf::OptionalFlag &flag, 5677 const char *startSpecifier, unsigned specifierLen); 5678 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5679 const analyze_printf::OptionalFlag &ignoredFlag, 5680 const analyze_printf::OptionalFlag &flag, 5681 const char *startSpecifier, unsigned specifierLen); 5682 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5683 const Expr *E); 5684 5685 void HandleEmptyObjCModifierFlag(const char *startFlag, 5686 unsigned flagLen) override; 5687 5688 void HandleInvalidObjCModifierFlag(const char *startFlag, 5689 unsigned flagLen) override; 5690 5691 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5692 const char *flagsEnd, 5693 const char *conversionPosition) 5694 override; 5695 }; 5696 } // end anonymous namespace 5697 5698 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5699 const analyze_printf::PrintfSpecifier &FS, 5700 const char *startSpecifier, 5701 unsigned specifierLen) { 5702 const analyze_printf::PrintfConversionSpecifier &CS = 5703 FS.getConversionSpecifier(); 5704 5705 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5706 getLocationOfByte(CS.getStart()), 5707 startSpecifier, specifierLen, 5708 CS.getStart(), CS.getLength()); 5709 } 5710 5711 bool CheckPrintfHandler::HandleAmount( 5712 const analyze_format_string::OptionalAmount &Amt, 5713 unsigned k, const char *startSpecifier, 5714 unsigned specifierLen) { 5715 if (Amt.hasDataArgument()) { 5716 if (!HasVAListArg) { 5717 unsigned argIndex = Amt.getArgIndex(); 5718 if (argIndex >= NumDataArgs) { 5719 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5720 << k, 5721 getLocationOfByte(Amt.getStart()), 5722 /*IsStringLocation*/true, 5723 getSpecifierRange(startSpecifier, specifierLen)); 5724 // Don't do any more checking. We will just emit 5725 // spurious errors. 5726 return false; 5727 } 5728 5729 // Type check the data argument. It should be an 'int'. 5730 // Although not in conformance with C99, we also allow the argument to be 5731 // an 'unsigned int' as that is a reasonably safe case. GCC also 5732 // doesn't emit a warning for that case. 5733 CoveredArgs.set(argIndex); 5734 const Expr *Arg = getDataArg(argIndex); 5735 if (!Arg) 5736 return false; 5737 5738 QualType T = Arg->getType(); 5739 5740 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5741 assert(AT.isValid()); 5742 5743 if (!AT.matchesType(S.Context, T)) { 5744 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5745 << k << AT.getRepresentativeTypeName(S.Context) 5746 << T << Arg->getSourceRange(), 5747 getLocationOfByte(Amt.getStart()), 5748 /*IsStringLocation*/true, 5749 getSpecifierRange(startSpecifier, specifierLen)); 5750 // Don't do any more checking. We will just emit 5751 // spurious errors. 5752 return false; 5753 } 5754 } 5755 } 5756 return true; 5757 } 5758 5759 void CheckPrintfHandler::HandleInvalidAmount( 5760 const analyze_printf::PrintfSpecifier &FS, 5761 const analyze_printf::OptionalAmount &Amt, 5762 unsigned type, 5763 const char *startSpecifier, 5764 unsigned specifierLen) { 5765 const analyze_printf::PrintfConversionSpecifier &CS = 5766 FS.getConversionSpecifier(); 5767 5768 FixItHint fixit = 5769 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5770 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5771 Amt.getConstantLength())) 5772 : FixItHint(); 5773 5774 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5775 << type << CS.toString(), 5776 getLocationOfByte(Amt.getStart()), 5777 /*IsStringLocation*/true, 5778 getSpecifierRange(startSpecifier, specifierLen), 5779 fixit); 5780 } 5781 5782 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5783 const analyze_printf::OptionalFlag &flag, 5784 const char *startSpecifier, 5785 unsigned specifierLen) { 5786 // Warn about pointless flag with a fixit removal. 5787 const analyze_printf::PrintfConversionSpecifier &CS = 5788 FS.getConversionSpecifier(); 5789 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5790 << flag.toString() << CS.toString(), 5791 getLocationOfByte(flag.getPosition()), 5792 /*IsStringLocation*/true, 5793 getSpecifierRange(startSpecifier, specifierLen), 5794 FixItHint::CreateRemoval( 5795 getSpecifierRange(flag.getPosition(), 1))); 5796 } 5797 5798 void CheckPrintfHandler::HandleIgnoredFlag( 5799 const analyze_printf::PrintfSpecifier &FS, 5800 const analyze_printf::OptionalFlag &ignoredFlag, 5801 const analyze_printf::OptionalFlag &flag, 5802 const char *startSpecifier, 5803 unsigned specifierLen) { 5804 // Warn about ignored flag with a fixit removal. 5805 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5806 << ignoredFlag.toString() << flag.toString(), 5807 getLocationOfByte(ignoredFlag.getPosition()), 5808 /*IsStringLocation*/true, 5809 getSpecifierRange(startSpecifier, specifierLen), 5810 FixItHint::CreateRemoval( 5811 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5812 } 5813 5814 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5815 // bool IsStringLocation, Range StringRange, 5816 // ArrayRef<FixItHint> Fixit = None); 5817 5818 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5819 unsigned flagLen) { 5820 // Warn about an empty flag. 5821 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5822 getLocationOfByte(startFlag), 5823 /*IsStringLocation*/true, 5824 getSpecifierRange(startFlag, flagLen)); 5825 } 5826 5827 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5828 unsigned flagLen) { 5829 // Warn about an invalid flag. 5830 auto Range = getSpecifierRange(startFlag, flagLen); 5831 StringRef flag(startFlag, flagLen); 5832 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5833 getLocationOfByte(startFlag), 5834 /*IsStringLocation*/true, 5835 Range, FixItHint::CreateRemoval(Range)); 5836 } 5837 5838 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5839 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5840 // Warn about using '[...]' without a '@' conversion. 5841 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5842 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5843 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5844 getLocationOfByte(conversionPosition), 5845 /*IsStringLocation*/true, 5846 Range, FixItHint::CreateRemoval(Range)); 5847 } 5848 5849 // Determines if the specified is a C++ class or struct containing 5850 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5851 // "c_str()"). 5852 template<typename MemberKind> 5853 static llvm::SmallPtrSet<MemberKind*, 1> 5854 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5855 const RecordType *RT = Ty->getAs<RecordType>(); 5856 llvm::SmallPtrSet<MemberKind*, 1> Results; 5857 5858 if (!RT) 5859 return Results; 5860 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5861 if (!RD || !RD->getDefinition()) 5862 return Results; 5863 5864 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5865 Sema::LookupMemberName); 5866 R.suppressDiagnostics(); 5867 5868 // We just need to include all members of the right kind turned up by the 5869 // filter, at this point. 5870 if (S.LookupQualifiedName(R, RT->getDecl())) 5871 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5872 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5873 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5874 Results.insert(FK); 5875 } 5876 return Results; 5877 } 5878 5879 /// Check if we could call '.c_str()' on an object. 5880 /// 5881 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5882 /// allow the call, or if it would be ambiguous). 5883 bool Sema::hasCStrMethod(const Expr *E) { 5884 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5885 MethodSet Results = 5886 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5887 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5888 MI != ME; ++MI) 5889 if ((*MI)->getMinRequiredArguments() == 0) 5890 return true; 5891 return false; 5892 } 5893 5894 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5895 // better diagnostic if so. AT is assumed to be valid. 5896 // Returns true when a c_str() conversion method is found. 5897 bool CheckPrintfHandler::checkForCStrMembers( 5898 const analyze_printf::ArgType &AT, const Expr *E) { 5899 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5900 5901 MethodSet Results = 5902 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5903 5904 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5905 MI != ME; ++MI) { 5906 const CXXMethodDecl *Method = *MI; 5907 if (Method->getMinRequiredArguments() == 0 && 5908 AT.matchesType(S.Context, Method->getReturnType())) { 5909 // FIXME: Suggest parens if the expression needs them. 5910 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5911 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5912 << "c_str()" 5913 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5914 return true; 5915 } 5916 } 5917 5918 return false; 5919 } 5920 5921 bool 5922 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5923 &FS, 5924 const char *startSpecifier, 5925 unsigned specifierLen) { 5926 using namespace analyze_format_string; 5927 using namespace analyze_printf; 5928 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5929 5930 if (FS.consumesDataArgument()) { 5931 if (atFirstArg) { 5932 atFirstArg = false; 5933 usesPositionalArgs = FS.usesPositionalArg(); 5934 } 5935 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5936 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5937 startSpecifier, specifierLen); 5938 return false; 5939 } 5940 } 5941 5942 // First check if the field width, precision, and conversion specifier 5943 // have matching data arguments. 5944 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5945 startSpecifier, specifierLen)) { 5946 return false; 5947 } 5948 5949 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5950 startSpecifier, specifierLen)) { 5951 return false; 5952 } 5953 5954 if (!CS.consumesDataArgument()) { 5955 // FIXME: Technically specifying a precision or field width here 5956 // makes no sense. Worth issuing a warning at some point. 5957 return true; 5958 } 5959 5960 // Consume the argument. 5961 unsigned argIndex = FS.getArgIndex(); 5962 if (argIndex < NumDataArgs) { 5963 // The check to see if the argIndex is valid will come later. 5964 // We set the bit here because we may exit early from this 5965 // function if we encounter some other error. 5966 CoveredArgs.set(argIndex); 5967 } 5968 5969 // FreeBSD kernel extensions. 5970 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5971 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5972 // We need at least two arguments. 5973 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5974 return false; 5975 5976 // Claim the second argument. 5977 CoveredArgs.set(argIndex + 1); 5978 5979 // Type check the first argument (int for %b, pointer for %D) 5980 const Expr *Ex = getDataArg(argIndex); 5981 const analyze_printf::ArgType &AT = 5982 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5983 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5984 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5985 EmitFormatDiagnostic( 5986 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5987 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5988 << false << Ex->getSourceRange(), 5989 Ex->getLocStart(), /*IsStringLocation*/false, 5990 getSpecifierRange(startSpecifier, specifierLen)); 5991 5992 // Type check the second argument (char * for both %b and %D) 5993 Ex = getDataArg(argIndex + 1); 5994 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5995 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5996 EmitFormatDiagnostic( 5997 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5998 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5999 << false << Ex->getSourceRange(), 6000 Ex->getLocStart(), /*IsStringLocation*/false, 6001 getSpecifierRange(startSpecifier, specifierLen)); 6002 6003 return true; 6004 } 6005 6006 // Check for using an Objective-C specific conversion specifier 6007 // in a non-ObjC literal. 6008 if (!allowsObjCArg() && CS.isObjCArg()) { 6009 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6010 specifierLen); 6011 } 6012 6013 // %P can only be used with os_log. 6014 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 6015 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6016 specifierLen); 6017 } 6018 6019 // %n is not allowed with os_log. 6020 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 6021 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 6022 getLocationOfByte(CS.getStart()), 6023 /*IsStringLocation*/ false, 6024 getSpecifierRange(startSpecifier, specifierLen)); 6025 6026 return true; 6027 } 6028 6029 // Only scalars are allowed for os_trace. 6030 if (FSType == Sema::FST_OSTrace && 6031 (CS.getKind() == ConversionSpecifier::PArg || 6032 CS.getKind() == ConversionSpecifier::sArg || 6033 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 6034 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6035 specifierLen); 6036 } 6037 6038 // Check for use of public/private annotation outside of os_log(). 6039 if (FSType != Sema::FST_OSLog) { 6040 if (FS.isPublic().isSet()) { 6041 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6042 << "public", 6043 getLocationOfByte(FS.isPublic().getPosition()), 6044 /*IsStringLocation*/ false, 6045 getSpecifierRange(startSpecifier, specifierLen)); 6046 } 6047 if (FS.isPrivate().isSet()) { 6048 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6049 << "private", 6050 getLocationOfByte(FS.isPrivate().getPosition()), 6051 /*IsStringLocation*/ false, 6052 getSpecifierRange(startSpecifier, specifierLen)); 6053 } 6054 } 6055 6056 // Check for invalid use of field width 6057 if (!FS.hasValidFieldWidth()) { 6058 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6059 startSpecifier, specifierLen); 6060 } 6061 6062 // Check for invalid use of precision 6063 if (!FS.hasValidPrecision()) { 6064 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6065 startSpecifier, specifierLen); 6066 } 6067 6068 // Precision is mandatory for %P specifier. 6069 if (CS.getKind() == ConversionSpecifier::PArg && 6070 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6071 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6072 getLocationOfByte(startSpecifier), 6073 /*IsStringLocation*/ false, 6074 getSpecifierRange(startSpecifier, specifierLen)); 6075 } 6076 6077 // Check each flag does not conflict with any other component. 6078 if (!FS.hasValidThousandsGroupingPrefix()) 6079 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6080 if (!FS.hasValidLeadingZeros()) 6081 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6082 if (!FS.hasValidPlusPrefix()) 6083 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6084 if (!FS.hasValidSpacePrefix()) 6085 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6086 if (!FS.hasValidAlternativeForm()) 6087 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6088 if (!FS.hasValidLeftJustified()) 6089 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6090 6091 // Check that flags are not ignored by another flag 6092 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6093 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6094 startSpecifier, specifierLen); 6095 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6096 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6097 startSpecifier, specifierLen); 6098 6099 // Check the length modifier is valid with the given conversion specifier. 6100 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6101 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6102 diag::warn_format_nonsensical_length); 6103 else if (!FS.hasStandardLengthModifier()) 6104 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6105 else if (!FS.hasStandardLengthConversionCombination()) 6106 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6107 diag::warn_format_non_standard_conversion_spec); 6108 6109 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6110 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6111 6112 // The remaining checks depend on the data arguments. 6113 if (HasVAListArg) 6114 return true; 6115 6116 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6117 return false; 6118 6119 const Expr *Arg = getDataArg(argIndex); 6120 if (!Arg) 6121 return true; 6122 6123 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6124 } 6125 6126 static bool requiresParensToAddCast(const Expr *E) { 6127 // FIXME: We should have a general way to reason about operator 6128 // precedence and whether parens are actually needed here. 6129 // Take care of a few common cases where they aren't. 6130 const Expr *Inside = E->IgnoreImpCasts(); 6131 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6132 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6133 6134 switch (Inside->getStmtClass()) { 6135 case Stmt::ArraySubscriptExprClass: 6136 case Stmt::CallExprClass: 6137 case Stmt::CharacterLiteralClass: 6138 case Stmt::CXXBoolLiteralExprClass: 6139 case Stmt::DeclRefExprClass: 6140 case Stmt::FloatingLiteralClass: 6141 case Stmt::IntegerLiteralClass: 6142 case Stmt::MemberExprClass: 6143 case Stmt::ObjCArrayLiteralClass: 6144 case Stmt::ObjCBoolLiteralExprClass: 6145 case Stmt::ObjCBoxedExprClass: 6146 case Stmt::ObjCDictionaryLiteralClass: 6147 case Stmt::ObjCEncodeExprClass: 6148 case Stmt::ObjCIvarRefExprClass: 6149 case Stmt::ObjCMessageExprClass: 6150 case Stmt::ObjCPropertyRefExprClass: 6151 case Stmt::ObjCStringLiteralClass: 6152 case Stmt::ObjCSubscriptRefExprClass: 6153 case Stmt::ParenExprClass: 6154 case Stmt::StringLiteralClass: 6155 case Stmt::UnaryOperatorClass: 6156 return false; 6157 default: 6158 return true; 6159 } 6160 } 6161 6162 static std::pair<QualType, StringRef> 6163 shouldNotPrintDirectly(const ASTContext &Context, 6164 QualType IntendedTy, 6165 const Expr *E) { 6166 // Use a 'while' to peel off layers of typedefs. 6167 QualType TyTy = IntendedTy; 6168 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6169 StringRef Name = UserTy->getDecl()->getName(); 6170 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6171 .Case("CFIndex", Context.LongTy) 6172 .Case("NSInteger", Context.LongTy) 6173 .Case("NSUInteger", Context.UnsignedLongTy) 6174 .Case("SInt32", Context.IntTy) 6175 .Case("UInt32", Context.UnsignedIntTy) 6176 .Default(QualType()); 6177 6178 if (!CastTy.isNull()) 6179 return std::make_pair(CastTy, Name); 6180 6181 TyTy = UserTy->desugar(); 6182 } 6183 6184 // Strip parens if necessary. 6185 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6186 return shouldNotPrintDirectly(Context, 6187 PE->getSubExpr()->getType(), 6188 PE->getSubExpr()); 6189 6190 // If this is a conditional expression, then its result type is constructed 6191 // via usual arithmetic conversions and thus there might be no necessary 6192 // typedef sugar there. Recurse to operands to check for NSInteger & 6193 // Co. usage condition. 6194 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6195 QualType TrueTy, FalseTy; 6196 StringRef TrueName, FalseName; 6197 6198 std::tie(TrueTy, TrueName) = 6199 shouldNotPrintDirectly(Context, 6200 CO->getTrueExpr()->getType(), 6201 CO->getTrueExpr()); 6202 std::tie(FalseTy, FalseName) = 6203 shouldNotPrintDirectly(Context, 6204 CO->getFalseExpr()->getType(), 6205 CO->getFalseExpr()); 6206 6207 if (TrueTy == FalseTy) 6208 return std::make_pair(TrueTy, TrueName); 6209 else if (TrueTy.isNull()) 6210 return std::make_pair(FalseTy, FalseName); 6211 else if (FalseTy.isNull()) 6212 return std::make_pair(TrueTy, TrueName); 6213 } 6214 6215 return std::make_pair(QualType(), StringRef()); 6216 } 6217 6218 bool 6219 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6220 const char *StartSpecifier, 6221 unsigned SpecifierLen, 6222 const Expr *E) { 6223 using namespace analyze_format_string; 6224 using namespace analyze_printf; 6225 // Now type check the data expression that matches the 6226 // format specifier. 6227 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6228 if (!AT.isValid()) 6229 return true; 6230 6231 QualType ExprTy = E->getType(); 6232 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6233 ExprTy = TET->getUnderlyingExpr()->getType(); 6234 } 6235 6236 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6237 6238 if (match == analyze_printf::ArgType::Match) { 6239 return true; 6240 } 6241 6242 // Look through argument promotions for our error message's reported type. 6243 // This includes the integral and floating promotions, but excludes array 6244 // and function pointer decay; seeing that an argument intended to be a 6245 // string has type 'char [6]' is probably more confusing than 'char *'. 6246 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6247 if (ICE->getCastKind() == CK_IntegralCast || 6248 ICE->getCastKind() == CK_FloatingCast) { 6249 E = ICE->getSubExpr(); 6250 ExprTy = E->getType(); 6251 6252 // Check if we didn't match because of an implicit cast from a 'char' 6253 // or 'short' to an 'int'. This is done because printf is a varargs 6254 // function. 6255 if (ICE->getType() == S.Context.IntTy || 6256 ICE->getType() == S.Context.UnsignedIntTy) { 6257 // All further checking is done on the subexpression. 6258 if (AT.matchesType(S.Context, ExprTy)) 6259 return true; 6260 } 6261 } 6262 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6263 // Special case for 'a', which has type 'int' in C. 6264 // Note, however, that we do /not/ want to treat multibyte constants like 6265 // 'MooV' as characters! This form is deprecated but still exists. 6266 if (ExprTy == S.Context.IntTy) 6267 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6268 ExprTy = S.Context.CharTy; 6269 } 6270 6271 // Look through enums to their underlying type. 6272 bool IsEnum = false; 6273 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6274 ExprTy = EnumTy->getDecl()->getIntegerType(); 6275 IsEnum = true; 6276 } 6277 6278 // %C in an Objective-C context prints a unichar, not a wchar_t. 6279 // If the argument is an integer of some kind, believe the %C and suggest 6280 // a cast instead of changing the conversion specifier. 6281 QualType IntendedTy = ExprTy; 6282 if (isObjCContext() && 6283 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6284 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6285 !ExprTy->isCharType()) { 6286 // 'unichar' is defined as a typedef of unsigned short, but we should 6287 // prefer using the typedef if it is visible. 6288 IntendedTy = S.Context.UnsignedShortTy; 6289 6290 // While we are here, check if the value is an IntegerLiteral that happens 6291 // to be within the valid range. 6292 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6293 const llvm::APInt &V = IL->getValue(); 6294 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6295 return true; 6296 } 6297 6298 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6299 Sema::LookupOrdinaryName); 6300 if (S.LookupName(Result, S.getCurScope())) { 6301 NamedDecl *ND = Result.getFoundDecl(); 6302 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6303 if (TD->getUnderlyingType() == IntendedTy) 6304 IntendedTy = S.Context.getTypedefType(TD); 6305 } 6306 } 6307 } 6308 6309 // Special-case some of Darwin's platform-independence types by suggesting 6310 // casts to primitive types that are known to be large enough. 6311 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6312 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6313 QualType CastTy; 6314 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6315 if (!CastTy.isNull()) { 6316 IntendedTy = CastTy; 6317 ShouldNotPrintDirectly = true; 6318 } 6319 } 6320 6321 // We may be able to offer a FixItHint if it is a supported type. 6322 PrintfSpecifier fixedFS = FS; 6323 bool success = 6324 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6325 6326 if (success) { 6327 // Get the fix string from the fixed format specifier 6328 SmallString<16> buf; 6329 llvm::raw_svector_ostream os(buf); 6330 fixedFS.toString(os); 6331 6332 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6333 6334 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6335 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6336 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6337 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6338 } 6339 // In this case, the specifier is wrong and should be changed to match 6340 // the argument. 6341 EmitFormatDiagnostic(S.PDiag(diag) 6342 << AT.getRepresentativeTypeName(S.Context) 6343 << IntendedTy << IsEnum << E->getSourceRange(), 6344 E->getLocStart(), 6345 /*IsStringLocation*/ false, SpecRange, 6346 FixItHint::CreateReplacement(SpecRange, os.str())); 6347 } else { 6348 // The canonical type for formatting this value is different from the 6349 // actual type of the expression. (This occurs, for example, with Darwin's 6350 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6351 // should be printed as 'long' for 64-bit compatibility.) 6352 // Rather than emitting a normal format/argument mismatch, we want to 6353 // add a cast to the recommended type (and correct the format string 6354 // if necessary). 6355 SmallString<16> CastBuf; 6356 llvm::raw_svector_ostream CastFix(CastBuf); 6357 CastFix << "("; 6358 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6359 CastFix << ")"; 6360 6361 SmallVector<FixItHint,4> Hints; 6362 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 6363 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6364 6365 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6366 // If there's already a cast present, just replace it. 6367 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6368 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6369 6370 } else if (!requiresParensToAddCast(E)) { 6371 // If the expression has high enough precedence, 6372 // just write the C-style cast. 6373 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6374 CastFix.str())); 6375 } else { 6376 // Otherwise, add parens around the expression as well as the cast. 6377 CastFix << "("; 6378 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6379 CastFix.str())); 6380 6381 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6382 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6383 } 6384 6385 if (ShouldNotPrintDirectly) { 6386 // The expression has a type that should not be printed directly. 6387 // We extract the name from the typedef because we don't want to show 6388 // the underlying type in the diagnostic. 6389 StringRef Name; 6390 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6391 Name = TypedefTy->getDecl()->getName(); 6392 else 6393 Name = CastTyName; 6394 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6395 << Name << IntendedTy << IsEnum 6396 << E->getSourceRange(), 6397 E->getLocStart(), /*IsStringLocation=*/false, 6398 SpecRange, Hints); 6399 } else { 6400 // In this case, the expression could be printed using a different 6401 // specifier, but we've decided that the specifier is probably correct 6402 // and we should cast instead. Just use the normal warning message. 6403 EmitFormatDiagnostic( 6404 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6405 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6406 << E->getSourceRange(), 6407 E->getLocStart(), /*IsStringLocation*/false, 6408 SpecRange, Hints); 6409 } 6410 } 6411 } else { 6412 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6413 SpecifierLen); 6414 // Since the warning for passing non-POD types to variadic functions 6415 // was deferred until now, we emit a warning for non-POD 6416 // arguments here. 6417 switch (S.isValidVarArgType(ExprTy)) { 6418 case Sema::VAK_Valid: 6419 case Sema::VAK_ValidInCXX11: { 6420 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6421 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6422 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6423 } 6424 6425 EmitFormatDiagnostic( 6426 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6427 << IsEnum << CSR << E->getSourceRange(), 6428 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6429 break; 6430 } 6431 case Sema::VAK_Undefined: 6432 case Sema::VAK_MSVCUndefined: 6433 EmitFormatDiagnostic( 6434 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6435 << S.getLangOpts().CPlusPlus11 6436 << ExprTy 6437 << CallType 6438 << AT.getRepresentativeTypeName(S.Context) 6439 << CSR 6440 << E->getSourceRange(), 6441 E->getLocStart(), /*IsStringLocation*/false, CSR); 6442 checkForCStrMembers(AT, E); 6443 break; 6444 6445 case Sema::VAK_Invalid: 6446 if (ExprTy->isObjCObjectType()) 6447 EmitFormatDiagnostic( 6448 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6449 << S.getLangOpts().CPlusPlus11 6450 << ExprTy 6451 << CallType 6452 << AT.getRepresentativeTypeName(S.Context) 6453 << CSR 6454 << E->getSourceRange(), 6455 E->getLocStart(), /*IsStringLocation*/false, CSR); 6456 else 6457 // FIXME: If this is an initializer list, suggest removing the braces 6458 // or inserting a cast to the target type. 6459 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6460 << isa<InitListExpr>(E) << ExprTy << CallType 6461 << AT.getRepresentativeTypeName(S.Context) 6462 << E->getSourceRange(); 6463 break; 6464 } 6465 6466 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6467 "format string specifier index out of range"); 6468 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6469 } 6470 6471 return true; 6472 } 6473 6474 //===--- CHECK: Scanf format string checking ------------------------------===// 6475 6476 namespace { 6477 class CheckScanfHandler : public CheckFormatHandler { 6478 public: 6479 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6480 const Expr *origFormatExpr, Sema::FormatStringType type, 6481 unsigned firstDataArg, unsigned numDataArgs, 6482 const char *beg, bool hasVAListArg, 6483 ArrayRef<const Expr *> Args, unsigned formatIdx, 6484 bool inFunctionCall, Sema::VariadicCallType CallType, 6485 llvm::SmallBitVector &CheckedVarArgs, 6486 UncoveredArgHandler &UncoveredArg) 6487 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6488 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6489 inFunctionCall, CallType, CheckedVarArgs, 6490 UncoveredArg) {} 6491 6492 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6493 const char *startSpecifier, 6494 unsigned specifierLen) override; 6495 6496 bool HandleInvalidScanfConversionSpecifier( 6497 const analyze_scanf::ScanfSpecifier &FS, 6498 const char *startSpecifier, 6499 unsigned specifierLen) override; 6500 6501 void HandleIncompleteScanList(const char *start, const char *end) override; 6502 }; 6503 } // end anonymous namespace 6504 6505 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6506 const char *end) { 6507 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6508 getLocationOfByte(end), /*IsStringLocation*/true, 6509 getSpecifierRange(start, end - start)); 6510 } 6511 6512 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6513 const analyze_scanf::ScanfSpecifier &FS, 6514 const char *startSpecifier, 6515 unsigned specifierLen) { 6516 6517 const analyze_scanf::ScanfConversionSpecifier &CS = 6518 FS.getConversionSpecifier(); 6519 6520 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6521 getLocationOfByte(CS.getStart()), 6522 startSpecifier, specifierLen, 6523 CS.getStart(), CS.getLength()); 6524 } 6525 6526 bool CheckScanfHandler::HandleScanfSpecifier( 6527 const analyze_scanf::ScanfSpecifier &FS, 6528 const char *startSpecifier, 6529 unsigned specifierLen) { 6530 using namespace analyze_scanf; 6531 using namespace analyze_format_string; 6532 6533 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6534 6535 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6536 // be used to decide if we are using positional arguments consistently. 6537 if (FS.consumesDataArgument()) { 6538 if (atFirstArg) { 6539 atFirstArg = false; 6540 usesPositionalArgs = FS.usesPositionalArg(); 6541 } 6542 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6543 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6544 startSpecifier, specifierLen); 6545 return false; 6546 } 6547 } 6548 6549 // Check if the field with is non-zero. 6550 const OptionalAmount &Amt = FS.getFieldWidth(); 6551 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6552 if (Amt.getConstantAmount() == 0) { 6553 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6554 Amt.getConstantLength()); 6555 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6556 getLocationOfByte(Amt.getStart()), 6557 /*IsStringLocation*/true, R, 6558 FixItHint::CreateRemoval(R)); 6559 } 6560 } 6561 6562 if (!FS.consumesDataArgument()) { 6563 // FIXME: Technically specifying a precision or field width here 6564 // makes no sense. Worth issuing a warning at some point. 6565 return true; 6566 } 6567 6568 // Consume the argument. 6569 unsigned argIndex = FS.getArgIndex(); 6570 if (argIndex < NumDataArgs) { 6571 // The check to see if the argIndex is valid will come later. 6572 // We set the bit here because we may exit early from this 6573 // function if we encounter some other error. 6574 CoveredArgs.set(argIndex); 6575 } 6576 6577 // Check the length modifier is valid with the given conversion specifier. 6578 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6579 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6580 diag::warn_format_nonsensical_length); 6581 else if (!FS.hasStandardLengthModifier()) 6582 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6583 else if (!FS.hasStandardLengthConversionCombination()) 6584 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6585 diag::warn_format_non_standard_conversion_spec); 6586 6587 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6588 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6589 6590 // The remaining checks depend on the data arguments. 6591 if (HasVAListArg) 6592 return true; 6593 6594 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6595 return false; 6596 6597 // Check that the argument type matches the format specifier. 6598 const Expr *Ex = getDataArg(argIndex); 6599 if (!Ex) 6600 return true; 6601 6602 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6603 6604 if (!AT.isValid()) { 6605 return true; 6606 } 6607 6608 analyze_format_string::ArgType::MatchKind match = 6609 AT.matchesType(S.Context, Ex->getType()); 6610 if (match == analyze_format_string::ArgType::Match) { 6611 return true; 6612 } 6613 6614 ScanfSpecifier fixedFS = FS; 6615 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6616 S.getLangOpts(), S.Context); 6617 6618 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6619 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6620 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6621 } 6622 6623 if (success) { 6624 // Get the fix string from the fixed format specifier. 6625 SmallString<128> buf; 6626 llvm::raw_svector_ostream os(buf); 6627 fixedFS.toString(os); 6628 6629 EmitFormatDiagnostic( 6630 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6631 << Ex->getType() << false << Ex->getSourceRange(), 6632 Ex->getLocStart(), 6633 /*IsStringLocation*/ false, 6634 getSpecifierRange(startSpecifier, specifierLen), 6635 FixItHint::CreateReplacement( 6636 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6637 } else { 6638 EmitFormatDiagnostic(S.PDiag(diag) 6639 << AT.getRepresentativeTypeName(S.Context) 6640 << Ex->getType() << false << Ex->getSourceRange(), 6641 Ex->getLocStart(), 6642 /*IsStringLocation*/ false, 6643 getSpecifierRange(startSpecifier, specifierLen)); 6644 } 6645 6646 return true; 6647 } 6648 6649 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6650 const Expr *OrigFormatExpr, 6651 ArrayRef<const Expr *> Args, 6652 bool HasVAListArg, unsigned format_idx, 6653 unsigned firstDataArg, 6654 Sema::FormatStringType Type, 6655 bool inFunctionCall, 6656 Sema::VariadicCallType CallType, 6657 llvm::SmallBitVector &CheckedVarArgs, 6658 UncoveredArgHandler &UncoveredArg) { 6659 // CHECK: is the format string a wide literal? 6660 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6661 CheckFormatHandler::EmitFormatDiagnostic( 6662 S, inFunctionCall, Args[format_idx], 6663 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6664 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6665 return; 6666 } 6667 6668 // Str - The format string. NOTE: this is NOT null-terminated! 6669 StringRef StrRef = FExpr->getString(); 6670 const char *Str = StrRef.data(); 6671 // Account for cases where the string literal is truncated in a declaration. 6672 const ConstantArrayType *T = 6673 S.Context.getAsConstantArrayType(FExpr->getType()); 6674 assert(T && "String literal not of constant array type!"); 6675 size_t TypeSize = T->getSize().getZExtValue(); 6676 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6677 const unsigned numDataArgs = Args.size() - firstDataArg; 6678 6679 // Emit a warning if the string literal is truncated and does not contain an 6680 // embedded null character. 6681 if (TypeSize <= StrRef.size() && 6682 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6683 CheckFormatHandler::EmitFormatDiagnostic( 6684 S, inFunctionCall, Args[format_idx], 6685 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6686 FExpr->getLocStart(), 6687 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6688 return; 6689 } 6690 6691 // CHECK: empty format string? 6692 if (StrLen == 0 && numDataArgs > 0) { 6693 CheckFormatHandler::EmitFormatDiagnostic( 6694 S, inFunctionCall, Args[format_idx], 6695 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6696 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6697 return; 6698 } 6699 6700 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6701 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6702 Type == Sema::FST_OSTrace) { 6703 CheckPrintfHandler H( 6704 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6705 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6706 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6707 CheckedVarArgs, UncoveredArg); 6708 6709 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6710 S.getLangOpts(), 6711 S.Context.getTargetInfo(), 6712 Type == Sema::FST_FreeBSDKPrintf)) 6713 H.DoneProcessing(); 6714 } else if (Type == Sema::FST_Scanf) { 6715 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6716 numDataArgs, Str, HasVAListArg, Args, format_idx, 6717 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6718 6719 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6720 S.getLangOpts(), 6721 S.Context.getTargetInfo())) 6722 H.DoneProcessing(); 6723 } // TODO: handle other formats 6724 } 6725 6726 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6727 // Str - The format string. NOTE: this is NOT null-terminated! 6728 StringRef StrRef = FExpr->getString(); 6729 const char *Str = StrRef.data(); 6730 // Account for cases where the string literal is truncated in a declaration. 6731 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6732 assert(T && "String literal not of constant array type!"); 6733 size_t TypeSize = T->getSize().getZExtValue(); 6734 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6735 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6736 getLangOpts(), 6737 Context.getTargetInfo()); 6738 } 6739 6740 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6741 6742 // Returns the related absolute value function that is larger, of 0 if one 6743 // does not exist. 6744 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6745 switch (AbsFunction) { 6746 default: 6747 return 0; 6748 6749 case Builtin::BI__builtin_abs: 6750 return Builtin::BI__builtin_labs; 6751 case Builtin::BI__builtin_labs: 6752 return Builtin::BI__builtin_llabs; 6753 case Builtin::BI__builtin_llabs: 6754 return 0; 6755 6756 case Builtin::BI__builtin_fabsf: 6757 return Builtin::BI__builtin_fabs; 6758 case Builtin::BI__builtin_fabs: 6759 return Builtin::BI__builtin_fabsl; 6760 case Builtin::BI__builtin_fabsl: 6761 return 0; 6762 6763 case Builtin::BI__builtin_cabsf: 6764 return Builtin::BI__builtin_cabs; 6765 case Builtin::BI__builtin_cabs: 6766 return Builtin::BI__builtin_cabsl; 6767 case Builtin::BI__builtin_cabsl: 6768 return 0; 6769 6770 case Builtin::BIabs: 6771 return Builtin::BIlabs; 6772 case Builtin::BIlabs: 6773 return Builtin::BIllabs; 6774 case Builtin::BIllabs: 6775 return 0; 6776 6777 case Builtin::BIfabsf: 6778 return Builtin::BIfabs; 6779 case Builtin::BIfabs: 6780 return Builtin::BIfabsl; 6781 case Builtin::BIfabsl: 6782 return 0; 6783 6784 case Builtin::BIcabsf: 6785 return Builtin::BIcabs; 6786 case Builtin::BIcabs: 6787 return Builtin::BIcabsl; 6788 case Builtin::BIcabsl: 6789 return 0; 6790 } 6791 } 6792 6793 // Returns the argument type of the absolute value function. 6794 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6795 unsigned AbsType) { 6796 if (AbsType == 0) 6797 return QualType(); 6798 6799 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6800 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6801 if (Error != ASTContext::GE_None) 6802 return QualType(); 6803 6804 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6805 if (!FT) 6806 return QualType(); 6807 6808 if (FT->getNumParams() != 1) 6809 return QualType(); 6810 6811 return FT->getParamType(0); 6812 } 6813 6814 // Returns the best absolute value function, or zero, based on type and 6815 // current absolute value function. 6816 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6817 unsigned AbsFunctionKind) { 6818 unsigned BestKind = 0; 6819 uint64_t ArgSize = Context.getTypeSize(ArgType); 6820 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6821 Kind = getLargerAbsoluteValueFunction(Kind)) { 6822 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6823 if (Context.getTypeSize(ParamType) >= ArgSize) { 6824 if (BestKind == 0) 6825 BestKind = Kind; 6826 else if (Context.hasSameType(ParamType, ArgType)) { 6827 BestKind = Kind; 6828 break; 6829 } 6830 } 6831 } 6832 return BestKind; 6833 } 6834 6835 enum AbsoluteValueKind { 6836 AVK_Integer, 6837 AVK_Floating, 6838 AVK_Complex 6839 }; 6840 6841 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6842 if (T->isIntegralOrEnumerationType()) 6843 return AVK_Integer; 6844 if (T->isRealFloatingType()) 6845 return AVK_Floating; 6846 if (T->isAnyComplexType()) 6847 return AVK_Complex; 6848 6849 llvm_unreachable("Type not integer, floating, or complex"); 6850 } 6851 6852 // Changes the absolute value function to a different type. Preserves whether 6853 // the function is a builtin. 6854 static unsigned changeAbsFunction(unsigned AbsKind, 6855 AbsoluteValueKind ValueKind) { 6856 switch (ValueKind) { 6857 case AVK_Integer: 6858 switch (AbsKind) { 6859 default: 6860 return 0; 6861 case Builtin::BI__builtin_fabsf: 6862 case Builtin::BI__builtin_fabs: 6863 case Builtin::BI__builtin_fabsl: 6864 case Builtin::BI__builtin_cabsf: 6865 case Builtin::BI__builtin_cabs: 6866 case Builtin::BI__builtin_cabsl: 6867 return Builtin::BI__builtin_abs; 6868 case Builtin::BIfabsf: 6869 case Builtin::BIfabs: 6870 case Builtin::BIfabsl: 6871 case Builtin::BIcabsf: 6872 case Builtin::BIcabs: 6873 case Builtin::BIcabsl: 6874 return Builtin::BIabs; 6875 } 6876 case AVK_Floating: 6877 switch (AbsKind) { 6878 default: 6879 return 0; 6880 case Builtin::BI__builtin_abs: 6881 case Builtin::BI__builtin_labs: 6882 case Builtin::BI__builtin_llabs: 6883 case Builtin::BI__builtin_cabsf: 6884 case Builtin::BI__builtin_cabs: 6885 case Builtin::BI__builtin_cabsl: 6886 return Builtin::BI__builtin_fabsf; 6887 case Builtin::BIabs: 6888 case Builtin::BIlabs: 6889 case Builtin::BIllabs: 6890 case Builtin::BIcabsf: 6891 case Builtin::BIcabs: 6892 case Builtin::BIcabsl: 6893 return Builtin::BIfabsf; 6894 } 6895 case AVK_Complex: 6896 switch (AbsKind) { 6897 default: 6898 return 0; 6899 case Builtin::BI__builtin_abs: 6900 case Builtin::BI__builtin_labs: 6901 case Builtin::BI__builtin_llabs: 6902 case Builtin::BI__builtin_fabsf: 6903 case Builtin::BI__builtin_fabs: 6904 case Builtin::BI__builtin_fabsl: 6905 return Builtin::BI__builtin_cabsf; 6906 case Builtin::BIabs: 6907 case Builtin::BIlabs: 6908 case Builtin::BIllabs: 6909 case Builtin::BIfabsf: 6910 case Builtin::BIfabs: 6911 case Builtin::BIfabsl: 6912 return Builtin::BIcabsf; 6913 } 6914 } 6915 llvm_unreachable("Unable to convert function"); 6916 } 6917 6918 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6919 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6920 if (!FnInfo) 6921 return 0; 6922 6923 switch (FDecl->getBuiltinID()) { 6924 default: 6925 return 0; 6926 case Builtin::BI__builtin_abs: 6927 case Builtin::BI__builtin_fabs: 6928 case Builtin::BI__builtin_fabsf: 6929 case Builtin::BI__builtin_fabsl: 6930 case Builtin::BI__builtin_labs: 6931 case Builtin::BI__builtin_llabs: 6932 case Builtin::BI__builtin_cabs: 6933 case Builtin::BI__builtin_cabsf: 6934 case Builtin::BI__builtin_cabsl: 6935 case Builtin::BIabs: 6936 case Builtin::BIlabs: 6937 case Builtin::BIllabs: 6938 case Builtin::BIfabs: 6939 case Builtin::BIfabsf: 6940 case Builtin::BIfabsl: 6941 case Builtin::BIcabs: 6942 case Builtin::BIcabsf: 6943 case Builtin::BIcabsl: 6944 return FDecl->getBuiltinID(); 6945 } 6946 llvm_unreachable("Unknown Builtin type"); 6947 } 6948 6949 // If the replacement is valid, emit a note with replacement function. 6950 // Additionally, suggest including the proper header if not already included. 6951 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6952 unsigned AbsKind, QualType ArgType) { 6953 bool EmitHeaderHint = true; 6954 const char *HeaderName = nullptr; 6955 const char *FunctionName = nullptr; 6956 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6957 FunctionName = "std::abs"; 6958 if (ArgType->isIntegralOrEnumerationType()) { 6959 HeaderName = "cstdlib"; 6960 } else if (ArgType->isRealFloatingType()) { 6961 HeaderName = "cmath"; 6962 } else { 6963 llvm_unreachable("Invalid Type"); 6964 } 6965 6966 // Lookup all std::abs 6967 if (NamespaceDecl *Std = S.getStdNamespace()) { 6968 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6969 R.suppressDiagnostics(); 6970 S.LookupQualifiedName(R, Std); 6971 6972 for (const auto *I : R) { 6973 const FunctionDecl *FDecl = nullptr; 6974 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6975 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6976 } else { 6977 FDecl = dyn_cast<FunctionDecl>(I); 6978 } 6979 if (!FDecl) 6980 continue; 6981 6982 // Found std::abs(), check that they are the right ones. 6983 if (FDecl->getNumParams() != 1) 6984 continue; 6985 6986 // Check that the parameter type can handle the argument. 6987 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6988 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6989 S.Context.getTypeSize(ArgType) <= 6990 S.Context.getTypeSize(ParamType)) { 6991 // Found a function, don't need the header hint. 6992 EmitHeaderHint = false; 6993 break; 6994 } 6995 } 6996 } 6997 } else { 6998 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6999 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 7000 7001 if (HeaderName) { 7002 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 7003 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 7004 R.suppressDiagnostics(); 7005 S.LookupName(R, S.getCurScope()); 7006 7007 if (R.isSingleResult()) { 7008 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 7009 if (FD && FD->getBuiltinID() == AbsKind) { 7010 EmitHeaderHint = false; 7011 } else { 7012 return; 7013 } 7014 } else if (!R.empty()) { 7015 return; 7016 } 7017 } 7018 } 7019 7020 S.Diag(Loc, diag::note_replace_abs_function) 7021 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 7022 7023 if (!HeaderName) 7024 return; 7025 7026 if (!EmitHeaderHint) 7027 return; 7028 7029 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 7030 << FunctionName; 7031 } 7032 7033 template <std::size_t StrLen> 7034 static bool IsStdFunction(const FunctionDecl *FDecl, 7035 const char (&Str)[StrLen]) { 7036 if (!FDecl) 7037 return false; 7038 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 7039 return false; 7040 if (!FDecl->isInStdNamespace()) 7041 return false; 7042 7043 return true; 7044 } 7045 7046 // Warn when using the wrong abs() function. 7047 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7048 const FunctionDecl *FDecl) { 7049 if (Call->getNumArgs() != 1) 7050 return; 7051 7052 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7053 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7054 if (AbsKind == 0 && !IsStdAbs) 7055 return; 7056 7057 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7058 QualType ParamType = Call->getArg(0)->getType(); 7059 7060 // Unsigned types cannot be negative. Suggest removing the absolute value 7061 // function call. 7062 if (ArgType->isUnsignedIntegerType()) { 7063 const char *FunctionName = 7064 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7065 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7066 Diag(Call->getExprLoc(), diag::note_remove_abs) 7067 << FunctionName 7068 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7069 return; 7070 } 7071 7072 // Taking the absolute value of a pointer is very suspicious, they probably 7073 // wanted to index into an array, dereference a pointer, call a function, etc. 7074 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7075 unsigned DiagType = 0; 7076 if (ArgType->isFunctionType()) 7077 DiagType = 1; 7078 else if (ArgType->isArrayType()) 7079 DiagType = 2; 7080 7081 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7082 return; 7083 } 7084 7085 // std::abs has overloads which prevent most of the absolute value problems 7086 // from occurring. 7087 if (IsStdAbs) 7088 return; 7089 7090 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7091 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7092 7093 // The argument and parameter are the same kind. Check if they are the right 7094 // size. 7095 if (ArgValueKind == ParamValueKind) { 7096 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7097 return; 7098 7099 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7100 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7101 << FDecl << ArgType << ParamType; 7102 7103 if (NewAbsKind == 0) 7104 return; 7105 7106 emitReplacement(*this, Call->getExprLoc(), 7107 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7108 return; 7109 } 7110 7111 // ArgValueKind != ParamValueKind 7112 // The wrong type of absolute value function was used. Attempt to find the 7113 // proper one. 7114 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7115 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7116 if (NewAbsKind == 0) 7117 return; 7118 7119 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7120 << FDecl << ParamValueKind << ArgValueKind; 7121 7122 emitReplacement(*this, Call->getExprLoc(), 7123 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7124 } 7125 7126 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7127 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7128 const FunctionDecl *FDecl) { 7129 if (!Call || !FDecl) return; 7130 7131 // Ignore template specializations and macros. 7132 if (inTemplateInstantiation()) return; 7133 if (Call->getExprLoc().isMacroID()) return; 7134 7135 // Only care about the one template argument, two function parameter std::max 7136 if (Call->getNumArgs() != 2) return; 7137 if (!IsStdFunction(FDecl, "max")) return; 7138 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7139 if (!ArgList) return; 7140 if (ArgList->size() != 1) return; 7141 7142 // Check that template type argument is unsigned integer. 7143 const auto& TA = ArgList->get(0); 7144 if (TA.getKind() != TemplateArgument::Type) return; 7145 QualType ArgType = TA.getAsType(); 7146 if (!ArgType->isUnsignedIntegerType()) return; 7147 7148 // See if either argument is a literal zero. 7149 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7150 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7151 if (!MTE) return false; 7152 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7153 if (!Num) return false; 7154 if (Num->getValue() != 0) return false; 7155 return true; 7156 }; 7157 7158 const Expr *FirstArg = Call->getArg(0); 7159 const Expr *SecondArg = Call->getArg(1); 7160 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7161 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7162 7163 // Only warn when exactly one argument is zero. 7164 if (IsFirstArgZero == IsSecondArgZero) return; 7165 7166 SourceRange FirstRange = FirstArg->getSourceRange(); 7167 SourceRange SecondRange = SecondArg->getSourceRange(); 7168 7169 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7170 7171 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7172 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7173 7174 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7175 SourceRange RemovalRange; 7176 if (IsFirstArgZero) { 7177 RemovalRange = SourceRange(FirstRange.getBegin(), 7178 SecondRange.getBegin().getLocWithOffset(-1)); 7179 } else { 7180 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7181 SecondRange.getEnd()); 7182 } 7183 7184 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7185 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7186 << FixItHint::CreateRemoval(RemovalRange); 7187 } 7188 7189 //===--- CHECK: Standard memory functions ---------------------------------===// 7190 7191 /// \brief Takes the expression passed to the size_t parameter of functions 7192 /// such as memcmp, strncat, etc and warns if it's a comparison. 7193 /// 7194 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7195 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7196 IdentifierInfo *FnName, 7197 SourceLocation FnLoc, 7198 SourceLocation RParenLoc) { 7199 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7200 if (!Size) 7201 return false; 7202 7203 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 7204 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 7205 return false; 7206 7207 SourceRange SizeRange = Size->getSourceRange(); 7208 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7209 << SizeRange << FnName; 7210 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7211 << FnName << FixItHint::CreateInsertion( 7212 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7213 << FixItHint::CreateRemoval(RParenLoc); 7214 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7215 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7216 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7217 ")"); 7218 7219 return true; 7220 } 7221 7222 /// \brief Determine whether the given type is or contains a dynamic class type 7223 /// (e.g., whether it has a vtable). 7224 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7225 bool &IsContained) { 7226 // Look through array types while ignoring qualifiers. 7227 const Type *Ty = T->getBaseElementTypeUnsafe(); 7228 IsContained = false; 7229 7230 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7231 RD = RD ? RD->getDefinition() : nullptr; 7232 if (!RD || RD->isInvalidDecl()) 7233 return nullptr; 7234 7235 if (RD->isDynamicClass()) 7236 return RD; 7237 7238 // Check all the fields. If any bases were dynamic, the class is dynamic. 7239 // It's impossible for a class to transitively contain itself by value, so 7240 // infinite recursion is impossible. 7241 for (auto *FD : RD->fields()) { 7242 bool SubContained; 7243 if (const CXXRecordDecl *ContainedRD = 7244 getContainedDynamicClass(FD->getType(), SubContained)) { 7245 IsContained = true; 7246 return ContainedRD; 7247 } 7248 } 7249 7250 return nullptr; 7251 } 7252 7253 /// \brief If E is a sizeof expression, returns its argument expression, 7254 /// otherwise returns NULL. 7255 static const Expr *getSizeOfExprArg(const Expr *E) { 7256 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7257 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7258 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 7259 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7260 7261 return nullptr; 7262 } 7263 7264 /// \brief If E is a sizeof expression, returns its argument type. 7265 static QualType getSizeOfArgType(const Expr *E) { 7266 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7267 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7268 if (SizeOf->getKind() == clang::UETT_SizeOf) 7269 return SizeOf->getTypeOfArgument(); 7270 7271 return QualType(); 7272 } 7273 7274 /// \brief Check for dangerous or invalid arguments to memset(). 7275 /// 7276 /// This issues warnings on known problematic, dangerous or unspecified 7277 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7278 /// function calls. 7279 /// 7280 /// \param Call The call expression to diagnose. 7281 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7282 unsigned BId, 7283 IdentifierInfo *FnName) { 7284 assert(BId != 0); 7285 7286 // It is possible to have a non-standard definition of memset. Validate 7287 // we have enough arguments, and if not, abort further checking. 7288 unsigned ExpectedNumArgs = 7289 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7290 if (Call->getNumArgs() < ExpectedNumArgs) 7291 return; 7292 7293 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7294 BId == Builtin::BIstrndup ? 1 : 2); 7295 unsigned LenArg = 7296 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7297 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7298 7299 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7300 Call->getLocStart(), Call->getRParenLoc())) 7301 return; 7302 7303 // We have special checking when the length is a sizeof expression. 7304 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7305 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7306 llvm::FoldingSetNodeID SizeOfArgID; 7307 7308 // Although widely used, 'bzero' is not a standard function. Be more strict 7309 // with the argument types before allowing diagnostics and only allow the 7310 // form bzero(ptr, sizeof(...)). 7311 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7312 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7313 return; 7314 7315 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7316 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7317 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7318 7319 QualType DestTy = Dest->getType(); 7320 QualType PointeeTy; 7321 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7322 PointeeTy = DestPtrTy->getPointeeType(); 7323 7324 // Never warn about void type pointers. This can be used to suppress 7325 // false positives. 7326 if (PointeeTy->isVoidType()) 7327 continue; 7328 7329 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7330 // actually comparing the expressions for equality. Because computing the 7331 // expression IDs can be expensive, we only do this if the diagnostic is 7332 // enabled. 7333 if (SizeOfArg && 7334 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7335 SizeOfArg->getExprLoc())) { 7336 // We only compute IDs for expressions if the warning is enabled, and 7337 // cache the sizeof arg's ID. 7338 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7339 SizeOfArg->Profile(SizeOfArgID, Context, true); 7340 llvm::FoldingSetNodeID DestID; 7341 Dest->Profile(DestID, Context, true); 7342 if (DestID == SizeOfArgID) { 7343 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7344 // over sizeof(src) as well. 7345 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7346 StringRef ReadableName = FnName->getName(); 7347 7348 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7349 if (UnaryOp->getOpcode() == UO_AddrOf) 7350 ActionIdx = 1; // If its an address-of operator, just remove it. 7351 if (!PointeeTy->isIncompleteType() && 7352 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7353 ActionIdx = 2; // If the pointee's size is sizeof(char), 7354 // suggest an explicit length. 7355 7356 // If the function is defined as a builtin macro, do not show macro 7357 // expansion. 7358 SourceLocation SL = SizeOfArg->getExprLoc(); 7359 SourceRange DSR = Dest->getSourceRange(); 7360 SourceRange SSR = SizeOfArg->getSourceRange(); 7361 SourceManager &SM = getSourceManager(); 7362 7363 if (SM.isMacroArgExpansion(SL)) { 7364 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7365 SL = SM.getSpellingLoc(SL); 7366 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7367 SM.getSpellingLoc(DSR.getEnd())); 7368 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7369 SM.getSpellingLoc(SSR.getEnd())); 7370 } 7371 7372 DiagRuntimeBehavior(SL, SizeOfArg, 7373 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7374 << ReadableName 7375 << PointeeTy 7376 << DestTy 7377 << DSR 7378 << SSR); 7379 DiagRuntimeBehavior(SL, SizeOfArg, 7380 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7381 << ActionIdx 7382 << SSR); 7383 7384 break; 7385 } 7386 } 7387 7388 // Also check for cases where the sizeof argument is the exact same 7389 // type as the memory argument, and where it points to a user-defined 7390 // record type. 7391 if (SizeOfArgTy != QualType()) { 7392 if (PointeeTy->isRecordType() && 7393 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7394 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7395 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7396 << FnName << SizeOfArgTy << ArgIdx 7397 << PointeeTy << Dest->getSourceRange() 7398 << LenExpr->getSourceRange()); 7399 break; 7400 } 7401 } 7402 } else if (DestTy->isArrayType()) { 7403 PointeeTy = DestTy; 7404 } 7405 7406 if (PointeeTy == QualType()) 7407 continue; 7408 7409 // Always complain about dynamic classes. 7410 bool IsContained; 7411 if (const CXXRecordDecl *ContainedRD = 7412 getContainedDynamicClass(PointeeTy, IsContained)) { 7413 7414 unsigned OperationType = 0; 7415 // "overwritten" if we're warning about the destination for any call 7416 // but memcmp; otherwise a verb appropriate to the call. 7417 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7418 if (BId == Builtin::BImemcpy) 7419 OperationType = 1; 7420 else if(BId == Builtin::BImemmove) 7421 OperationType = 2; 7422 else if (BId == Builtin::BImemcmp) 7423 OperationType = 3; 7424 } 7425 7426 DiagRuntimeBehavior( 7427 Dest->getExprLoc(), Dest, 7428 PDiag(diag::warn_dyn_class_memaccess) 7429 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7430 << FnName << IsContained << ContainedRD << OperationType 7431 << Call->getCallee()->getSourceRange()); 7432 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7433 BId != Builtin::BImemset) 7434 DiagRuntimeBehavior( 7435 Dest->getExprLoc(), Dest, 7436 PDiag(diag::warn_arc_object_memaccess) 7437 << ArgIdx << FnName << PointeeTy 7438 << Call->getCallee()->getSourceRange()); 7439 else 7440 continue; 7441 7442 DiagRuntimeBehavior( 7443 Dest->getExprLoc(), Dest, 7444 PDiag(diag::note_bad_memaccess_silence) 7445 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7446 break; 7447 } 7448 } 7449 7450 // A little helper routine: ignore addition and subtraction of integer literals. 7451 // This intentionally does not ignore all integer constant expressions because 7452 // we don't want to remove sizeof(). 7453 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7454 Ex = Ex->IgnoreParenCasts(); 7455 7456 for (;;) { 7457 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7458 if (!BO || !BO->isAdditiveOp()) 7459 break; 7460 7461 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7462 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7463 7464 if (isa<IntegerLiteral>(RHS)) 7465 Ex = LHS; 7466 else if (isa<IntegerLiteral>(LHS)) 7467 Ex = RHS; 7468 else 7469 break; 7470 } 7471 7472 return Ex; 7473 } 7474 7475 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7476 ASTContext &Context) { 7477 // Only handle constant-sized or VLAs, but not flexible members. 7478 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7479 // Only issue the FIXIT for arrays of size > 1. 7480 if (CAT->getSize().getSExtValue() <= 1) 7481 return false; 7482 } else if (!Ty->isVariableArrayType()) { 7483 return false; 7484 } 7485 return true; 7486 } 7487 7488 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7489 // be the size of the source, instead of the destination. 7490 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7491 IdentifierInfo *FnName) { 7492 7493 // Don't crash if the user has the wrong number of arguments 7494 unsigned NumArgs = Call->getNumArgs(); 7495 if ((NumArgs != 3) && (NumArgs != 4)) 7496 return; 7497 7498 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7499 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7500 const Expr *CompareWithSrc = nullptr; 7501 7502 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7503 Call->getLocStart(), Call->getRParenLoc())) 7504 return; 7505 7506 // Look for 'strlcpy(dst, x, sizeof(x))' 7507 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7508 CompareWithSrc = Ex; 7509 else { 7510 // Look for 'strlcpy(dst, x, strlen(x))' 7511 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7512 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7513 SizeCall->getNumArgs() == 1) 7514 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7515 } 7516 } 7517 7518 if (!CompareWithSrc) 7519 return; 7520 7521 // Determine if the argument to sizeof/strlen is equal to the source 7522 // argument. In principle there's all kinds of things you could do 7523 // here, for instance creating an == expression and evaluating it with 7524 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7525 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7526 if (!SrcArgDRE) 7527 return; 7528 7529 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7530 if (!CompareWithSrcDRE || 7531 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7532 return; 7533 7534 const Expr *OriginalSizeArg = Call->getArg(2); 7535 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7536 << OriginalSizeArg->getSourceRange() << FnName; 7537 7538 // Output a FIXIT hint if the destination is an array (rather than a 7539 // pointer to an array). This could be enhanced to handle some 7540 // pointers if we know the actual size, like if DstArg is 'array+2' 7541 // we could say 'sizeof(array)-2'. 7542 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7543 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7544 return; 7545 7546 SmallString<128> sizeString; 7547 llvm::raw_svector_ostream OS(sizeString); 7548 OS << "sizeof("; 7549 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7550 OS << ")"; 7551 7552 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7553 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7554 OS.str()); 7555 } 7556 7557 /// Check if two expressions refer to the same declaration. 7558 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7559 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7560 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7561 return D1->getDecl() == D2->getDecl(); 7562 return false; 7563 } 7564 7565 static const Expr *getStrlenExprArg(const Expr *E) { 7566 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7567 const FunctionDecl *FD = CE->getDirectCallee(); 7568 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7569 return nullptr; 7570 return CE->getArg(0)->IgnoreParenCasts(); 7571 } 7572 return nullptr; 7573 } 7574 7575 // Warn on anti-patterns as the 'size' argument to strncat. 7576 // The correct size argument should look like following: 7577 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7578 void Sema::CheckStrncatArguments(const CallExpr *CE, 7579 IdentifierInfo *FnName) { 7580 // Don't crash if the user has the wrong number of arguments. 7581 if (CE->getNumArgs() < 3) 7582 return; 7583 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7584 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7585 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7586 7587 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7588 CE->getRParenLoc())) 7589 return; 7590 7591 // Identify common expressions, which are wrongly used as the size argument 7592 // to strncat and may lead to buffer overflows. 7593 unsigned PatternType = 0; 7594 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7595 // - sizeof(dst) 7596 if (referToTheSameDecl(SizeOfArg, DstArg)) 7597 PatternType = 1; 7598 // - sizeof(src) 7599 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7600 PatternType = 2; 7601 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7602 if (BE->getOpcode() == BO_Sub) { 7603 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7604 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7605 // - sizeof(dst) - strlen(dst) 7606 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7607 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7608 PatternType = 1; 7609 // - sizeof(src) - (anything) 7610 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7611 PatternType = 2; 7612 } 7613 } 7614 7615 if (PatternType == 0) 7616 return; 7617 7618 // Generate the diagnostic. 7619 SourceLocation SL = LenArg->getLocStart(); 7620 SourceRange SR = LenArg->getSourceRange(); 7621 SourceManager &SM = getSourceManager(); 7622 7623 // If the function is defined as a builtin macro, do not show macro expansion. 7624 if (SM.isMacroArgExpansion(SL)) { 7625 SL = SM.getSpellingLoc(SL); 7626 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7627 SM.getSpellingLoc(SR.getEnd())); 7628 } 7629 7630 // Check if the destination is an array (rather than a pointer to an array). 7631 QualType DstTy = DstArg->getType(); 7632 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7633 Context); 7634 if (!isKnownSizeArray) { 7635 if (PatternType == 1) 7636 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7637 else 7638 Diag(SL, diag::warn_strncat_src_size) << SR; 7639 return; 7640 } 7641 7642 if (PatternType == 1) 7643 Diag(SL, diag::warn_strncat_large_size) << SR; 7644 else 7645 Diag(SL, diag::warn_strncat_src_size) << SR; 7646 7647 SmallString<128> sizeString; 7648 llvm::raw_svector_ostream OS(sizeString); 7649 OS << "sizeof("; 7650 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7651 OS << ") - "; 7652 OS << "strlen("; 7653 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7654 OS << ") - 1"; 7655 7656 Diag(SL, diag::note_strncat_wrong_size) 7657 << FixItHint::CreateReplacement(SR, OS.str()); 7658 } 7659 7660 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7661 7662 static const Expr *EvalVal(const Expr *E, 7663 SmallVectorImpl<const DeclRefExpr *> &refVars, 7664 const Decl *ParentDecl); 7665 static const Expr *EvalAddr(const Expr *E, 7666 SmallVectorImpl<const DeclRefExpr *> &refVars, 7667 const Decl *ParentDecl); 7668 7669 /// CheckReturnStackAddr - Check if a return statement returns the address 7670 /// of a stack variable. 7671 static void 7672 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7673 SourceLocation ReturnLoc) { 7674 7675 const Expr *stackE = nullptr; 7676 SmallVector<const DeclRefExpr *, 8> refVars; 7677 7678 // Perform checking for returned stack addresses, local blocks, 7679 // label addresses or references to temporaries. 7680 if (lhsType->isPointerType() || 7681 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7682 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7683 } else if (lhsType->isReferenceType()) { 7684 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7685 } 7686 7687 if (!stackE) 7688 return; // Nothing suspicious was found. 7689 7690 // Parameters are initialized in the calling scope, so taking the address 7691 // of a parameter reference doesn't need a warning. 7692 for (auto *DRE : refVars) 7693 if (isa<ParmVarDecl>(DRE->getDecl())) 7694 return; 7695 7696 SourceLocation diagLoc; 7697 SourceRange diagRange; 7698 if (refVars.empty()) { 7699 diagLoc = stackE->getLocStart(); 7700 diagRange = stackE->getSourceRange(); 7701 } else { 7702 // We followed through a reference variable. 'stackE' contains the 7703 // problematic expression but we will warn at the return statement pointing 7704 // at the reference variable. We will later display the "trail" of 7705 // reference variables using notes. 7706 diagLoc = refVars[0]->getLocStart(); 7707 diagRange = refVars[0]->getSourceRange(); 7708 } 7709 7710 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7711 // address of local var 7712 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7713 << DR->getDecl()->getDeclName() << diagRange; 7714 } else if (isa<BlockExpr>(stackE)) { // local block. 7715 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7716 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7717 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7718 } else { // local temporary. 7719 // If there is an LValue->RValue conversion, then the value of the 7720 // reference type is used, not the reference. 7721 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7722 if (ICE->getCastKind() == CK_LValueToRValue) { 7723 return; 7724 } 7725 } 7726 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7727 << lhsType->isReferenceType() << diagRange; 7728 } 7729 7730 // Display the "trail" of reference variables that we followed until we 7731 // found the problematic expression using notes. 7732 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7733 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7734 // If this var binds to another reference var, show the range of the next 7735 // var, otherwise the var binds to the problematic expression, in which case 7736 // show the range of the expression. 7737 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7738 : stackE->getSourceRange(); 7739 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7740 << VD->getDeclName() << range; 7741 } 7742 } 7743 7744 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7745 /// check if the expression in a return statement evaluates to an address 7746 /// to a location on the stack, a local block, an address of a label, or a 7747 /// reference to local temporary. The recursion is used to traverse the 7748 /// AST of the return expression, with recursion backtracking when we 7749 /// encounter a subexpression that (1) clearly does not lead to one of the 7750 /// above problematic expressions (2) is something we cannot determine leads to 7751 /// a problematic expression based on such local checking. 7752 /// 7753 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7754 /// the expression that they point to. Such variables are added to the 7755 /// 'refVars' vector so that we know what the reference variable "trail" was. 7756 /// 7757 /// EvalAddr processes expressions that are pointers that are used as 7758 /// references (and not L-values). EvalVal handles all other values. 7759 /// At the base case of the recursion is a check for the above problematic 7760 /// expressions. 7761 /// 7762 /// This implementation handles: 7763 /// 7764 /// * pointer-to-pointer casts 7765 /// * implicit conversions from array references to pointers 7766 /// * taking the address of fields 7767 /// * arbitrary interplay between "&" and "*" operators 7768 /// * pointer arithmetic from an address of a stack variable 7769 /// * taking the address of an array element where the array is on the stack 7770 static const Expr *EvalAddr(const Expr *E, 7771 SmallVectorImpl<const DeclRefExpr *> &refVars, 7772 const Decl *ParentDecl) { 7773 if (E->isTypeDependent()) 7774 return nullptr; 7775 7776 // We should only be called for evaluating pointer expressions. 7777 assert((E->getType()->isAnyPointerType() || 7778 E->getType()->isBlockPointerType() || 7779 E->getType()->isObjCQualifiedIdType()) && 7780 "EvalAddr only works on pointers"); 7781 7782 E = E->IgnoreParens(); 7783 7784 // Our "symbolic interpreter" is just a dispatch off the currently 7785 // viewed AST node. We then recursively traverse the AST by calling 7786 // EvalAddr and EvalVal appropriately. 7787 switch (E->getStmtClass()) { 7788 case Stmt::DeclRefExprClass: { 7789 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7790 7791 // If we leave the immediate function, the lifetime isn't about to end. 7792 if (DR->refersToEnclosingVariableOrCapture()) 7793 return nullptr; 7794 7795 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7796 // If this is a reference variable, follow through to the expression that 7797 // it points to. 7798 if (V->hasLocalStorage() && 7799 V->getType()->isReferenceType() && V->hasInit()) { 7800 // Add the reference variable to the "trail". 7801 refVars.push_back(DR); 7802 return EvalAddr(V->getInit(), refVars, ParentDecl); 7803 } 7804 7805 return nullptr; 7806 } 7807 7808 case Stmt::UnaryOperatorClass: { 7809 // The only unary operator that make sense to handle here 7810 // is AddrOf. All others don't make sense as pointers. 7811 const UnaryOperator *U = cast<UnaryOperator>(E); 7812 7813 if (U->getOpcode() == UO_AddrOf) 7814 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7815 return nullptr; 7816 } 7817 7818 case Stmt::BinaryOperatorClass: { 7819 // Handle pointer arithmetic. All other binary operators are not valid 7820 // in this context. 7821 const BinaryOperator *B = cast<BinaryOperator>(E); 7822 BinaryOperatorKind op = B->getOpcode(); 7823 7824 if (op != BO_Add && op != BO_Sub) 7825 return nullptr; 7826 7827 const Expr *Base = B->getLHS(); 7828 7829 // Determine which argument is the real pointer base. It could be 7830 // the RHS argument instead of the LHS. 7831 if (!Base->getType()->isPointerType()) 7832 Base = B->getRHS(); 7833 7834 assert(Base->getType()->isPointerType()); 7835 return EvalAddr(Base, refVars, ParentDecl); 7836 } 7837 7838 // For conditional operators we need to see if either the LHS or RHS are 7839 // valid DeclRefExpr*s. If one of them is valid, we return it. 7840 case Stmt::ConditionalOperatorClass: { 7841 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7842 7843 // Handle the GNU extension for missing LHS. 7844 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7845 if (const Expr *LHSExpr = C->getLHS()) { 7846 // In C++, we can have a throw-expression, which has 'void' type. 7847 if (!LHSExpr->getType()->isVoidType()) 7848 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7849 return LHS; 7850 } 7851 7852 // In C++, we can have a throw-expression, which has 'void' type. 7853 if (C->getRHS()->getType()->isVoidType()) 7854 return nullptr; 7855 7856 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7857 } 7858 7859 case Stmt::BlockExprClass: 7860 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7861 return E; // local block. 7862 return nullptr; 7863 7864 case Stmt::AddrLabelExprClass: 7865 return E; // address of label. 7866 7867 case Stmt::ExprWithCleanupsClass: 7868 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7869 ParentDecl); 7870 7871 // For casts, we need to handle conversions from arrays to 7872 // pointer values, and pointer-to-pointer conversions. 7873 case Stmt::ImplicitCastExprClass: 7874 case Stmt::CStyleCastExprClass: 7875 case Stmt::CXXFunctionalCastExprClass: 7876 case Stmt::ObjCBridgedCastExprClass: 7877 case Stmt::CXXStaticCastExprClass: 7878 case Stmt::CXXDynamicCastExprClass: 7879 case Stmt::CXXConstCastExprClass: 7880 case Stmt::CXXReinterpretCastExprClass: { 7881 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7882 switch (cast<CastExpr>(E)->getCastKind()) { 7883 case CK_LValueToRValue: 7884 case CK_NoOp: 7885 case CK_BaseToDerived: 7886 case CK_DerivedToBase: 7887 case CK_UncheckedDerivedToBase: 7888 case CK_Dynamic: 7889 case CK_CPointerToObjCPointerCast: 7890 case CK_BlockPointerToObjCPointerCast: 7891 case CK_AnyPointerToBlockPointerCast: 7892 return EvalAddr(SubExpr, refVars, ParentDecl); 7893 7894 case CK_ArrayToPointerDecay: 7895 return EvalVal(SubExpr, refVars, ParentDecl); 7896 7897 case CK_BitCast: 7898 if (SubExpr->getType()->isAnyPointerType() || 7899 SubExpr->getType()->isBlockPointerType() || 7900 SubExpr->getType()->isObjCQualifiedIdType()) 7901 return EvalAddr(SubExpr, refVars, ParentDecl); 7902 else 7903 return nullptr; 7904 7905 default: 7906 return nullptr; 7907 } 7908 } 7909 7910 case Stmt::MaterializeTemporaryExprClass: 7911 if (const Expr *Result = 7912 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7913 refVars, ParentDecl)) 7914 return Result; 7915 return E; 7916 7917 // Everything else: we simply don't reason about them. 7918 default: 7919 return nullptr; 7920 } 7921 } 7922 7923 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7924 /// See the comments for EvalAddr for more details. 7925 static const Expr *EvalVal(const Expr *E, 7926 SmallVectorImpl<const DeclRefExpr *> &refVars, 7927 const Decl *ParentDecl) { 7928 do { 7929 // We should only be called for evaluating non-pointer expressions, or 7930 // expressions with a pointer type that are not used as references but 7931 // instead 7932 // are l-values (e.g., DeclRefExpr with a pointer type). 7933 7934 // Our "symbolic interpreter" is just a dispatch off the currently 7935 // viewed AST node. We then recursively traverse the AST by calling 7936 // EvalAddr and EvalVal appropriately. 7937 7938 E = E->IgnoreParens(); 7939 switch (E->getStmtClass()) { 7940 case Stmt::ImplicitCastExprClass: { 7941 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7942 if (IE->getValueKind() == VK_LValue) { 7943 E = IE->getSubExpr(); 7944 continue; 7945 } 7946 return nullptr; 7947 } 7948 7949 case Stmt::ExprWithCleanupsClass: 7950 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7951 ParentDecl); 7952 7953 case Stmt::DeclRefExprClass: { 7954 // When we hit a DeclRefExpr we are looking at code that refers to a 7955 // variable's name. If it's not a reference variable we check if it has 7956 // local storage within the function, and if so, return the expression. 7957 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7958 7959 // If we leave the immediate function, the lifetime isn't about to end. 7960 if (DR->refersToEnclosingVariableOrCapture()) 7961 return nullptr; 7962 7963 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7964 // Check if it refers to itself, e.g. "int& i = i;". 7965 if (V == ParentDecl) 7966 return DR; 7967 7968 if (V->hasLocalStorage()) { 7969 if (!V->getType()->isReferenceType()) 7970 return DR; 7971 7972 // Reference variable, follow through to the expression that 7973 // it points to. 7974 if (V->hasInit()) { 7975 // Add the reference variable to the "trail". 7976 refVars.push_back(DR); 7977 return EvalVal(V->getInit(), refVars, V); 7978 } 7979 } 7980 } 7981 7982 return nullptr; 7983 } 7984 7985 case Stmt::UnaryOperatorClass: { 7986 // The only unary operator that make sense to handle here 7987 // is Deref. All others don't resolve to a "name." This includes 7988 // handling all sorts of rvalues passed to a unary operator. 7989 const UnaryOperator *U = cast<UnaryOperator>(E); 7990 7991 if (U->getOpcode() == UO_Deref) 7992 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7993 7994 return nullptr; 7995 } 7996 7997 case Stmt::ArraySubscriptExprClass: { 7998 // Array subscripts are potential references to data on the stack. We 7999 // retrieve the DeclRefExpr* for the array variable if it indeed 8000 // has local storage. 8001 const auto *ASE = cast<ArraySubscriptExpr>(E); 8002 if (ASE->isTypeDependent()) 8003 return nullptr; 8004 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 8005 } 8006 8007 case Stmt::OMPArraySectionExprClass: { 8008 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 8009 ParentDecl); 8010 } 8011 8012 case Stmt::ConditionalOperatorClass: { 8013 // For conditional operators we need to see if either the LHS or RHS are 8014 // non-NULL Expr's. If one is non-NULL, we return it. 8015 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8016 8017 // Handle the GNU extension for missing LHS. 8018 if (const Expr *LHSExpr = C->getLHS()) { 8019 // In C++, we can have a throw-expression, which has 'void' type. 8020 if (!LHSExpr->getType()->isVoidType()) 8021 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 8022 return LHS; 8023 } 8024 8025 // In C++, we can have a throw-expression, which has 'void' type. 8026 if (C->getRHS()->getType()->isVoidType()) 8027 return nullptr; 8028 8029 return EvalVal(C->getRHS(), refVars, ParentDecl); 8030 } 8031 8032 // Accesses to members are potential references to data on the stack. 8033 case Stmt::MemberExprClass: { 8034 const MemberExpr *M = cast<MemberExpr>(E); 8035 8036 // Check for indirect access. We only want direct field accesses. 8037 if (M->isArrow()) 8038 return nullptr; 8039 8040 // Check whether the member type is itself a reference, in which case 8041 // we're not going to refer to the member, but to what the member refers 8042 // to. 8043 if (M->getMemberDecl()->getType()->isReferenceType()) 8044 return nullptr; 8045 8046 return EvalVal(M->getBase(), refVars, ParentDecl); 8047 } 8048 8049 case Stmt::MaterializeTemporaryExprClass: 8050 if (const Expr *Result = 8051 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8052 refVars, ParentDecl)) 8053 return Result; 8054 return E; 8055 8056 default: 8057 // Check that we don't return or take the address of a reference to a 8058 // temporary. This is only useful in C++. 8059 if (!E->isTypeDependent() && E->isRValue()) 8060 return E; 8061 8062 // Everything else: we simply don't reason about them. 8063 return nullptr; 8064 } 8065 } while (true); 8066 } 8067 8068 void 8069 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8070 SourceLocation ReturnLoc, 8071 bool isObjCMethod, 8072 const AttrVec *Attrs, 8073 const FunctionDecl *FD) { 8074 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8075 8076 // Check if the return value is null but should not be. 8077 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8078 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8079 CheckNonNullExpr(*this, RetValExp)) 8080 Diag(ReturnLoc, diag::warn_null_ret) 8081 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8082 8083 // C++11 [basic.stc.dynamic.allocation]p4: 8084 // If an allocation function declared with a non-throwing 8085 // exception-specification fails to allocate storage, it shall return 8086 // a null pointer. Any other allocation function that fails to allocate 8087 // storage shall indicate failure only by throwing an exception [...] 8088 if (FD) { 8089 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8090 if (Op == OO_New || Op == OO_Array_New) { 8091 const FunctionProtoType *Proto 8092 = FD->getType()->castAs<FunctionProtoType>(); 8093 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 8094 CheckNonNullExpr(*this, RetValExp)) 8095 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8096 << FD << getLangOpts().CPlusPlus11; 8097 } 8098 } 8099 } 8100 8101 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8102 8103 /// Check for comparisons of floating point operands using != and ==. 8104 /// Issue a warning if these are no self-comparisons, as they are not likely 8105 /// to do what the programmer intended. 8106 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8107 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8108 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8109 8110 // Special case: check for x == x (which is OK). 8111 // Do not emit warnings for such cases. 8112 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8113 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8114 if (DRL->getDecl() == DRR->getDecl()) 8115 return; 8116 8117 // Special case: check for comparisons against literals that can be exactly 8118 // represented by APFloat. In such cases, do not emit a warning. This 8119 // is a heuristic: often comparison against such literals are used to 8120 // detect if a value in a variable has not changed. This clearly can 8121 // lead to false negatives. 8122 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8123 if (FLL->isExact()) 8124 return; 8125 } else 8126 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8127 if (FLR->isExact()) 8128 return; 8129 8130 // Check for comparisons with builtin types. 8131 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8132 if (CL->getBuiltinCallee()) 8133 return; 8134 8135 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8136 if (CR->getBuiltinCallee()) 8137 return; 8138 8139 // Emit the diagnostic. 8140 Diag(Loc, diag::warn_floatingpoint_eq) 8141 << LHS->getSourceRange() << RHS->getSourceRange(); 8142 } 8143 8144 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8145 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8146 8147 namespace { 8148 8149 /// Structure recording the 'active' range of an integer-valued 8150 /// expression. 8151 struct IntRange { 8152 /// The number of bits active in the int. 8153 unsigned Width; 8154 8155 /// True if the int is known not to have negative values. 8156 bool NonNegative; 8157 8158 IntRange(unsigned Width, bool NonNegative) 8159 : Width(Width), NonNegative(NonNegative) 8160 {} 8161 8162 /// Returns the range of the bool type. 8163 static IntRange forBoolType() { 8164 return IntRange(1, true); 8165 } 8166 8167 /// Returns the range of an opaque value of the given integral type. 8168 static IntRange forValueOfType(ASTContext &C, QualType T) { 8169 return forValueOfCanonicalType(C, 8170 T->getCanonicalTypeInternal().getTypePtr()); 8171 } 8172 8173 /// Returns the range of an opaque value of a canonical integral type. 8174 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8175 assert(T->isCanonicalUnqualified()); 8176 8177 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8178 T = VT->getElementType().getTypePtr(); 8179 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8180 T = CT->getElementType().getTypePtr(); 8181 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8182 T = AT->getValueType().getTypePtr(); 8183 8184 // For enum types, use the known bit width of the enumerators. 8185 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8186 EnumDecl *Enum = ET->getDecl(); 8187 // In C++11, enums without definitions can have an explicitly specified 8188 // underlying type. Use this type to compute the range. 8189 if (!Enum->isCompleteDefinition()) 8190 return IntRange(C.getIntWidth(QualType(T, 0)), 8191 !ET->isSignedIntegerOrEnumerationType()); 8192 8193 unsigned NumPositive = Enum->getNumPositiveBits(); 8194 unsigned NumNegative = Enum->getNumNegativeBits(); 8195 8196 if (NumNegative == 0) 8197 return IntRange(NumPositive, true/*NonNegative*/); 8198 else 8199 return IntRange(std::max(NumPositive + 1, NumNegative), 8200 false/*NonNegative*/); 8201 } 8202 8203 const BuiltinType *BT = cast<BuiltinType>(T); 8204 assert(BT->isInteger()); 8205 8206 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8207 } 8208 8209 /// Returns the "target" range of a canonical integral type, i.e. 8210 /// the range of values expressible in the type. 8211 /// 8212 /// This matches forValueOfCanonicalType except that enums have the 8213 /// full range of their type, not the range of their enumerators. 8214 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8215 assert(T->isCanonicalUnqualified()); 8216 8217 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8218 T = VT->getElementType().getTypePtr(); 8219 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8220 T = CT->getElementType().getTypePtr(); 8221 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8222 T = AT->getValueType().getTypePtr(); 8223 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8224 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8225 8226 const BuiltinType *BT = cast<BuiltinType>(T); 8227 assert(BT->isInteger()); 8228 8229 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8230 } 8231 8232 /// Returns the supremum of two ranges: i.e. their conservative merge. 8233 static IntRange join(IntRange L, IntRange R) { 8234 return IntRange(std::max(L.Width, R.Width), 8235 L.NonNegative && R.NonNegative); 8236 } 8237 8238 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8239 static IntRange meet(IntRange L, IntRange R) { 8240 return IntRange(std::min(L.Width, R.Width), 8241 L.NonNegative || R.NonNegative); 8242 } 8243 }; 8244 8245 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 8246 if (value.isSigned() && value.isNegative()) 8247 return IntRange(value.getMinSignedBits(), false); 8248 8249 if (value.getBitWidth() > MaxWidth) 8250 value = value.trunc(MaxWidth); 8251 8252 // isNonNegative() just checks the sign bit without considering 8253 // signedness. 8254 return IntRange(value.getActiveBits(), true); 8255 } 8256 8257 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8258 unsigned MaxWidth) { 8259 if (result.isInt()) 8260 return GetValueRange(C, result.getInt(), MaxWidth); 8261 8262 if (result.isVector()) { 8263 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8264 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8265 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8266 R = IntRange::join(R, El); 8267 } 8268 return R; 8269 } 8270 8271 if (result.isComplexInt()) { 8272 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8273 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8274 return IntRange::join(R, I); 8275 } 8276 8277 // This can happen with lossless casts to intptr_t of "based" lvalues. 8278 // Assume it might use arbitrary bits. 8279 // FIXME: The only reason we need to pass the type in here is to get 8280 // the sign right on this one case. It would be nice if APValue 8281 // preserved this. 8282 assert(result.isLValue() || result.isAddrLabelDiff()); 8283 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8284 } 8285 8286 QualType GetExprType(const Expr *E) { 8287 QualType Ty = E->getType(); 8288 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8289 Ty = AtomicRHS->getValueType(); 8290 return Ty; 8291 } 8292 8293 /// Pseudo-evaluate the given integer expression, estimating the 8294 /// range of values it might take. 8295 /// 8296 /// \param MaxWidth - the width to which the value will be truncated 8297 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8298 E = E->IgnoreParens(); 8299 8300 // Try a full evaluation first. 8301 Expr::EvalResult result; 8302 if (E->EvaluateAsRValue(result, C)) 8303 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8304 8305 // I think we only want to look through implicit casts here; if the 8306 // user has an explicit widening cast, we should treat the value as 8307 // being of the new, wider type. 8308 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8309 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8310 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8311 8312 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8313 8314 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8315 CE->getCastKind() == CK_BooleanToSignedIntegral; 8316 8317 // Assume that non-integer casts can span the full range of the type. 8318 if (!isIntegerCast) 8319 return OutputTypeRange; 8320 8321 IntRange SubRange 8322 = GetExprRange(C, CE->getSubExpr(), 8323 std::min(MaxWidth, OutputTypeRange.Width)); 8324 8325 // Bail out if the subexpr's range is as wide as the cast type. 8326 if (SubRange.Width >= OutputTypeRange.Width) 8327 return OutputTypeRange; 8328 8329 // Otherwise, we take the smaller width, and we're non-negative if 8330 // either the output type or the subexpr is. 8331 return IntRange(SubRange.Width, 8332 SubRange.NonNegative || OutputTypeRange.NonNegative); 8333 } 8334 8335 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8336 // If we can fold the condition, just take that operand. 8337 bool CondResult; 8338 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8339 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8340 : CO->getFalseExpr(), 8341 MaxWidth); 8342 8343 // Otherwise, conservatively merge. 8344 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8345 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8346 return IntRange::join(L, R); 8347 } 8348 8349 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8350 switch (BO->getOpcode()) { 8351 8352 // Boolean-valued operations are single-bit and positive. 8353 case BO_LAnd: 8354 case BO_LOr: 8355 case BO_LT: 8356 case BO_GT: 8357 case BO_LE: 8358 case BO_GE: 8359 case BO_EQ: 8360 case BO_NE: 8361 return IntRange::forBoolType(); 8362 8363 // The type of the assignments is the type of the LHS, so the RHS 8364 // is not necessarily the same type. 8365 case BO_MulAssign: 8366 case BO_DivAssign: 8367 case BO_RemAssign: 8368 case BO_AddAssign: 8369 case BO_SubAssign: 8370 case BO_XorAssign: 8371 case BO_OrAssign: 8372 // TODO: bitfields? 8373 return IntRange::forValueOfType(C, GetExprType(E)); 8374 8375 // Simple assignments just pass through the RHS, which will have 8376 // been coerced to the LHS type. 8377 case BO_Assign: 8378 // TODO: bitfields? 8379 return GetExprRange(C, BO->getRHS(), MaxWidth); 8380 8381 // Operations with opaque sources are black-listed. 8382 case BO_PtrMemD: 8383 case BO_PtrMemI: 8384 return IntRange::forValueOfType(C, GetExprType(E)); 8385 8386 // Bitwise-and uses the *infinum* of the two source ranges. 8387 case BO_And: 8388 case BO_AndAssign: 8389 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8390 GetExprRange(C, BO->getRHS(), MaxWidth)); 8391 8392 // Left shift gets black-listed based on a judgement call. 8393 case BO_Shl: 8394 // ...except that we want to treat '1 << (blah)' as logically 8395 // positive. It's an important idiom. 8396 if (IntegerLiteral *I 8397 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8398 if (I->getValue() == 1) { 8399 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8400 return IntRange(R.Width, /*NonNegative*/ true); 8401 } 8402 } 8403 // fallthrough 8404 8405 case BO_ShlAssign: 8406 return IntRange::forValueOfType(C, GetExprType(E)); 8407 8408 // Right shift by a constant can narrow its left argument. 8409 case BO_Shr: 8410 case BO_ShrAssign: { 8411 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8412 8413 // If the shift amount is a positive constant, drop the width by 8414 // that much. 8415 llvm::APSInt shift; 8416 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8417 shift.isNonNegative()) { 8418 unsigned zext = shift.getZExtValue(); 8419 if (zext >= L.Width) 8420 L.Width = (L.NonNegative ? 0 : 1); 8421 else 8422 L.Width -= zext; 8423 } 8424 8425 return L; 8426 } 8427 8428 // Comma acts as its right operand. 8429 case BO_Comma: 8430 return GetExprRange(C, BO->getRHS(), MaxWidth); 8431 8432 // Black-list pointer subtractions. 8433 case BO_Sub: 8434 if (BO->getLHS()->getType()->isPointerType()) 8435 return IntRange::forValueOfType(C, GetExprType(E)); 8436 break; 8437 8438 // The width of a division result is mostly determined by the size 8439 // of the LHS. 8440 case BO_Div: { 8441 // Don't 'pre-truncate' the operands. 8442 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8443 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8444 8445 // If the divisor is constant, use that. 8446 llvm::APSInt divisor; 8447 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8448 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8449 if (log2 >= L.Width) 8450 L.Width = (L.NonNegative ? 0 : 1); 8451 else 8452 L.Width = std::min(L.Width - log2, MaxWidth); 8453 return L; 8454 } 8455 8456 // Otherwise, just use the LHS's width. 8457 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8458 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8459 } 8460 8461 // The result of a remainder can't be larger than the result of 8462 // either side. 8463 case BO_Rem: { 8464 // Don't 'pre-truncate' the operands. 8465 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8466 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8467 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8468 8469 IntRange meet = IntRange::meet(L, R); 8470 meet.Width = std::min(meet.Width, MaxWidth); 8471 return meet; 8472 } 8473 8474 // The default behavior is okay for these. 8475 case BO_Mul: 8476 case BO_Add: 8477 case BO_Xor: 8478 case BO_Or: 8479 break; 8480 } 8481 8482 // The default case is to treat the operation as if it were closed 8483 // on the narrowest type that encompasses both operands. 8484 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8485 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8486 return IntRange::join(L, R); 8487 } 8488 8489 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8490 switch (UO->getOpcode()) { 8491 // Boolean-valued operations are white-listed. 8492 case UO_LNot: 8493 return IntRange::forBoolType(); 8494 8495 // Operations with opaque sources are black-listed. 8496 case UO_Deref: 8497 case UO_AddrOf: // should be impossible 8498 return IntRange::forValueOfType(C, GetExprType(E)); 8499 8500 default: 8501 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8502 } 8503 } 8504 8505 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8506 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8507 8508 if (const auto *BitField = E->getSourceBitField()) 8509 return IntRange(BitField->getBitWidthValue(C), 8510 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8511 8512 return IntRange::forValueOfType(C, GetExprType(E)); 8513 } 8514 8515 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8516 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8517 } 8518 8519 /// Checks whether the given value, which currently has the given 8520 /// source semantics, has the same value when coerced through the 8521 /// target semantics. 8522 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8523 const llvm::fltSemantics &Src, 8524 const llvm::fltSemantics &Tgt) { 8525 llvm::APFloat truncated = value; 8526 8527 bool ignored; 8528 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8529 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8530 8531 return truncated.bitwiseIsEqual(value); 8532 } 8533 8534 /// Checks whether the given value, which currently has the given 8535 /// source semantics, has the same value when coerced through the 8536 /// target semantics. 8537 /// 8538 /// The value might be a vector of floats (or a complex number). 8539 bool IsSameFloatAfterCast(const APValue &value, 8540 const llvm::fltSemantics &Src, 8541 const llvm::fltSemantics &Tgt) { 8542 if (value.isFloat()) 8543 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8544 8545 if (value.isVector()) { 8546 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8547 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8548 return false; 8549 return true; 8550 } 8551 8552 assert(value.isComplexFloat()); 8553 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8554 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8555 } 8556 8557 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8558 8559 bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 8560 // Suppress cases where we are comparing against an enum constant. 8561 if (const DeclRefExpr *DR = 8562 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8563 if (isa<EnumConstantDecl>(DR->getDecl())) 8564 return true; 8565 8566 // Suppress cases where the '0' value is expanded from a macro. 8567 if (E->getLocStart().isMacroID()) 8568 return true; 8569 8570 return false; 8571 } 8572 8573 bool isNonBooleanIntegerValue(Expr *E) { 8574 return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType(); 8575 } 8576 8577 bool isNonBooleanUnsignedValue(Expr *E) { 8578 // We are checking that the expression is not known to have boolean value, 8579 // is an integer type; and is either unsigned after implicit casts, 8580 // or was unsigned before implicit casts. 8581 return isNonBooleanIntegerValue(E) && 8582 (!E->getType()->isSignedIntegerType() || 8583 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 8584 } 8585 8586 enum class LimitType { 8587 Max, // e.g. 32767 for short 8588 Min // e.g. -32768 for short 8589 }; 8590 8591 /// Checks whether Expr 'Constant' may be the 8592 /// std::numeric_limits<>::max() or std::numeric_limits<>::min() 8593 /// of the Expr 'Other'. If true, then returns the limit type (min or max). 8594 /// The Value is the evaluation of Constant 8595 llvm::Optional<LimitType> IsTypeLimit(Sema &S, Expr *Constant, Expr *Other, 8596 const llvm::APSInt &Value) { 8597 if (IsEnumConstOrFromMacro(S, Constant)) 8598 return llvm::Optional<LimitType>(); 8599 8600 if (isNonBooleanUnsignedValue(Other) && Value == 0) 8601 return LimitType::Min; 8602 8603 // TODO: Investigate using GetExprRange() to get tighter bounds 8604 // on the bit ranges. 8605 QualType OtherT = Other->IgnoreParenImpCasts()->getType(); 8606 if (const auto *AT = OtherT->getAs<AtomicType>()) 8607 OtherT = AT->getValueType(); 8608 8609 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8610 8611 if (llvm::APSInt::isSameValue( 8612 llvm::APSInt::getMaxValue(OtherRange.Width, 8613 OtherT->isUnsignedIntegerType()), 8614 Value)) 8615 return LimitType::Max; 8616 8617 if (llvm::APSInt::isSameValue( 8618 llvm::APSInt::getMinValue(OtherRange.Width, 8619 OtherT->isUnsignedIntegerType()), 8620 Value)) 8621 return LimitType::Min; 8622 8623 return llvm::Optional<LimitType>(); 8624 } 8625 8626 bool HasEnumType(Expr *E) { 8627 // Strip off implicit integral promotions. 8628 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8629 if (ICE->getCastKind() != CK_IntegralCast && 8630 ICE->getCastKind() != CK_NoOp) 8631 break; 8632 E = ICE->getSubExpr(); 8633 } 8634 8635 return E->getType()->isEnumeralType(); 8636 } 8637 8638 bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8639 Expr *Other, const llvm::APSInt &Value, 8640 bool RhsConstant) { 8641 // Disable warning in template instantiations 8642 // and only analyze <, >, <= and >= operations. 8643 if (S.inTemplateInstantiation() || !E->isRelationalOp()) 8644 return false; 8645 8646 BinaryOperatorKind Op = E->getOpcode(); 8647 8648 QualType OType = Other->IgnoreParenImpCasts()->getType(); 8649 8650 llvm::Optional<LimitType> ValueType; // Which limit (min/max) is the constant? 8651 8652 if (!(isNonBooleanIntegerValue(Other) && 8653 (ValueType = IsTypeLimit(S, Constant, Other, Value)))) 8654 return false; 8655 8656 bool ConstIsLowerBound = (Op == BO_LT || Op == BO_LE) ^ RhsConstant; 8657 bool ResultWhenConstEqualsOther = (Op == BO_LE || Op == BO_GE); 8658 bool ResultWhenConstNeOther = 8659 ConstIsLowerBound ^ (ValueType == LimitType::Max); 8660 if (ResultWhenConstEqualsOther != ResultWhenConstNeOther) 8661 return false; // The comparison is not tautological. 8662 8663 const bool Result = ResultWhenConstEqualsOther; 8664 8665 unsigned Diag = (isNonBooleanUnsignedValue(Other) && Value == 0) 8666 ? (HasEnumType(Other) 8667 ? diag::warn_unsigned_enum_always_true_comparison 8668 : diag::warn_unsigned_always_true_comparison) 8669 : diag::warn_tautological_constant_compare; 8670 8671 // Should be enough for uint128 (39 decimal digits) 8672 SmallString<64> PrettySourceValue; 8673 llvm::raw_svector_ostream OS(PrettySourceValue); 8674 OS << Value; 8675 8676 S.Diag(E->getOperatorLoc(), Diag) 8677 << RhsConstant << OType << E->getOpcodeStr() << OS.str() << Result 8678 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8679 8680 return true; 8681 } 8682 8683 bool DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8684 Expr *Other, const llvm::APSInt &Value, 8685 bool RhsConstant) { 8686 // Disable warning in template instantiations. 8687 if (S.inTemplateInstantiation()) 8688 return false; 8689 8690 Constant = Constant->IgnoreParenImpCasts(); 8691 Other = Other->IgnoreParenImpCasts(); 8692 8693 // TODO: Investigate using GetExprRange() to get tighter bounds 8694 // on the bit ranges. 8695 QualType OtherT = Other->getType(); 8696 if (const auto *AT = OtherT->getAs<AtomicType>()) 8697 OtherT = AT->getValueType(); 8698 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8699 unsigned OtherWidth = OtherRange.Width; 8700 8701 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8702 8703 BinaryOperatorKind op = E->getOpcode(); 8704 bool IsTrue = true; 8705 8706 // Used for diagnostic printout. 8707 enum { 8708 LiteralConstant = 0, 8709 CXXBoolLiteralTrue, 8710 CXXBoolLiteralFalse 8711 } LiteralOrBoolConstant = LiteralConstant; 8712 8713 if (!OtherIsBooleanType) { 8714 QualType ConstantT = Constant->getType(); 8715 QualType CommonT = E->getLHS()->getType(); 8716 8717 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8718 return false; 8719 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8720 "comparison with non-integer type"); 8721 8722 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8723 bool CommonSigned = CommonT->isSignedIntegerType(); 8724 8725 bool EqualityOnly = false; 8726 8727 if (CommonSigned) { 8728 // The common type is signed, therefore no signed to unsigned conversion. 8729 if (!OtherRange.NonNegative) { 8730 // Check that the constant is representable in type OtherT. 8731 if (ConstantSigned) { 8732 if (OtherWidth >= Value.getMinSignedBits()) 8733 return false; 8734 } else { // !ConstantSigned 8735 if (OtherWidth >= Value.getActiveBits() + 1) 8736 return false; 8737 } 8738 } else { // !OtherSigned 8739 // Check that the constant is representable in type OtherT. 8740 // Negative values are out of range. 8741 if (ConstantSigned) { 8742 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8743 return false; 8744 } else { // !ConstantSigned 8745 if (OtherWidth >= Value.getActiveBits()) 8746 return false; 8747 } 8748 } 8749 } else { // !CommonSigned 8750 if (OtherRange.NonNegative) { 8751 if (OtherWidth >= Value.getActiveBits()) 8752 return false; 8753 } else { // OtherSigned 8754 assert(!ConstantSigned && 8755 "Two signed types converted to unsigned types."); 8756 // Check to see if the constant is representable in OtherT. 8757 if (OtherWidth > Value.getActiveBits()) 8758 return false; 8759 // Check to see if the constant is equivalent to a negative value 8760 // cast to CommonT. 8761 if (S.Context.getIntWidth(ConstantT) == 8762 S.Context.getIntWidth(CommonT) && 8763 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8764 return false; 8765 // The constant value rests between values that OtherT can represent 8766 // after conversion. Relational comparison still works, but equality 8767 // comparisons will be tautological. 8768 EqualityOnly = true; 8769 } 8770 } 8771 8772 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8773 8774 if (op == BO_EQ || op == BO_NE) { 8775 IsTrue = op == BO_NE; 8776 } else if (EqualityOnly) { 8777 return false; 8778 } else if (RhsConstant) { 8779 if (op == BO_GT || op == BO_GE) 8780 IsTrue = !PositiveConstant; 8781 else // op == BO_LT || op == BO_LE 8782 IsTrue = PositiveConstant; 8783 } else { 8784 if (op == BO_LT || op == BO_LE) 8785 IsTrue = !PositiveConstant; 8786 else // op == BO_GT || op == BO_GE 8787 IsTrue = PositiveConstant; 8788 } 8789 } else { 8790 // Other isKnownToHaveBooleanValue 8791 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8792 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8793 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8794 8795 static const struct LinkedConditions { 8796 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8797 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8798 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8799 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8800 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8801 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8802 8803 } TruthTable = { 8804 // Constant on LHS. | Constant on RHS. | 8805 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8806 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8807 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8808 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8809 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8810 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8811 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8812 }; 8813 8814 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8815 8816 enum ConstantValue ConstVal = Zero; 8817 if (Value.isUnsigned() || Value.isNonNegative()) { 8818 if (Value == 0) { 8819 LiteralOrBoolConstant = 8820 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8821 ConstVal = Zero; 8822 } else if (Value == 1) { 8823 LiteralOrBoolConstant = 8824 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8825 ConstVal = One; 8826 } else { 8827 LiteralOrBoolConstant = LiteralConstant; 8828 ConstVal = GT_One; 8829 } 8830 } else { 8831 ConstVal = LT_Zero; 8832 } 8833 8834 CompareBoolWithConstantResult CmpRes; 8835 8836 switch (op) { 8837 case BO_LT: 8838 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8839 break; 8840 case BO_GT: 8841 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8842 break; 8843 case BO_LE: 8844 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8845 break; 8846 case BO_GE: 8847 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8848 break; 8849 case BO_EQ: 8850 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8851 break; 8852 case BO_NE: 8853 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8854 break; 8855 default: 8856 CmpRes = Unkwn; 8857 break; 8858 } 8859 8860 if (CmpRes == AFals) { 8861 IsTrue = false; 8862 } else if (CmpRes == ATrue) { 8863 IsTrue = true; 8864 } else { 8865 return false; 8866 } 8867 } 8868 8869 // If this is a comparison to an enum constant, include that 8870 // constant in the diagnostic. 8871 const EnumConstantDecl *ED = nullptr; 8872 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8873 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8874 8875 SmallString<64> PrettySourceValue; 8876 llvm::raw_svector_ostream OS(PrettySourceValue); 8877 if (ED) 8878 OS << '\'' << *ED << "' (" << Value << ")"; 8879 else 8880 OS << Value; 8881 8882 S.DiagRuntimeBehavior( 8883 E->getOperatorLoc(), E, 8884 S.PDiag(diag::warn_out_of_range_compare) 8885 << OS.str() << LiteralOrBoolConstant 8886 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8887 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8888 8889 return true; 8890 } 8891 8892 /// Analyze the operands of the given comparison. Implements the 8893 /// fallback case from AnalyzeComparison. 8894 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8895 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8896 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8897 } 8898 8899 /// \brief Implements -Wsign-compare. 8900 /// 8901 /// \param E the binary operator to check for warnings 8902 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8903 // The type the comparison is being performed in. 8904 QualType T = E->getLHS()->getType(); 8905 8906 // Only analyze comparison operators where both sides have been converted to 8907 // the same type. 8908 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8909 return AnalyzeImpConvsInComparison(S, E); 8910 8911 // Don't analyze value-dependent comparisons directly. 8912 if (E->isValueDependent()) 8913 return AnalyzeImpConvsInComparison(S, E); 8914 8915 Expr *LHS = E->getLHS(); 8916 Expr *RHS = E->getRHS(); 8917 8918 if (T->isIntegralType(S.Context)) { 8919 llvm::APSInt RHSValue; 8920 llvm::APSInt LHSValue; 8921 8922 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 8923 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 8924 8925 // We don't care about expressions whose result is a constant. 8926 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8927 return AnalyzeImpConvsInComparison(S, E); 8928 8929 // We only care about expressions where just one side is literal 8930 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 8931 // Is the constant on the RHS or LHS? 8932 const bool RhsConstant = IsRHSIntegralLiteral; 8933 Expr *Const = RhsConstant ? RHS : LHS; 8934 Expr *Other = RhsConstant ? LHS : RHS; 8935 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 8936 8937 // Check whether an integer constant comparison results in a value 8938 // of 'true' or 'false'. 8939 8940 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 8941 return AnalyzeImpConvsInComparison(S, E); 8942 8943 if (DiagnoseOutOfRangeComparison(S, E, Const, Other, Value, RhsConstant)) 8944 return AnalyzeImpConvsInComparison(S, E); 8945 } 8946 } 8947 8948 if (!T->hasUnsignedIntegerRepresentation()) { 8949 // We don't do anything special if this isn't an unsigned integral 8950 // comparison: we're only interested in integral comparisons, and 8951 // signed comparisons only happen in cases we don't care to warn about. 8952 return AnalyzeImpConvsInComparison(S, E); 8953 } 8954 8955 LHS = LHS->IgnoreParenImpCasts(); 8956 RHS = RHS->IgnoreParenImpCasts(); 8957 8958 // Check to see if one of the (unmodified) operands is of different 8959 // signedness. 8960 Expr *signedOperand, *unsignedOperand; 8961 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8962 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8963 "unsigned comparison between two signed integer expressions?"); 8964 signedOperand = LHS; 8965 unsignedOperand = RHS; 8966 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8967 signedOperand = RHS; 8968 unsignedOperand = LHS; 8969 } else { 8970 return AnalyzeImpConvsInComparison(S, E); 8971 } 8972 8973 // Otherwise, calculate the effective range of the signed operand. 8974 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8975 8976 // Go ahead and analyze implicit conversions in the operands. Note 8977 // that we skip the implicit conversions on both sides. 8978 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8979 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8980 8981 // If the signed range is non-negative, -Wsign-compare won't fire. 8982 if (signedRange.NonNegative) 8983 return; 8984 8985 // For (in)equality comparisons, if the unsigned operand is a 8986 // constant which cannot collide with a overflowed signed operand, 8987 // then reinterpreting the signed operand as unsigned will not 8988 // change the result of the comparison. 8989 if (E->isEqualityOp()) { 8990 unsigned comparisonWidth = S.Context.getIntWidth(T); 8991 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8992 8993 // We should never be unable to prove that the unsigned operand is 8994 // non-negative. 8995 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8996 8997 if (unsignedRange.Width < comparisonWidth) 8998 return; 8999 } 9000 9001 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 9002 S.PDiag(diag::warn_mixed_sign_comparison) 9003 << LHS->getType() << RHS->getType() 9004 << LHS->getSourceRange() << RHS->getSourceRange()); 9005 } 9006 9007 /// Analyzes an attempt to assign the given value to a bitfield. 9008 /// 9009 /// Returns true if there was something fishy about the attempt. 9010 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 9011 SourceLocation InitLoc) { 9012 assert(Bitfield->isBitField()); 9013 if (Bitfield->isInvalidDecl()) 9014 return false; 9015 9016 // White-list bool bitfields. 9017 QualType BitfieldType = Bitfield->getType(); 9018 if (BitfieldType->isBooleanType()) 9019 return false; 9020 9021 if (BitfieldType->isEnumeralType()) { 9022 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 9023 // If the underlying enum type was not explicitly specified as an unsigned 9024 // type and the enum contain only positive values, MSVC++ will cause an 9025 // inconsistency by storing this as a signed type. 9026 if (S.getLangOpts().CPlusPlus11 && 9027 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 9028 BitfieldEnumDecl->getNumPositiveBits() > 0 && 9029 BitfieldEnumDecl->getNumNegativeBits() == 0) { 9030 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 9031 << BitfieldEnumDecl->getNameAsString(); 9032 } 9033 } 9034 9035 if (Bitfield->getType()->isBooleanType()) 9036 return false; 9037 9038 // Ignore value- or type-dependent expressions. 9039 if (Bitfield->getBitWidth()->isValueDependent() || 9040 Bitfield->getBitWidth()->isTypeDependent() || 9041 Init->isValueDependent() || 9042 Init->isTypeDependent()) 9043 return false; 9044 9045 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 9046 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 9047 9048 llvm::APSInt Value; 9049 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 9050 Expr::SE_AllowSideEffects)) { 9051 // The RHS is not constant. If the RHS has an enum type, make sure the 9052 // bitfield is wide enough to hold all the values of the enum without 9053 // truncation. 9054 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 9055 EnumDecl *ED = EnumTy->getDecl(); 9056 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 9057 9058 // Enum types are implicitly signed on Windows, so check if there are any 9059 // negative enumerators to see if the enum was intended to be signed or 9060 // not. 9061 bool SignedEnum = ED->getNumNegativeBits() > 0; 9062 9063 // Check for surprising sign changes when assigning enum values to a 9064 // bitfield of different signedness. If the bitfield is signed and we 9065 // have exactly the right number of bits to store this unsigned enum, 9066 // suggest changing the enum to an unsigned type. This typically happens 9067 // on Windows where unfixed enums always use an underlying type of 'int'. 9068 unsigned DiagID = 0; 9069 if (SignedEnum && !SignedBitfield) { 9070 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 9071 } else if (SignedBitfield && !SignedEnum && 9072 ED->getNumPositiveBits() == FieldWidth) { 9073 DiagID = diag::warn_signed_bitfield_enum_conversion; 9074 } 9075 9076 if (DiagID) { 9077 S.Diag(InitLoc, DiagID) << Bitfield << ED; 9078 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 9079 SourceRange TypeRange = 9080 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 9081 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 9082 << SignedEnum << TypeRange; 9083 } 9084 9085 // Compute the required bitwidth. If the enum has negative values, we need 9086 // one more bit than the normal number of positive bits to represent the 9087 // sign bit. 9088 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 9089 ED->getNumNegativeBits()) 9090 : ED->getNumPositiveBits(); 9091 9092 // Check the bitwidth. 9093 if (BitsNeeded > FieldWidth) { 9094 Expr *WidthExpr = Bitfield->getBitWidth(); 9095 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 9096 << Bitfield << ED; 9097 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 9098 << BitsNeeded << ED << WidthExpr->getSourceRange(); 9099 } 9100 } 9101 9102 return false; 9103 } 9104 9105 unsigned OriginalWidth = Value.getBitWidth(); 9106 9107 if (!Value.isSigned() || Value.isNegative()) 9108 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 9109 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 9110 OriginalWidth = Value.getMinSignedBits(); 9111 9112 if (OriginalWidth <= FieldWidth) 9113 return false; 9114 9115 // Compute the value which the bitfield will contain. 9116 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 9117 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 9118 9119 // Check whether the stored value is equal to the original value. 9120 TruncatedValue = TruncatedValue.extend(OriginalWidth); 9121 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 9122 return false; 9123 9124 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9125 // therefore don't strictly fit into a signed bitfield of width 1. 9126 if (FieldWidth == 1 && Value == 1) 9127 return false; 9128 9129 std::string PrettyValue = Value.toString(10); 9130 std::string PrettyTrunc = TruncatedValue.toString(10); 9131 9132 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9133 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9134 << Init->getSourceRange(); 9135 9136 return true; 9137 } 9138 9139 /// Analyze the given simple or compound assignment for warning-worthy 9140 /// operations. 9141 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9142 // Just recurse on the LHS. 9143 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9144 9145 // We want to recurse on the RHS as normal unless we're assigning to 9146 // a bitfield. 9147 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9148 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9149 E->getOperatorLoc())) { 9150 // Recurse, ignoring any implicit conversions on the RHS. 9151 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9152 E->getOperatorLoc()); 9153 } 9154 } 9155 9156 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9157 } 9158 9159 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9160 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9161 SourceLocation CContext, unsigned diag, 9162 bool pruneControlFlow = false) { 9163 if (pruneControlFlow) { 9164 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9165 S.PDiag(diag) 9166 << SourceType << T << E->getSourceRange() 9167 << SourceRange(CContext)); 9168 return; 9169 } 9170 S.Diag(E->getExprLoc(), diag) 9171 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9172 } 9173 9174 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9175 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 9176 unsigned diag, bool pruneControlFlow = false) { 9177 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9178 } 9179 9180 9181 /// Diagnose an implicit cast from a floating point value to an integer value. 9182 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9183 9184 SourceLocation CContext) { 9185 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9186 const bool PruneWarnings = S.inTemplateInstantiation(); 9187 9188 Expr *InnerE = E->IgnoreParenImpCasts(); 9189 // We also want to warn on, e.g., "int i = -1.234" 9190 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9191 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9192 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9193 9194 const bool IsLiteral = 9195 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9196 9197 llvm::APFloat Value(0.0); 9198 bool IsConstant = 9199 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9200 if (!IsConstant) { 9201 return DiagnoseImpCast(S, E, T, CContext, 9202 diag::warn_impcast_float_integer, PruneWarnings); 9203 } 9204 9205 bool isExact = false; 9206 9207 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9208 T->hasUnsignedIntegerRepresentation()); 9209 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 9210 &isExact) == llvm::APFloat::opOK && 9211 isExact) { 9212 if (IsLiteral) return; 9213 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9214 PruneWarnings); 9215 } 9216 9217 unsigned DiagID = 0; 9218 if (IsLiteral) { 9219 // Warn on floating point literal to integer. 9220 DiagID = diag::warn_impcast_literal_float_to_integer; 9221 } else if (IntegerValue == 0) { 9222 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9223 return DiagnoseImpCast(S, E, T, CContext, 9224 diag::warn_impcast_float_integer, PruneWarnings); 9225 } 9226 // Warn on non-zero to zero conversion. 9227 DiagID = diag::warn_impcast_float_to_integer_zero; 9228 } else { 9229 if (IntegerValue.isUnsigned()) { 9230 if (!IntegerValue.isMaxValue()) { 9231 return DiagnoseImpCast(S, E, T, CContext, 9232 diag::warn_impcast_float_integer, PruneWarnings); 9233 } 9234 } else { // IntegerValue.isSigned() 9235 if (!IntegerValue.isMaxSignedValue() && 9236 !IntegerValue.isMinSignedValue()) { 9237 return DiagnoseImpCast(S, E, T, CContext, 9238 diag::warn_impcast_float_integer, PruneWarnings); 9239 } 9240 } 9241 // Warn on evaluatable floating point expression to integer conversion. 9242 DiagID = diag::warn_impcast_float_to_integer; 9243 } 9244 9245 // FIXME: Force the precision of the source value down so we don't print 9246 // digits which are usually useless (we don't really care here if we 9247 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9248 // would automatically print the shortest representation, but it's a bit 9249 // tricky to implement. 9250 SmallString<16> PrettySourceValue; 9251 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9252 precision = (precision * 59 + 195) / 196; 9253 Value.toString(PrettySourceValue, precision); 9254 9255 SmallString<16> PrettyTargetValue; 9256 if (IsBool) 9257 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9258 else 9259 IntegerValue.toString(PrettyTargetValue); 9260 9261 if (PruneWarnings) { 9262 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9263 S.PDiag(DiagID) 9264 << E->getType() << T.getUnqualifiedType() 9265 << PrettySourceValue << PrettyTargetValue 9266 << E->getSourceRange() << SourceRange(CContext)); 9267 } else { 9268 S.Diag(E->getExprLoc(), DiagID) 9269 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9270 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9271 } 9272 } 9273 9274 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 9275 if (!Range.Width) return "0"; 9276 9277 llvm::APSInt ValueInRange = Value; 9278 ValueInRange.setIsSigned(!Range.NonNegative); 9279 ValueInRange = ValueInRange.trunc(Range.Width); 9280 return ValueInRange.toString(10); 9281 } 9282 9283 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9284 if (!isa<ImplicitCastExpr>(Ex)) 9285 return false; 9286 9287 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9288 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9289 const Type *Source = 9290 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9291 if (Target->isDependentType()) 9292 return false; 9293 9294 const BuiltinType *FloatCandidateBT = 9295 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9296 const Type *BoolCandidateType = ToBool ? Target : Source; 9297 9298 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9299 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9300 } 9301 9302 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9303 SourceLocation CC) { 9304 unsigned NumArgs = TheCall->getNumArgs(); 9305 for (unsigned i = 0; i < NumArgs; ++i) { 9306 Expr *CurrA = TheCall->getArg(i); 9307 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9308 continue; 9309 9310 bool IsSwapped = ((i > 0) && 9311 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9312 IsSwapped |= ((i < (NumArgs - 1)) && 9313 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9314 if (IsSwapped) { 9315 // Warn on this floating-point to bool conversion. 9316 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9317 CurrA->getType(), CC, 9318 diag::warn_impcast_floating_point_to_bool); 9319 } 9320 } 9321 } 9322 9323 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 9324 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9325 E->getExprLoc())) 9326 return; 9327 9328 // Don't warn on functions which have return type nullptr_t. 9329 if (isa<CallExpr>(E)) 9330 return; 9331 9332 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9333 const Expr::NullPointerConstantKind NullKind = 9334 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9335 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9336 return; 9337 9338 // Return if target type is a safe conversion. 9339 if (T->isAnyPointerType() || T->isBlockPointerType() || 9340 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9341 return; 9342 9343 SourceLocation Loc = E->getSourceRange().getBegin(); 9344 9345 // Venture through the macro stacks to get to the source of macro arguments. 9346 // The new location is a better location than the complete location that was 9347 // passed in. 9348 while (S.SourceMgr.isMacroArgExpansion(Loc)) 9349 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 9350 9351 while (S.SourceMgr.isMacroArgExpansion(CC)) 9352 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 9353 9354 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9355 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9356 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9357 Loc, S.SourceMgr, S.getLangOpts()); 9358 if (MacroName == "NULL") 9359 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 9360 } 9361 9362 // Only warn if the null and context location are in the same macro expansion. 9363 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9364 return; 9365 9366 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9367 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 9368 << FixItHint::CreateReplacement(Loc, 9369 S.getFixItZeroLiteralForType(T, Loc)); 9370 } 9371 9372 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9373 ObjCArrayLiteral *ArrayLiteral); 9374 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9375 ObjCDictionaryLiteral *DictionaryLiteral); 9376 9377 /// Check a single element within a collection literal against the 9378 /// target element type. 9379 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 9380 Expr *Element, unsigned ElementKind) { 9381 // Skip a bitcast to 'id' or qualified 'id'. 9382 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9383 if (ICE->getCastKind() == CK_BitCast && 9384 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9385 Element = ICE->getSubExpr(); 9386 } 9387 9388 QualType ElementType = Element->getType(); 9389 ExprResult ElementResult(Element); 9390 if (ElementType->getAs<ObjCObjectPointerType>() && 9391 S.CheckSingleAssignmentConstraints(TargetElementType, 9392 ElementResult, 9393 false, false) 9394 != Sema::Compatible) { 9395 S.Diag(Element->getLocStart(), 9396 diag::warn_objc_collection_literal_element) 9397 << ElementType << ElementKind << TargetElementType 9398 << Element->getSourceRange(); 9399 } 9400 9401 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9402 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9403 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9404 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9405 } 9406 9407 /// Check an Objective-C array literal being converted to the given 9408 /// target type. 9409 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9410 ObjCArrayLiteral *ArrayLiteral) { 9411 if (!S.NSArrayDecl) 9412 return; 9413 9414 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9415 if (!TargetObjCPtr) 9416 return; 9417 9418 if (TargetObjCPtr->isUnspecialized() || 9419 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9420 != S.NSArrayDecl->getCanonicalDecl()) 9421 return; 9422 9423 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9424 if (TypeArgs.size() != 1) 9425 return; 9426 9427 QualType TargetElementType = TypeArgs[0]; 9428 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9429 checkObjCCollectionLiteralElement(S, TargetElementType, 9430 ArrayLiteral->getElement(I), 9431 0); 9432 } 9433 } 9434 9435 /// Check an Objective-C dictionary literal being converted to the given 9436 /// target type. 9437 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9438 ObjCDictionaryLiteral *DictionaryLiteral) { 9439 if (!S.NSDictionaryDecl) 9440 return; 9441 9442 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9443 if (!TargetObjCPtr) 9444 return; 9445 9446 if (TargetObjCPtr->isUnspecialized() || 9447 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9448 != S.NSDictionaryDecl->getCanonicalDecl()) 9449 return; 9450 9451 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9452 if (TypeArgs.size() != 2) 9453 return; 9454 9455 QualType TargetKeyType = TypeArgs[0]; 9456 QualType TargetObjectType = TypeArgs[1]; 9457 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9458 auto Element = DictionaryLiteral->getKeyValueElement(I); 9459 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9460 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9461 } 9462 } 9463 9464 // Helper function to filter out cases for constant width constant conversion. 9465 // Don't warn on char array initialization or for non-decimal values. 9466 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9467 SourceLocation CC) { 9468 // If initializing from a constant, and the constant starts with '0', 9469 // then it is a binary, octal, or hexadecimal. Allow these constants 9470 // to fill all the bits, even if there is a sign change. 9471 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9472 const char FirstLiteralCharacter = 9473 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9474 if (FirstLiteralCharacter == '0') 9475 return false; 9476 } 9477 9478 // If the CC location points to a '{', and the type is char, then assume 9479 // assume it is an array initialization. 9480 if (CC.isValid() && T->isCharType()) { 9481 const char FirstContextCharacter = 9482 S.getSourceManager().getCharacterData(CC)[0]; 9483 if (FirstContextCharacter == '{') 9484 return false; 9485 } 9486 9487 return true; 9488 } 9489 9490 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 9491 SourceLocation CC, bool *ICContext = nullptr) { 9492 if (E->isTypeDependent() || E->isValueDependent()) return; 9493 9494 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9495 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9496 if (Source == Target) return; 9497 if (Target->isDependentType()) return; 9498 9499 // If the conversion context location is invalid don't complain. We also 9500 // don't want to emit a warning if the issue occurs from the expansion of 9501 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9502 // delay this check as long as possible. Once we detect we are in that 9503 // scenario, we just return. 9504 if (CC.isInvalid()) 9505 return; 9506 9507 // Diagnose implicit casts to bool. 9508 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9509 if (isa<StringLiteral>(E)) 9510 // Warn on string literal to bool. Checks for string literals in logical 9511 // and expressions, for instance, assert(0 && "error here"), are 9512 // prevented by a check in AnalyzeImplicitConversions(). 9513 return DiagnoseImpCast(S, E, T, CC, 9514 diag::warn_impcast_string_literal_to_bool); 9515 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9516 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9517 // This covers the literal expressions that evaluate to Objective-C 9518 // objects. 9519 return DiagnoseImpCast(S, E, T, CC, 9520 diag::warn_impcast_objective_c_literal_to_bool); 9521 } 9522 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9523 // Warn on pointer to bool conversion that is always true. 9524 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9525 SourceRange(CC)); 9526 } 9527 } 9528 9529 // Check implicit casts from Objective-C collection literals to specialized 9530 // collection types, e.g., NSArray<NSString *> *. 9531 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9532 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9533 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9534 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9535 9536 // Strip vector types. 9537 if (isa<VectorType>(Source)) { 9538 if (!isa<VectorType>(Target)) { 9539 if (S.SourceMgr.isInSystemMacro(CC)) 9540 return; 9541 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9542 } 9543 9544 // If the vector cast is cast between two vectors of the same size, it is 9545 // a bitcast, not a conversion. 9546 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9547 return; 9548 9549 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9550 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9551 } 9552 if (auto VecTy = dyn_cast<VectorType>(Target)) 9553 Target = VecTy->getElementType().getTypePtr(); 9554 9555 // Strip complex types. 9556 if (isa<ComplexType>(Source)) { 9557 if (!isa<ComplexType>(Target)) { 9558 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 9559 return; 9560 9561 return DiagnoseImpCast(S, E, T, CC, 9562 S.getLangOpts().CPlusPlus 9563 ? diag::err_impcast_complex_scalar 9564 : diag::warn_impcast_complex_scalar); 9565 } 9566 9567 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9568 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9569 } 9570 9571 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9572 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9573 9574 // If the source is floating point... 9575 if (SourceBT && SourceBT->isFloatingPoint()) { 9576 // ...and the target is floating point... 9577 if (TargetBT && TargetBT->isFloatingPoint()) { 9578 // ...then warn if we're dropping FP rank. 9579 9580 // Builtin FP kinds are ordered by increasing FP rank. 9581 if (SourceBT->getKind() > TargetBT->getKind()) { 9582 // Don't warn about float constants that are precisely 9583 // representable in the target type. 9584 Expr::EvalResult result; 9585 if (E->EvaluateAsRValue(result, S.Context)) { 9586 // Value might be a float, a float vector, or a float complex. 9587 if (IsSameFloatAfterCast(result.Val, 9588 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9589 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9590 return; 9591 } 9592 9593 if (S.SourceMgr.isInSystemMacro(CC)) 9594 return; 9595 9596 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9597 } 9598 // ... or possibly if we're increasing rank, too 9599 else if (TargetBT->getKind() > SourceBT->getKind()) { 9600 if (S.SourceMgr.isInSystemMacro(CC)) 9601 return; 9602 9603 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9604 } 9605 return; 9606 } 9607 9608 // If the target is integral, always warn. 9609 if (TargetBT && TargetBT->isInteger()) { 9610 if (S.SourceMgr.isInSystemMacro(CC)) 9611 return; 9612 9613 DiagnoseFloatingImpCast(S, E, T, CC); 9614 } 9615 9616 // Detect the case where a call result is converted from floating-point to 9617 // to bool, and the final argument to the call is converted from bool, to 9618 // discover this typo: 9619 // 9620 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9621 // 9622 // FIXME: This is an incredibly special case; is there some more general 9623 // way to detect this class of misplaced-parentheses bug? 9624 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9625 // Check last argument of function call to see if it is an 9626 // implicit cast from a type matching the type the result 9627 // is being cast to. 9628 CallExpr *CEx = cast<CallExpr>(E); 9629 if (unsigned NumArgs = CEx->getNumArgs()) { 9630 Expr *LastA = CEx->getArg(NumArgs - 1); 9631 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9632 if (isa<ImplicitCastExpr>(LastA) && 9633 InnerE->getType()->isBooleanType()) { 9634 // Warn on this floating-point to bool conversion 9635 DiagnoseImpCast(S, E, T, CC, 9636 diag::warn_impcast_floating_point_to_bool); 9637 } 9638 } 9639 } 9640 return; 9641 } 9642 9643 DiagnoseNullConversion(S, E, T, CC); 9644 9645 S.DiscardMisalignedMemberAddress(Target, E); 9646 9647 if (!Source->isIntegerType() || !Target->isIntegerType()) 9648 return; 9649 9650 // TODO: remove this early return once the false positives for constant->bool 9651 // in templates, macros, etc, are reduced or removed. 9652 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9653 return; 9654 9655 IntRange SourceRange = GetExprRange(S.Context, E); 9656 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9657 9658 if (SourceRange.Width > TargetRange.Width) { 9659 // If the source is a constant, use a default-on diagnostic. 9660 // TODO: this should happen for bitfield stores, too. 9661 llvm::APSInt Value(32); 9662 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9663 if (S.SourceMgr.isInSystemMacro(CC)) 9664 return; 9665 9666 std::string PrettySourceValue = Value.toString(10); 9667 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9668 9669 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9670 S.PDiag(diag::warn_impcast_integer_precision_constant) 9671 << PrettySourceValue << PrettyTargetValue 9672 << E->getType() << T << E->getSourceRange() 9673 << clang::SourceRange(CC)); 9674 return; 9675 } 9676 9677 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9678 if (S.SourceMgr.isInSystemMacro(CC)) 9679 return; 9680 9681 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9682 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9683 /* pruneControlFlow */ true); 9684 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9685 } 9686 9687 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9688 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9689 // Warn when doing a signed to signed conversion, warn if the positive 9690 // source value is exactly the width of the target type, which will 9691 // cause a negative value to be stored. 9692 9693 llvm::APSInt Value; 9694 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9695 !S.SourceMgr.isInSystemMacro(CC)) { 9696 if (isSameWidthConstantConversion(S, E, T, CC)) { 9697 std::string PrettySourceValue = Value.toString(10); 9698 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9699 9700 S.DiagRuntimeBehavior( 9701 E->getExprLoc(), E, 9702 S.PDiag(diag::warn_impcast_integer_precision_constant) 9703 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9704 << E->getSourceRange() << clang::SourceRange(CC)); 9705 return; 9706 } 9707 } 9708 9709 // Fall through for non-constants to give a sign conversion warning. 9710 } 9711 9712 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9713 (!TargetRange.NonNegative && SourceRange.NonNegative && 9714 SourceRange.Width == TargetRange.Width)) { 9715 if (S.SourceMgr.isInSystemMacro(CC)) 9716 return; 9717 9718 unsigned DiagID = diag::warn_impcast_integer_sign; 9719 9720 // Traditionally, gcc has warned about this under -Wsign-compare. 9721 // We also want to warn about it in -Wconversion. 9722 // So if -Wconversion is off, use a completely identical diagnostic 9723 // in the sign-compare group. 9724 // The conditional-checking code will 9725 if (ICContext) { 9726 DiagID = diag::warn_impcast_integer_sign_conditional; 9727 *ICContext = true; 9728 } 9729 9730 return DiagnoseImpCast(S, E, T, CC, DiagID); 9731 } 9732 9733 // Diagnose conversions between different enumeration types. 9734 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9735 // type, to give us better diagnostics. 9736 QualType SourceType = E->getType(); 9737 if (!S.getLangOpts().CPlusPlus) { 9738 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9739 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9740 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9741 SourceType = S.Context.getTypeDeclType(Enum); 9742 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9743 } 9744 } 9745 9746 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9747 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9748 if (SourceEnum->getDecl()->hasNameForLinkage() && 9749 TargetEnum->getDecl()->hasNameForLinkage() && 9750 SourceEnum != TargetEnum) { 9751 if (S.SourceMgr.isInSystemMacro(CC)) 9752 return; 9753 9754 return DiagnoseImpCast(S, E, SourceType, T, CC, 9755 diag::warn_impcast_different_enum_types); 9756 } 9757 } 9758 9759 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9760 SourceLocation CC, QualType T); 9761 9762 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9763 SourceLocation CC, bool &ICContext) { 9764 E = E->IgnoreParenImpCasts(); 9765 9766 if (isa<ConditionalOperator>(E)) 9767 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9768 9769 AnalyzeImplicitConversions(S, E, CC); 9770 if (E->getType() != T) 9771 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9772 } 9773 9774 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9775 SourceLocation CC, QualType T) { 9776 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9777 9778 bool Suspicious = false; 9779 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9780 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9781 9782 // If -Wconversion would have warned about either of the candidates 9783 // for a signedness conversion to the context type... 9784 if (!Suspicious) return; 9785 9786 // ...but it's currently ignored... 9787 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9788 return; 9789 9790 // ...then check whether it would have warned about either of the 9791 // candidates for a signedness conversion to the condition type. 9792 if (E->getType() == T) return; 9793 9794 Suspicious = false; 9795 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9796 E->getType(), CC, &Suspicious); 9797 if (!Suspicious) 9798 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9799 E->getType(), CC, &Suspicious); 9800 } 9801 9802 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9803 /// Input argument E is a logical expression. 9804 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9805 if (S.getLangOpts().Bool) 9806 return; 9807 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9808 } 9809 9810 /// AnalyzeImplicitConversions - Find and report any interesting 9811 /// implicit conversions in the given expression. There are a couple 9812 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9813 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9814 QualType T = OrigE->getType(); 9815 Expr *E = OrigE->IgnoreParenImpCasts(); 9816 9817 if (E->isTypeDependent() || E->isValueDependent()) 9818 return; 9819 9820 // For conditional operators, we analyze the arguments as if they 9821 // were being fed directly into the output. 9822 if (isa<ConditionalOperator>(E)) { 9823 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9824 CheckConditionalOperator(S, CO, CC, T); 9825 return; 9826 } 9827 9828 // Check implicit argument conversions for function calls. 9829 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9830 CheckImplicitArgumentConversions(S, Call, CC); 9831 9832 // Go ahead and check any implicit conversions we might have skipped. 9833 // The non-canonical typecheck is just an optimization; 9834 // CheckImplicitConversion will filter out dead implicit conversions. 9835 if (E->getType() != T) 9836 CheckImplicitConversion(S, E, T, CC); 9837 9838 // Now continue drilling into this expression. 9839 9840 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9841 // The bound subexpressions in a PseudoObjectExpr are not reachable 9842 // as transitive children. 9843 // FIXME: Use a more uniform representation for this. 9844 for (auto *SE : POE->semantics()) 9845 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9846 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9847 } 9848 9849 // Skip past explicit casts. 9850 if (isa<ExplicitCastExpr>(E)) { 9851 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9852 return AnalyzeImplicitConversions(S, E, CC); 9853 } 9854 9855 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9856 // Do a somewhat different check with comparison operators. 9857 if (BO->isComparisonOp()) 9858 return AnalyzeComparison(S, BO); 9859 9860 // And with simple assignments. 9861 if (BO->getOpcode() == BO_Assign) 9862 return AnalyzeAssignment(S, BO); 9863 } 9864 9865 // These break the otherwise-useful invariant below. Fortunately, 9866 // we don't really need to recurse into them, because any internal 9867 // expressions should have been analyzed already when they were 9868 // built into statements. 9869 if (isa<StmtExpr>(E)) return; 9870 9871 // Don't descend into unevaluated contexts. 9872 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9873 9874 // Now just recurse over the expression's children. 9875 CC = E->getExprLoc(); 9876 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9877 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9878 for (Stmt *SubStmt : E->children()) { 9879 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9880 if (!ChildExpr) 9881 continue; 9882 9883 if (IsLogicalAndOperator && 9884 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9885 // Ignore checking string literals that are in logical and operators. 9886 // This is a common pattern for asserts. 9887 continue; 9888 AnalyzeImplicitConversions(S, ChildExpr, CC); 9889 } 9890 9891 if (BO && BO->isLogicalOp()) { 9892 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9893 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9894 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9895 9896 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9897 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9898 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9899 } 9900 9901 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9902 if (U->getOpcode() == UO_LNot) 9903 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9904 } 9905 9906 } // end anonymous namespace 9907 9908 /// Diagnose integer type and any valid implicit convertion to it. 9909 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 9910 // Taking into account implicit conversions, 9911 // allow any integer. 9912 if (!E->getType()->isIntegerType()) { 9913 S.Diag(E->getLocStart(), 9914 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9915 return true; 9916 } 9917 // Potentially emit standard warnings for implicit conversions if enabled 9918 // using -Wconversion. 9919 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 9920 return false; 9921 } 9922 9923 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9924 // Returns true when emitting a warning about taking the address of a reference. 9925 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9926 const PartialDiagnostic &PD) { 9927 E = E->IgnoreParenImpCasts(); 9928 9929 const FunctionDecl *FD = nullptr; 9930 9931 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9932 if (!DRE->getDecl()->getType()->isReferenceType()) 9933 return false; 9934 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9935 if (!M->getMemberDecl()->getType()->isReferenceType()) 9936 return false; 9937 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9938 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9939 return false; 9940 FD = Call->getDirectCallee(); 9941 } else { 9942 return false; 9943 } 9944 9945 SemaRef.Diag(E->getExprLoc(), PD); 9946 9947 // If possible, point to location of function. 9948 if (FD) { 9949 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9950 } 9951 9952 return true; 9953 } 9954 9955 // Returns true if the SourceLocation is expanded from any macro body. 9956 // Returns false if the SourceLocation is invalid, is from not in a macro 9957 // expansion, or is from expanded from a top-level macro argument. 9958 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9959 if (Loc.isInvalid()) 9960 return false; 9961 9962 while (Loc.isMacroID()) { 9963 if (SM.isMacroBodyExpansion(Loc)) 9964 return true; 9965 Loc = SM.getImmediateMacroCallerLoc(Loc); 9966 } 9967 9968 return false; 9969 } 9970 9971 /// \brief Diagnose pointers that are always non-null. 9972 /// \param E the expression containing the pointer 9973 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9974 /// compared to a null pointer 9975 /// \param IsEqual True when the comparison is equal to a null pointer 9976 /// \param Range Extra SourceRange to highlight in the diagnostic 9977 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9978 Expr::NullPointerConstantKind NullKind, 9979 bool IsEqual, SourceRange Range) { 9980 if (!E) 9981 return; 9982 9983 // Don't warn inside macros. 9984 if (E->getExprLoc().isMacroID()) { 9985 const SourceManager &SM = getSourceManager(); 9986 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9987 IsInAnyMacroBody(SM, Range.getBegin())) 9988 return; 9989 } 9990 E = E->IgnoreImpCasts(); 9991 9992 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9993 9994 if (isa<CXXThisExpr>(E)) { 9995 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9996 : diag::warn_this_bool_conversion; 9997 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9998 return; 9999 } 10000 10001 bool IsAddressOf = false; 10002 10003 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10004 if (UO->getOpcode() != UO_AddrOf) 10005 return; 10006 IsAddressOf = true; 10007 E = UO->getSubExpr(); 10008 } 10009 10010 if (IsAddressOf) { 10011 unsigned DiagID = IsCompare 10012 ? diag::warn_address_of_reference_null_compare 10013 : diag::warn_address_of_reference_bool_conversion; 10014 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 10015 << IsEqual; 10016 if (CheckForReference(*this, E, PD)) { 10017 return; 10018 } 10019 } 10020 10021 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 10022 bool IsParam = isa<NonNullAttr>(NonnullAttr); 10023 std::string Str; 10024 llvm::raw_string_ostream S(Str); 10025 E->printPretty(S, nullptr, getPrintingPolicy()); 10026 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 10027 : diag::warn_cast_nonnull_to_bool; 10028 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 10029 << E->getSourceRange() << Range << IsEqual; 10030 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 10031 }; 10032 10033 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 10034 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 10035 if (auto *Callee = Call->getDirectCallee()) { 10036 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 10037 ComplainAboutNonnullParamOrCall(A); 10038 return; 10039 } 10040 } 10041 } 10042 10043 // Expect to find a single Decl. Skip anything more complicated. 10044 ValueDecl *D = nullptr; 10045 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 10046 D = R->getDecl(); 10047 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10048 D = M->getMemberDecl(); 10049 } 10050 10051 // Weak Decls can be null. 10052 if (!D || D->isWeak()) 10053 return; 10054 10055 // Check for parameter decl with nonnull attribute 10056 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 10057 if (getCurFunction() && 10058 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 10059 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 10060 ComplainAboutNonnullParamOrCall(A); 10061 return; 10062 } 10063 10064 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 10065 auto ParamIter = llvm::find(FD->parameters(), PV); 10066 assert(ParamIter != FD->param_end()); 10067 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 10068 10069 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 10070 if (!NonNull->args_size()) { 10071 ComplainAboutNonnullParamOrCall(NonNull); 10072 return; 10073 } 10074 10075 for (unsigned ArgNo : NonNull->args()) { 10076 if (ArgNo == ParamNo) { 10077 ComplainAboutNonnullParamOrCall(NonNull); 10078 return; 10079 } 10080 } 10081 } 10082 } 10083 } 10084 } 10085 10086 QualType T = D->getType(); 10087 const bool IsArray = T->isArrayType(); 10088 const bool IsFunction = T->isFunctionType(); 10089 10090 // Address of function is used to silence the function warning. 10091 if (IsAddressOf && IsFunction) { 10092 return; 10093 } 10094 10095 // Found nothing. 10096 if (!IsAddressOf && !IsFunction && !IsArray) 10097 return; 10098 10099 // Pretty print the expression for the diagnostic. 10100 std::string Str; 10101 llvm::raw_string_ostream S(Str); 10102 E->printPretty(S, nullptr, getPrintingPolicy()); 10103 10104 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 10105 : diag::warn_impcast_pointer_to_bool; 10106 enum { 10107 AddressOf, 10108 FunctionPointer, 10109 ArrayPointer 10110 } DiagType; 10111 if (IsAddressOf) 10112 DiagType = AddressOf; 10113 else if (IsFunction) 10114 DiagType = FunctionPointer; 10115 else if (IsArray) 10116 DiagType = ArrayPointer; 10117 else 10118 llvm_unreachable("Could not determine diagnostic."); 10119 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 10120 << Range << IsEqual; 10121 10122 if (!IsFunction) 10123 return; 10124 10125 // Suggest '&' to silence the function warning. 10126 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10127 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10128 10129 // Check to see if '()' fixit should be emitted. 10130 QualType ReturnType; 10131 UnresolvedSet<4> NonTemplateOverloads; 10132 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10133 if (ReturnType.isNull()) 10134 return; 10135 10136 if (IsCompare) { 10137 // There are two cases here. If there is null constant, the only suggest 10138 // for a pointer return type. If the null is 0, then suggest if the return 10139 // type is a pointer or an integer type. 10140 if (!ReturnType->isPointerType()) { 10141 if (NullKind == Expr::NPCK_ZeroExpression || 10142 NullKind == Expr::NPCK_ZeroLiteral) { 10143 if (!ReturnType->isIntegerType()) 10144 return; 10145 } else { 10146 return; 10147 } 10148 } 10149 } else { // !IsCompare 10150 // For function to bool, only suggest if the function pointer has bool 10151 // return type. 10152 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10153 return; 10154 } 10155 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10156 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10157 } 10158 10159 /// Diagnoses "dangerous" implicit conversions within the given 10160 /// expression (which is a full expression). Implements -Wconversion 10161 /// and -Wsign-compare. 10162 /// 10163 /// \param CC the "context" location of the implicit conversion, i.e. 10164 /// the most location of the syntactic entity requiring the implicit 10165 /// conversion 10166 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10167 // Don't diagnose in unevaluated contexts. 10168 if (isUnevaluatedContext()) 10169 return; 10170 10171 // Don't diagnose for value- or type-dependent expressions. 10172 if (E->isTypeDependent() || E->isValueDependent()) 10173 return; 10174 10175 // Check for array bounds violations in cases where the check isn't triggered 10176 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10177 // ArraySubscriptExpr is on the RHS of a variable initialization. 10178 CheckArrayAccess(E); 10179 10180 // This is not the right CC for (e.g.) a variable initialization. 10181 AnalyzeImplicitConversions(*this, E, CC); 10182 } 10183 10184 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10185 /// Input argument E is a logical expression. 10186 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10187 ::CheckBoolLikeConversion(*this, E, CC); 10188 } 10189 10190 /// Diagnose when expression is an integer constant expression and its evaluation 10191 /// results in integer overflow 10192 void Sema::CheckForIntOverflow (Expr *E) { 10193 // Use a work list to deal with nested struct initializers. 10194 SmallVector<Expr *, 2> Exprs(1, E); 10195 10196 do { 10197 Expr *E = Exprs.pop_back_val(); 10198 10199 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 10200 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10201 continue; 10202 } 10203 10204 if (auto InitList = dyn_cast<InitListExpr>(E)) 10205 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10206 10207 if (isa<ObjCBoxedExpr>(E)) 10208 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10209 } while (!Exprs.empty()); 10210 } 10211 10212 namespace { 10213 /// \brief Visitor for expressions which looks for unsequenced operations on the 10214 /// same object. 10215 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10216 typedef EvaluatedExprVisitor<SequenceChecker> Base; 10217 10218 /// \brief A tree of sequenced regions within an expression. Two regions are 10219 /// unsequenced if one is an ancestor or a descendent of the other. When we 10220 /// finish processing an expression with sequencing, such as a comma 10221 /// expression, we fold its tree nodes into its parent, since they are 10222 /// unsequenced with respect to nodes we will visit later. 10223 class SequenceTree { 10224 struct Value { 10225 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10226 unsigned Parent : 31; 10227 unsigned Merged : 1; 10228 }; 10229 SmallVector<Value, 8> Values; 10230 10231 public: 10232 /// \brief A region within an expression which may be sequenced with respect 10233 /// to some other region. 10234 class Seq { 10235 explicit Seq(unsigned N) : Index(N) {} 10236 unsigned Index; 10237 friend class SequenceTree; 10238 public: 10239 Seq() : Index(0) {} 10240 }; 10241 10242 SequenceTree() { Values.push_back(Value(0)); } 10243 Seq root() const { return Seq(0); } 10244 10245 /// \brief Create a new sequence of operations, which is an unsequenced 10246 /// subset of \p Parent. This sequence of operations is sequenced with 10247 /// respect to other children of \p Parent. 10248 Seq allocate(Seq Parent) { 10249 Values.push_back(Value(Parent.Index)); 10250 return Seq(Values.size() - 1); 10251 } 10252 10253 /// \brief Merge a sequence of operations into its parent. 10254 void merge(Seq S) { 10255 Values[S.Index].Merged = true; 10256 } 10257 10258 /// \brief Determine whether two operations are unsequenced. This operation 10259 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10260 /// should have been merged into its parent as appropriate. 10261 bool isUnsequenced(Seq Cur, Seq Old) { 10262 unsigned C = representative(Cur.Index); 10263 unsigned Target = representative(Old.Index); 10264 while (C >= Target) { 10265 if (C == Target) 10266 return true; 10267 C = Values[C].Parent; 10268 } 10269 return false; 10270 } 10271 10272 private: 10273 /// \brief Pick a representative for a sequence. 10274 unsigned representative(unsigned K) { 10275 if (Values[K].Merged) 10276 // Perform path compression as we go. 10277 return Values[K].Parent = representative(Values[K].Parent); 10278 return K; 10279 } 10280 }; 10281 10282 /// An object for which we can track unsequenced uses. 10283 typedef NamedDecl *Object; 10284 10285 /// Different flavors of object usage which we track. We only track the 10286 /// least-sequenced usage of each kind. 10287 enum UsageKind { 10288 /// A read of an object. Multiple unsequenced reads are OK. 10289 UK_Use, 10290 /// A modification of an object which is sequenced before the value 10291 /// computation of the expression, such as ++n in C++. 10292 UK_ModAsValue, 10293 /// A modification of an object which is not sequenced before the value 10294 /// computation of the expression, such as n++. 10295 UK_ModAsSideEffect, 10296 10297 UK_Count = UK_ModAsSideEffect + 1 10298 }; 10299 10300 struct Usage { 10301 Usage() : Use(nullptr), Seq() {} 10302 Expr *Use; 10303 SequenceTree::Seq Seq; 10304 }; 10305 10306 struct UsageInfo { 10307 UsageInfo() : Diagnosed(false) {} 10308 Usage Uses[UK_Count]; 10309 /// Have we issued a diagnostic for this variable already? 10310 bool Diagnosed; 10311 }; 10312 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 10313 10314 Sema &SemaRef; 10315 /// Sequenced regions within the expression. 10316 SequenceTree Tree; 10317 /// Declaration modifications and references which we have seen. 10318 UsageInfoMap UsageMap; 10319 /// The region we are currently within. 10320 SequenceTree::Seq Region; 10321 /// Filled in with declarations which were modified as a side-effect 10322 /// (that is, post-increment operations). 10323 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 10324 /// Expressions to check later. We defer checking these to reduce 10325 /// stack usage. 10326 SmallVectorImpl<Expr *> &WorkList; 10327 10328 /// RAII object wrapping the visitation of a sequenced subexpression of an 10329 /// expression. At the end of this process, the side-effects of the evaluation 10330 /// become sequenced with respect to the value computation of the result, so 10331 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10332 /// UK_ModAsValue. 10333 struct SequencedSubexpression { 10334 SequencedSubexpression(SequenceChecker &Self) 10335 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 10336 Self.ModAsSideEffect = &ModAsSideEffect; 10337 } 10338 ~SequencedSubexpression() { 10339 for (auto &M : llvm::reverse(ModAsSideEffect)) { 10340 UsageInfo &U = Self.UsageMap[M.first]; 10341 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 10342 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 10343 SideEffectUsage = M.second; 10344 } 10345 Self.ModAsSideEffect = OldModAsSideEffect; 10346 } 10347 10348 SequenceChecker &Self; 10349 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 10350 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 10351 }; 10352 10353 /// RAII object wrapping the visitation of a subexpression which we might 10354 /// choose to evaluate as a constant. If any subexpression is evaluated and 10355 /// found to be non-constant, this allows us to suppress the evaluation of 10356 /// the outer expression. 10357 class EvaluationTracker { 10358 public: 10359 EvaluationTracker(SequenceChecker &Self) 10360 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 10361 Self.EvalTracker = this; 10362 } 10363 ~EvaluationTracker() { 10364 Self.EvalTracker = Prev; 10365 if (Prev) 10366 Prev->EvalOK &= EvalOK; 10367 } 10368 10369 bool evaluate(const Expr *E, bool &Result) { 10370 if (!EvalOK || E->isValueDependent()) 10371 return false; 10372 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 10373 return EvalOK; 10374 } 10375 10376 private: 10377 SequenceChecker &Self; 10378 EvaluationTracker *Prev; 10379 bool EvalOK; 10380 } *EvalTracker; 10381 10382 /// \brief Find the object which is produced by the specified expression, 10383 /// if any. 10384 Object getObject(Expr *E, bool Mod) const { 10385 E = E->IgnoreParenCasts(); 10386 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10387 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 10388 return getObject(UO->getSubExpr(), Mod); 10389 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10390 if (BO->getOpcode() == BO_Comma) 10391 return getObject(BO->getRHS(), Mod); 10392 if (Mod && BO->isAssignmentOp()) 10393 return getObject(BO->getLHS(), Mod); 10394 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10395 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 10396 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 10397 return ME->getMemberDecl(); 10398 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10399 // FIXME: If this is a reference, map through to its value. 10400 return DRE->getDecl(); 10401 return nullptr; 10402 } 10403 10404 /// \brief Note that an object was modified or used by an expression. 10405 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 10406 Usage &U = UI.Uses[UK]; 10407 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 10408 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 10409 ModAsSideEffect->push_back(std::make_pair(O, U)); 10410 U.Use = Ref; 10411 U.Seq = Region; 10412 } 10413 } 10414 /// \brief Check whether a modification or use conflicts with a prior usage. 10415 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 10416 bool IsModMod) { 10417 if (UI.Diagnosed) 10418 return; 10419 10420 const Usage &U = UI.Uses[OtherKind]; 10421 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 10422 return; 10423 10424 Expr *Mod = U.Use; 10425 Expr *ModOrUse = Ref; 10426 if (OtherKind == UK_Use) 10427 std::swap(Mod, ModOrUse); 10428 10429 SemaRef.Diag(Mod->getExprLoc(), 10430 IsModMod ? diag::warn_unsequenced_mod_mod 10431 : diag::warn_unsequenced_mod_use) 10432 << O << SourceRange(ModOrUse->getExprLoc()); 10433 UI.Diagnosed = true; 10434 } 10435 10436 void notePreUse(Object O, Expr *Use) { 10437 UsageInfo &U = UsageMap[O]; 10438 // Uses conflict with other modifications. 10439 checkUsage(O, U, Use, UK_ModAsValue, false); 10440 } 10441 void notePostUse(Object O, Expr *Use) { 10442 UsageInfo &U = UsageMap[O]; 10443 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 10444 addUsage(U, O, Use, UK_Use); 10445 } 10446 10447 void notePreMod(Object O, Expr *Mod) { 10448 UsageInfo &U = UsageMap[O]; 10449 // Modifications conflict with other modifications and with uses. 10450 checkUsage(O, U, Mod, UK_ModAsValue, true); 10451 checkUsage(O, U, Mod, UK_Use, false); 10452 } 10453 void notePostMod(Object O, Expr *Use, UsageKind UK) { 10454 UsageInfo &U = UsageMap[O]; 10455 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 10456 addUsage(U, O, Use, UK); 10457 } 10458 10459 public: 10460 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 10461 : Base(S.Context), SemaRef(S), Region(Tree.root()), 10462 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 10463 Visit(E); 10464 } 10465 10466 void VisitStmt(Stmt *S) { 10467 // Skip all statements which aren't expressions for now. 10468 } 10469 10470 void VisitExpr(Expr *E) { 10471 // By default, just recurse to evaluated subexpressions. 10472 Base::VisitStmt(E); 10473 } 10474 10475 void VisitCastExpr(CastExpr *E) { 10476 Object O = Object(); 10477 if (E->getCastKind() == CK_LValueToRValue) 10478 O = getObject(E->getSubExpr(), false); 10479 10480 if (O) 10481 notePreUse(O, E); 10482 VisitExpr(E); 10483 if (O) 10484 notePostUse(O, E); 10485 } 10486 10487 void VisitBinComma(BinaryOperator *BO) { 10488 // C++11 [expr.comma]p1: 10489 // Every value computation and side effect associated with the left 10490 // expression is sequenced before every value computation and side 10491 // effect associated with the right expression. 10492 SequenceTree::Seq LHS = Tree.allocate(Region); 10493 SequenceTree::Seq RHS = Tree.allocate(Region); 10494 SequenceTree::Seq OldRegion = Region; 10495 10496 { 10497 SequencedSubexpression SeqLHS(*this); 10498 Region = LHS; 10499 Visit(BO->getLHS()); 10500 } 10501 10502 Region = RHS; 10503 Visit(BO->getRHS()); 10504 10505 Region = OldRegion; 10506 10507 // Forget that LHS and RHS are sequenced. They are both unsequenced 10508 // with respect to other stuff. 10509 Tree.merge(LHS); 10510 Tree.merge(RHS); 10511 } 10512 10513 void VisitBinAssign(BinaryOperator *BO) { 10514 // The modification is sequenced after the value computation of the LHS 10515 // and RHS, so check it before inspecting the operands and update the 10516 // map afterwards. 10517 Object O = getObject(BO->getLHS(), true); 10518 if (!O) 10519 return VisitExpr(BO); 10520 10521 notePreMod(O, BO); 10522 10523 // C++11 [expr.ass]p7: 10524 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 10525 // only once. 10526 // 10527 // Therefore, for a compound assignment operator, O is considered used 10528 // everywhere except within the evaluation of E1 itself. 10529 if (isa<CompoundAssignOperator>(BO)) 10530 notePreUse(O, BO); 10531 10532 Visit(BO->getLHS()); 10533 10534 if (isa<CompoundAssignOperator>(BO)) 10535 notePostUse(O, BO); 10536 10537 Visit(BO->getRHS()); 10538 10539 // C++11 [expr.ass]p1: 10540 // the assignment is sequenced [...] before the value computation of the 10541 // assignment expression. 10542 // C11 6.5.16/3 has no such rule. 10543 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10544 : UK_ModAsSideEffect); 10545 } 10546 10547 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 10548 VisitBinAssign(CAO); 10549 } 10550 10551 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10552 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10553 void VisitUnaryPreIncDec(UnaryOperator *UO) { 10554 Object O = getObject(UO->getSubExpr(), true); 10555 if (!O) 10556 return VisitExpr(UO); 10557 10558 notePreMod(O, UO); 10559 Visit(UO->getSubExpr()); 10560 // C++11 [expr.pre.incr]p1: 10561 // the expression ++x is equivalent to x+=1 10562 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10563 : UK_ModAsSideEffect); 10564 } 10565 10566 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10567 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10568 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10569 Object O = getObject(UO->getSubExpr(), true); 10570 if (!O) 10571 return VisitExpr(UO); 10572 10573 notePreMod(O, UO); 10574 Visit(UO->getSubExpr()); 10575 notePostMod(O, UO, UK_ModAsSideEffect); 10576 } 10577 10578 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10579 void VisitBinLOr(BinaryOperator *BO) { 10580 // The side-effects of the LHS of an '&&' are sequenced before the 10581 // value computation of the RHS, and hence before the value computation 10582 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10583 // as if they were unconditionally sequenced. 10584 EvaluationTracker Eval(*this); 10585 { 10586 SequencedSubexpression Sequenced(*this); 10587 Visit(BO->getLHS()); 10588 } 10589 10590 bool Result; 10591 if (Eval.evaluate(BO->getLHS(), Result)) { 10592 if (!Result) 10593 Visit(BO->getRHS()); 10594 } else { 10595 // Check for unsequenced operations in the RHS, treating it as an 10596 // entirely separate evaluation. 10597 // 10598 // FIXME: If there are operations in the RHS which are unsequenced 10599 // with respect to operations outside the RHS, and those operations 10600 // are unconditionally evaluated, diagnose them. 10601 WorkList.push_back(BO->getRHS()); 10602 } 10603 } 10604 void VisitBinLAnd(BinaryOperator *BO) { 10605 EvaluationTracker Eval(*this); 10606 { 10607 SequencedSubexpression Sequenced(*this); 10608 Visit(BO->getLHS()); 10609 } 10610 10611 bool Result; 10612 if (Eval.evaluate(BO->getLHS(), Result)) { 10613 if (Result) 10614 Visit(BO->getRHS()); 10615 } else { 10616 WorkList.push_back(BO->getRHS()); 10617 } 10618 } 10619 10620 // Only visit the condition, unless we can be sure which subexpression will 10621 // be chosen. 10622 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10623 EvaluationTracker Eval(*this); 10624 { 10625 SequencedSubexpression Sequenced(*this); 10626 Visit(CO->getCond()); 10627 } 10628 10629 bool Result; 10630 if (Eval.evaluate(CO->getCond(), Result)) 10631 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10632 else { 10633 WorkList.push_back(CO->getTrueExpr()); 10634 WorkList.push_back(CO->getFalseExpr()); 10635 } 10636 } 10637 10638 void VisitCallExpr(CallExpr *CE) { 10639 // C++11 [intro.execution]p15: 10640 // When calling a function [...], every value computation and side effect 10641 // associated with any argument expression, or with the postfix expression 10642 // designating the called function, is sequenced before execution of every 10643 // expression or statement in the body of the function [and thus before 10644 // the value computation of its result]. 10645 SequencedSubexpression Sequenced(*this); 10646 Base::VisitCallExpr(CE); 10647 10648 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10649 } 10650 10651 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10652 // This is a call, so all subexpressions are sequenced before the result. 10653 SequencedSubexpression Sequenced(*this); 10654 10655 if (!CCE->isListInitialization()) 10656 return VisitExpr(CCE); 10657 10658 // In C++11, list initializations are sequenced. 10659 SmallVector<SequenceTree::Seq, 32> Elts; 10660 SequenceTree::Seq Parent = Region; 10661 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10662 E = CCE->arg_end(); 10663 I != E; ++I) { 10664 Region = Tree.allocate(Parent); 10665 Elts.push_back(Region); 10666 Visit(*I); 10667 } 10668 10669 // Forget that the initializers are sequenced. 10670 Region = Parent; 10671 for (unsigned I = 0; I < Elts.size(); ++I) 10672 Tree.merge(Elts[I]); 10673 } 10674 10675 void VisitInitListExpr(InitListExpr *ILE) { 10676 if (!SemaRef.getLangOpts().CPlusPlus11) 10677 return VisitExpr(ILE); 10678 10679 // In C++11, list initializations are sequenced. 10680 SmallVector<SequenceTree::Seq, 32> Elts; 10681 SequenceTree::Seq Parent = Region; 10682 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10683 Expr *E = ILE->getInit(I); 10684 if (!E) continue; 10685 Region = Tree.allocate(Parent); 10686 Elts.push_back(Region); 10687 Visit(E); 10688 } 10689 10690 // Forget that the initializers are sequenced. 10691 Region = Parent; 10692 for (unsigned I = 0; I < Elts.size(); ++I) 10693 Tree.merge(Elts[I]); 10694 } 10695 }; 10696 } // end anonymous namespace 10697 10698 void Sema::CheckUnsequencedOperations(Expr *E) { 10699 SmallVector<Expr *, 8> WorkList; 10700 WorkList.push_back(E); 10701 while (!WorkList.empty()) { 10702 Expr *Item = WorkList.pop_back_val(); 10703 SequenceChecker(*this, Item, WorkList); 10704 } 10705 } 10706 10707 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10708 bool IsConstexpr) { 10709 CheckImplicitConversions(E, CheckLoc); 10710 if (!E->isInstantiationDependent()) 10711 CheckUnsequencedOperations(E); 10712 if (!IsConstexpr && !E->isValueDependent()) 10713 CheckForIntOverflow(E); 10714 DiagnoseMisalignedMembers(); 10715 } 10716 10717 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10718 FieldDecl *BitField, 10719 Expr *Init) { 10720 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10721 } 10722 10723 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10724 SourceLocation Loc) { 10725 if (!PType->isVariablyModifiedType()) 10726 return; 10727 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10728 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10729 return; 10730 } 10731 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10732 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10733 return; 10734 } 10735 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10736 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10737 return; 10738 } 10739 10740 const ArrayType *AT = S.Context.getAsArrayType(PType); 10741 if (!AT) 10742 return; 10743 10744 if (AT->getSizeModifier() != ArrayType::Star) { 10745 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10746 return; 10747 } 10748 10749 S.Diag(Loc, diag::err_array_star_in_function_definition); 10750 } 10751 10752 /// CheckParmsForFunctionDef - Check that the parameters of the given 10753 /// function are appropriate for the definition of a function. This 10754 /// takes care of any checks that cannot be performed on the 10755 /// declaration itself, e.g., that the types of each of the function 10756 /// parameters are complete. 10757 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10758 bool CheckParameterNames) { 10759 bool HasInvalidParm = false; 10760 for (ParmVarDecl *Param : Parameters) { 10761 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10762 // function declarator that is part of a function definition of 10763 // that function shall not have incomplete type. 10764 // 10765 // This is also C++ [dcl.fct]p6. 10766 if (!Param->isInvalidDecl() && 10767 RequireCompleteType(Param->getLocation(), Param->getType(), 10768 diag::err_typecheck_decl_incomplete_type)) { 10769 Param->setInvalidDecl(); 10770 HasInvalidParm = true; 10771 } 10772 10773 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10774 // declaration of each parameter shall include an identifier. 10775 if (CheckParameterNames && 10776 Param->getIdentifier() == nullptr && 10777 !Param->isImplicit() && 10778 !getLangOpts().CPlusPlus) 10779 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10780 10781 // C99 6.7.5.3p12: 10782 // If the function declarator is not part of a definition of that 10783 // function, parameters may have incomplete type and may use the [*] 10784 // notation in their sequences of declarator specifiers to specify 10785 // variable length array types. 10786 QualType PType = Param->getOriginalType(); 10787 // FIXME: This diagnostic should point the '[*]' if source-location 10788 // information is added for it. 10789 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10790 10791 // MSVC destroys objects passed by value in the callee. Therefore a 10792 // function definition which takes such a parameter must be able to call the 10793 // object's destructor. However, we don't perform any direct access check 10794 // on the dtor. 10795 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10796 .getCXXABI() 10797 .areArgsDestroyedLeftToRightInCallee()) { 10798 if (!Param->isInvalidDecl()) { 10799 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10800 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10801 if (!ClassDecl->isInvalidDecl() && 10802 !ClassDecl->hasIrrelevantDestructor() && 10803 !ClassDecl->isDependentContext()) { 10804 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10805 MarkFunctionReferenced(Param->getLocation(), Destructor); 10806 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10807 } 10808 } 10809 } 10810 } 10811 10812 // Parameters with the pass_object_size attribute only need to be marked 10813 // constant at function definitions. Because we lack information about 10814 // whether we're on a declaration or definition when we're instantiating the 10815 // attribute, we need to check for constness here. 10816 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10817 if (!Param->getType().isConstQualified()) 10818 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10819 << Attr->getSpelling() << 1; 10820 } 10821 10822 return HasInvalidParm; 10823 } 10824 10825 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 10826 /// or MemberExpr. 10827 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 10828 ASTContext &Context) { 10829 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 10830 return Context.getDeclAlign(DRE->getDecl()); 10831 10832 if (const auto *ME = dyn_cast<MemberExpr>(E)) 10833 return Context.getDeclAlign(ME->getMemberDecl()); 10834 10835 return TypeAlign; 10836 } 10837 10838 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10839 /// pointer cast increases the alignment requirements. 10840 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10841 // This is actually a lot of work to potentially be doing on every 10842 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10843 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10844 return; 10845 10846 // Ignore dependent types. 10847 if (T->isDependentType() || Op->getType()->isDependentType()) 10848 return; 10849 10850 // Require that the destination be a pointer type. 10851 const PointerType *DestPtr = T->getAs<PointerType>(); 10852 if (!DestPtr) return; 10853 10854 // If the destination has alignment 1, we're done. 10855 QualType DestPointee = DestPtr->getPointeeType(); 10856 if (DestPointee->isIncompleteType()) return; 10857 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10858 if (DestAlign.isOne()) return; 10859 10860 // Require that the source be a pointer type. 10861 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10862 if (!SrcPtr) return; 10863 QualType SrcPointee = SrcPtr->getPointeeType(); 10864 10865 // Whitelist casts from cv void*. We already implicitly 10866 // whitelisted casts to cv void*, since they have alignment 1. 10867 // Also whitelist casts involving incomplete types, which implicitly 10868 // includes 'void'. 10869 if (SrcPointee->isIncompleteType()) return; 10870 10871 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10872 10873 if (auto *CE = dyn_cast<CastExpr>(Op)) { 10874 if (CE->getCastKind() == CK_ArrayToPointerDecay) 10875 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 10876 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 10877 if (UO->getOpcode() == UO_AddrOf) 10878 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 10879 } 10880 10881 if (SrcAlign >= DestAlign) return; 10882 10883 Diag(TRange.getBegin(), diag::warn_cast_align) 10884 << Op->getType() << T 10885 << static_cast<unsigned>(SrcAlign.getQuantity()) 10886 << static_cast<unsigned>(DestAlign.getQuantity()) 10887 << TRange << Op->getSourceRange(); 10888 } 10889 10890 /// \brief Check whether this array fits the idiom of a size-one tail padded 10891 /// array member of a struct. 10892 /// 10893 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10894 /// commonly used to emulate flexible arrays in C89 code. 10895 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10896 const NamedDecl *ND) { 10897 if (Size != 1 || !ND) return false; 10898 10899 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10900 if (!FD) return false; 10901 10902 // Don't consider sizes resulting from macro expansions or template argument 10903 // substitution to form C89 tail-padded arrays. 10904 10905 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10906 while (TInfo) { 10907 TypeLoc TL = TInfo->getTypeLoc(); 10908 // Look through typedefs. 10909 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10910 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10911 TInfo = TDL->getTypeSourceInfo(); 10912 continue; 10913 } 10914 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10915 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10916 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10917 return false; 10918 } 10919 break; 10920 } 10921 10922 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10923 if (!RD) return false; 10924 if (RD->isUnion()) return false; 10925 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10926 if (!CRD->isStandardLayout()) return false; 10927 } 10928 10929 // See if this is the last field decl in the record. 10930 const Decl *D = FD; 10931 while ((D = D->getNextDeclInContext())) 10932 if (isa<FieldDecl>(D)) 10933 return false; 10934 return true; 10935 } 10936 10937 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10938 const ArraySubscriptExpr *ASE, 10939 bool AllowOnePastEnd, bool IndexNegated) { 10940 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10941 if (IndexExpr->isValueDependent()) 10942 return; 10943 10944 const Type *EffectiveType = 10945 BaseExpr->getType()->getPointeeOrArrayElementType(); 10946 BaseExpr = BaseExpr->IgnoreParenCasts(); 10947 const ConstantArrayType *ArrayTy = 10948 Context.getAsConstantArrayType(BaseExpr->getType()); 10949 if (!ArrayTy) 10950 return; 10951 10952 llvm::APSInt index; 10953 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10954 return; 10955 if (IndexNegated) 10956 index = -index; 10957 10958 const NamedDecl *ND = nullptr; 10959 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10960 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10961 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10962 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10963 10964 if (index.isUnsigned() || !index.isNegative()) { 10965 llvm::APInt size = ArrayTy->getSize(); 10966 if (!size.isStrictlyPositive()) 10967 return; 10968 10969 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10970 if (BaseType != EffectiveType) { 10971 // Make sure we're comparing apples to apples when comparing index to size 10972 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10973 uint64_t array_typesize = Context.getTypeSize(BaseType); 10974 // Handle ptrarith_typesize being zero, such as when casting to void* 10975 if (!ptrarith_typesize) ptrarith_typesize = 1; 10976 if (ptrarith_typesize != array_typesize) { 10977 // There's a cast to a different size type involved 10978 uint64_t ratio = array_typesize / ptrarith_typesize; 10979 // TODO: Be smarter about handling cases where array_typesize is not a 10980 // multiple of ptrarith_typesize 10981 if (ptrarith_typesize * ratio == array_typesize) 10982 size *= llvm::APInt(size.getBitWidth(), ratio); 10983 } 10984 } 10985 10986 if (size.getBitWidth() > index.getBitWidth()) 10987 index = index.zext(size.getBitWidth()); 10988 else if (size.getBitWidth() < index.getBitWidth()) 10989 size = size.zext(index.getBitWidth()); 10990 10991 // For array subscripting the index must be less than size, but for pointer 10992 // arithmetic also allow the index (offset) to be equal to size since 10993 // computing the next address after the end of the array is legal and 10994 // commonly done e.g. in C++ iterators and range-based for loops. 10995 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10996 return; 10997 10998 // Also don't warn for arrays of size 1 which are members of some 10999 // structure. These are often used to approximate flexible arrays in C89 11000 // code. 11001 if (IsTailPaddedMemberArray(*this, size, ND)) 11002 return; 11003 11004 // Suppress the warning if the subscript expression (as identified by the 11005 // ']' location) and the index expression are both from macro expansions 11006 // within a system header. 11007 if (ASE) { 11008 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 11009 ASE->getRBracketLoc()); 11010 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 11011 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 11012 IndexExpr->getLocStart()); 11013 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 11014 return; 11015 } 11016 } 11017 11018 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 11019 if (ASE) 11020 DiagID = diag::warn_array_index_exceeds_bounds; 11021 11022 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11023 PDiag(DiagID) << index.toString(10, true) 11024 << size.toString(10, true) 11025 << (unsigned)size.getLimitedValue(~0U) 11026 << IndexExpr->getSourceRange()); 11027 } else { 11028 unsigned DiagID = diag::warn_array_index_precedes_bounds; 11029 if (!ASE) { 11030 DiagID = diag::warn_ptr_arith_precedes_bounds; 11031 if (index.isNegative()) index = -index; 11032 } 11033 11034 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11035 PDiag(DiagID) << index.toString(10, true) 11036 << IndexExpr->getSourceRange()); 11037 } 11038 11039 if (!ND) { 11040 // Try harder to find a NamedDecl to point at in the note. 11041 while (const ArraySubscriptExpr *ASE = 11042 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 11043 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 11044 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11045 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 11046 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11047 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 11048 } 11049 11050 if (ND) 11051 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 11052 PDiag(diag::note_array_index_out_of_bounds) 11053 << ND->getDeclName()); 11054 } 11055 11056 void Sema::CheckArrayAccess(const Expr *expr) { 11057 int AllowOnePastEnd = 0; 11058 while (expr) { 11059 expr = expr->IgnoreParenImpCasts(); 11060 switch (expr->getStmtClass()) { 11061 case Stmt::ArraySubscriptExprClass: { 11062 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 11063 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 11064 AllowOnePastEnd > 0); 11065 return; 11066 } 11067 case Stmt::OMPArraySectionExprClass: { 11068 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 11069 if (ASE->getLowerBound()) 11070 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 11071 /*ASE=*/nullptr, AllowOnePastEnd > 0); 11072 return; 11073 } 11074 case Stmt::UnaryOperatorClass: { 11075 // Only unwrap the * and & unary operators 11076 const UnaryOperator *UO = cast<UnaryOperator>(expr); 11077 expr = UO->getSubExpr(); 11078 switch (UO->getOpcode()) { 11079 case UO_AddrOf: 11080 AllowOnePastEnd++; 11081 break; 11082 case UO_Deref: 11083 AllowOnePastEnd--; 11084 break; 11085 default: 11086 return; 11087 } 11088 break; 11089 } 11090 case Stmt::ConditionalOperatorClass: { 11091 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 11092 if (const Expr *lhs = cond->getLHS()) 11093 CheckArrayAccess(lhs); 11094 if (const Expr *rhs = cond->getRHS()) 11095 CheckArrayAccess(rhs); 11096 return; 11097 } 11098 case Stmt::CXXOperatorCallExprClass: { 11099 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 11100 for (const auto *Arg : OCE->arguments()) 11101 CheckArrayAccess(Arg); 11102 return; 11103 } 11104 default: 11105 return; 11106 } 11107 } 11108 } 11109 11110 //===--- CHECK: Objective-C retain cycles ----------------------------------// 11111 11112 namespace { 11113 struct RetainCycleOwner { 11114 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 11115 VarDecl *Variable; 11116 SourceRange Range; 11117 SourceLocation Loc; 11118 bool Indirect; 11119 11120 void setLocsFrom(Expr *e) { 11121 Loc = e->getExprLoc(); 11122 Range = e->getSourceRange(); 11123 } 11124 }; 11125 } // end anonymous namespace 11126 11127 /// Consider whether capturing the given variable can possibly lead to 11128 /// a retain cycle. 11129 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11130 // In ARC, it's captured strongly iff the variable has __strong 11131 // lifetime. In MRR, it's captured strongly if the variable is 11132 // __block and has an appropriate type. 11133 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11134 return false; 11135 11136 owner.Variable = var; 11137 if (ref) 11138 owner.setLocsFrom(ref); 11139 return true; 11140 } 11141 11142 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11143 while (true) { 11144 e = e->IgnoreParens(); 11145 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11146 switch (cast->getCastKind()) { 11147 case CK_BitCast: 11148 case CK_LValueBitCast: 11149 case CK_LValueToRValue: 11150 case CK_ARCReclaimReturnedObject: 11151 e = cast->getSubExpr(); 11152 continue; 11153 11154 default: 11155 return false; 11156 } 11157 } 11158 11159 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11160 ObjCIvarDecl *ivar = ref->getDecl(); 11161 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11162 return false; 11163 11164 // Try to find a retain cycle in the base. 11165 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11166 return false; 11167 11168 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11169 owner.Indirect = true; 11170 return true; 11171 } 11172 11173 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11174 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11175 if (!var) return false; 11176 return considerVariable(var, ref, owner); 11177 } 11178 11179 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11180 if (member->isArrow()) return false; 11181 11182 // Don't count this as an indirect ownership. 11183 e = member->getBase(); 11184 continue; 11185 } 11186 11187 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11188 // Only pay attention to pseudo-objects on property references. 11189 ObjCPropertyRefExpr *pre 11190 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11191 ->IgnoreParens()); 11192 if (!pre) return false; 11193 if (pre->isImplicitProperty()) return false; 11194 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11195 if (!property->isRetaining() && 11196 !(property->getPropertyIvarDecl() && 11197 property->getPropertyIvarDecl()->getType() 11198 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11199 return false; 11200 11201 owner.Indirect = true; 11202 if (pre->isSuperReceiver()) { 11203 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11204 if (!owner.Variable) 11205 return false; 11206 owner.Loc = pre->getLocation(); 11207 owner.Range = pre->getSourceRange(); 11208 return true; 11209 } 11210 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11211 ->getSourceExpr()); 11212 continue; 11213 } 11214 11215 // Array ivars? 11216 11217 return false; 11218 } 11219 } 11220 11221 namespace { 11222 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11223 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11224 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11225 Context(Context), Variable(variable), Capturer(nullptr), 11226 VarWillBeReased(false) {} 11227 ASTContext &Context; 11228 VarDecl *Variable; 11229 Expr *Capturer; 11230 bool VarWillBeReased; 11231 11232 void VisitDeclRefExpr(DeclRefExpr *ref) { 11233 if (ref->getDecl() == Variable && !Capturer) 11234 Capturer = ref; 11235 } 11236 11237 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11238 if (Capturer) return; 11239 Visit(ref->getBase()); 11240 if (Capturer && ref->isFreeIvar()) 11241 Capturer = ref; 11242 } 11243 11244 void VisitBlockExpr(BlockExpr *block) { 11245 // Look inside nested blocks 11246 if (block->getBlockDecl()->capturesVariable(Variable)) 11247 Visit(block->getBlockDecl()->getBody()); 11248 } 11249 11250 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11251 if (Capturer) return; 11252 if (OVE->getSourceExpr()) 11253 Visit(OVE->getSourceExpr()); 11254 } 11255 void VisitBinaryOperator(BinaryOperator *BinOp) { 11256 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11257 return; 11258 Expr *LHS = BinOp->getLHS(); 11259 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11260 if (DRE->getDecl() != Variable) 11261 return; 11262 if (Expr *RHS = BinOp->getRHS()) { 11263 RHS = RHS->IgnoreParenCasts(); 11264 llvm::APSInt Value; 11265 VarWillBeReased = 11266 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11267 } 11268 } 11269 } 11270 }; 11271 } // end anonymous namespace 11272 11273 /// Check whether the given argument is a block which captures a 11274 /// variable. 11275 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11276 assert(owner.Variable && owner.Loc.isValid()); 11277 11278 e = e->IgnoreParenCasts(); 11279 11280 // Look through [^{...} copy] and Block_copy(^{...}). 11281 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11282 Selector Cmd = ME->getSelector(); 11283 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11284 e = ME->getInstanceReceiver(); 11285 if (!e) 11286 return nullptr; 11287 e = e->IgnoreParenCasts(); 11288 } 11289 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11290 if (CE->getNumArgs() == 1) { 11291 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11292 if (Fn) { 11293 const IdentifierInfo *FnI = Fn->getIdentifier(); 11294 if (FnI && FnI->isStr("_Block_copy")) { 11295 e = CE->getArg(0)->IgnoreParenCasts(); 11296 } 11297 } 11298 } 11299 } 11300 11301 BlockExpr *block = dyn_cast<BlockExpr>(e); 11302 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11303 return nullptr; 11304 11305 FindCaptureVisitor visitor(S.Context, owner.Variable); 11306 visitor.Visit(block->getBlockDecl()->getBody()); 11307 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11308 } 11309 11310 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11311 RetainCycleOwner &owner) { 11312 assert(capturer); 11313 assert(owner.Variable && owner.Loc.isValid()); 11314 11315 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11316 << owner.Variable << capturer->getSourceRange(); 11317 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11318 << owner.Indirect << owner.Range; 11319 } 11320 11321 /// Check for a keyword selector that starts with the word 'add' or 11322 /// 'set'. 11323 static bool isSetterLikeSelector(Selector sel) { 11324 if (sel.isUnarySelector()) return false; 11325 11326 StringRef str = sel.getNameForSlot(0); 11327 while (!str.empty() && str.front() == '_') str = str.substr(1); 11328 if (str.startswith("set")) 11329 str = str.substr(3); 11330 else if (str.startswith("add")) { 11331 // Specially whitelist 'addOperationWithBlock:'. 11332 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 11333 return false; 11334 str = str.substr(3); 11335 } 11336 else 11337 return false; 11338 11339 if (str.empty()) return true; 11340 return !isLowercase(str.front()); 11341 } 11342 11343 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 11344 ObjCMessageExpr *Message) { 11345 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 11346 Message->getReceiverInterface(), 11347 NSAPI::ClassId_NSMutableArray); 11348 if (!IsMutableArray) { 11349 return None; 11350 } 11351 11352 Selector Sel = Message->getSelector(); 11353 11354 Optional<NSAPI::NSArrayMethodKind> MKOpt = 11355 S.NSAPIObj->getNSArrayMethodKind(Sel); 11356 if (!MKOpt) { 11357 return None; 11358 } 11359 11360 NSAPI::NSArrayMethodKind MK = *MKOpt; 11361 11362 switch (MK) { 11363 case NSAPI::NSMutableArr_addObject: 11364 case NSAPI::NSMutableArr_insertObjectAtIndex: 11365 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 11366 return 0; 11367 case NSAPI::NSMutableArr_replaceObjectAtIndex: 11368 return 1; 11369 11370 default: 11371 return None; 11372 } 11373 11374 return None; 11375 } 11376 11377 static 11378 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 11379 ObjCMessageExpr *Message) { 11380 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 11381 Message->getReceiverInterface(), 11382 NSAPI::ClassId_NSMutableDictionary); 11383 if (!IsMutableDictionary) { 11384 return None; 11385 } 11386 11387 Selector Sel = Message->getSelector(); 11388 11389 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 11390 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 11391 if (!MKOpt) { 11392 return None; 11393 } 11394 11395 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 11396 11397 switch (MK) { 11398 case NSAPI::NSMutableDict_setObjectForKey: 11399 case NSAPI::NSMutableDict_setValueForKey: 11400 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 11401 return 0; 11402 11403 default: 11404 return None; 11405 } 11406 11407 return None; 11408 } 11409 11410 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 11411 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 11412 Message->getReceiverInterface(), 11413 NSAPI::ClassId_NSMutableSet); 11414 11415 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 11416 Message->getReceiverInterface(), 11417 NSAPI::ClassId_NSMutableOrderedSet); 11418 if (!IsMutableSet && !IsMutableOrderedSet) { 11419 return None; 11420 } 11421 11422 Selector Sel = Message->getSelector(); 11423 11424 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 11425 if (!MKOpt) { 11426 return None; 11427 } 11428 11429 NSAPI::NSSetMethodKind MK = *MKOpt; 11430 11431 switch (MK) { 11432 case NSAPI::NSMutableSet_addObject: 11433 case NSAPI::NSOrderedSet_setObjectAtIndex: 11434 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 11435 case NSAPI::NSOrderedSet_insertObjectAtIndex: 11436 return 0; 11437 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 11438 return 1; 11439 } 11440 11441 return None; 11442 } 11443 11444 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 11445 if (!Message->isInstanceMessage()) { 11446 return; 11447 } 11448 11449 Optional<int> ArgOpt; 11450 11451 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 11452 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 11453 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 11454 return; 11455 } 11456 11457 int ArgIndex = *ArgOpt; 11458 11459 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 11460 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 11461 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 11462 } 11463 11464 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 11465 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11466 if (ArgRE->isObjCSelfExpr()) { 11467 Diag(Message->getSourceRange().getBegin(), 11468 diag::warn_objc_circular_container) 11469 << ArgRE->getDecl()->getName() << StringRef("super"); 11470 } 11471 } 11472 } else { 11473 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 11474 11475 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 11476 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 11477 } 11478 11479 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 11480 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11481 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 11482 ValueDecl *Decl = ReceiverRE->getDecl(); 11483 Diag(Message->getSourceRange().getBegin(), 11484 diag::warn_objc_circular_container) 11485 << Decl->getName() << Decl->getName(); 11486 if (!ArgRE->isObjCSelfExpr()) { 11487 Diag(Decl->getLocation(), 11488 diag::note_objc_circular_container_declared_here) 11489 << Decl->getName(); 11490 } 11491 } 11492 } 11493 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 11494 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 11495 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 11496 ObjCIvarDecl *Decl = IvarRE->getDecl(); 11497 Diag(Message->getSourceRange().getBegin(), 11498 diag::warn_objc_circular_container) 11499 << Decl->getName() << Decl->getName(); 11500 Diag(Decl->getLocation(), 11501 diag::note_objc_circular_container_declared_here) 11502 << Decl->getName(); 11503 } 11504 } 11505 } 11506 } 11507 } 11508 11509 /// Check a message send to see if it's likely to cause a retain cycle. 11510 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11511 // Only check instance methods whose selector looks like a setter. 11512 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 11513 return; 11514 11515 // Try to find a variable that the receiver is strongly owned by. 11516 RetainCycleOwner owner; 11517 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 11518 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 11519 return; 11520 } else { 11521 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 11522 owner.Variable = getCurMethodDecl()->getSelfDecl(); 11523 owner.Loc = msg->getSuperLoc(); 11524 owner.Range = msg->getSuperLoc(); 11525 } 11526 11527 // Check whether the receiver is captured by any of the arguments. 11528 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 11529 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 11530 return diagnoseRetainCycle(*this, capturer, owner); 11531 } 11532 11533 /// Check a property assign to see if it's likely to cause a retain cycle. 11534 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 11535 RetainCycleOwner owner; 11536 if (!findRetainCycleOwner(*this, receiver, owner)) 11537 return; 11538 11539 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 11540 diagnoseRetainCycle(*this, capturer, owner); 11541 } 11542 11543 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 11544 RetainCycleOwner Owner; 11545 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 11546 return; 11547 11548 // Because we don't have an expression for the variable, we have to set the 11549 // location explicitly here. 11550 Owner.Loc = Var->getLocation(); 11551 Owner.Range = Var->getSourceRange(); 11552 11553 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 11554 diagnoseRetainCycle(*this, Capturer, Owner); 11555 } 11556 11557 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 11558 Expr *RHS, bool isProperty) { 11559 // Check if RHS is an Objective-C object literal, which also can get 11560 // immediately zapped in a weak reference. Note that we explicitly 11561 // allow ObjCStringLiterals, since those are designed to never really die. 11562 RHS = RHS->IgnoreParenImpCasts(); 11563 11564 // This enum needs to match with the 'select' in 11565 // warn_objc_arc_literal_assign (off-by-1). 11566 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 11567 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 11568 return false; 11569 11570 S.Diag(Loc, diag::warn_arc_literal_assign) 11571 << (unsigned) Kind 11572 << (isProperty ? 0 : 1) 11573 << RHS->getSourceRange(); 11574 11575 return true; 11576 } 11577 11578 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 11579 Qualifiers::ObjCLifetime LT, 11580 Expr *RHS, bool isProperty) { 11581 // Strip off any implicit cast added to get to the one ARC-specific. 11582 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11583 if (cast->getCastKind() == CK_ARCConsumeObject) { 11584 S.Diag(Loc, diag::warn_arc_retained_assign) 11585 << (LT == Qualifiers::OCL_ExplicitNone) 11586 << (isProperty ? 0 : 1) 11587 << RHS->getSourceRange(); 11588 return true; 11589 } 11590 RHS = cast->getSubExpr(); 11591 } 11592 11593 if (LT == Qualifiers::OCL_Weak && 11594 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11595 return true; 11596 11597 return false; 11598 } 11599 11600 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11601 QualType LHS, Expr *RHS) { 11602 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11603 11604 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11605 return false; 11606 11607 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11608 return true; 11609 11610 return false; 11611 } 11612 11613 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11614 Expr *LHS, Expr *RHS) { 11615 QualType LHSType; 11616 // PropertyRef on LHS type need be directly obtained from 11617 // its declaration as it has a PseudoType. 11618 ObjCPropertyRefExpr *PRE 11619 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11620 if (PRE && !PRE->isImplicitProperty()) { 11621 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11622 if (PD) 11623 LHSType = PD->getType(); 11624 } 11625 11626 if (LHSType.isNull()) 11627 LHSType = LHS->getType(); 11628 11629 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11630 11631 if (LT == Qualifiers::OCL_Weak) { 11632 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11633 getCurFunction()->markSafeWeakUse(LHS); 11634 } 11635 11636 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11637 return; 11638 11639 // FIXME. Check for other life times. 11640 if (LT != Qualifiers::OCL_None) 11641 return; 11642 11643 if (PRE) { 11644 if (PRE->isImplicitProperty()) 11645 return; 11646 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11647 if (!PD) 11648 return; 11649 11650 unsigned Attributes = PD->getPropertyAttributes(); 11651 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11652 // when 'assign' attribute was not explicitly specified 11653 // by user, ignore it and rely on property type itself 11654 // for lifetime info. 11655 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11656 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11657 LHSType->isObjCRetainableType()) 11658 return; 11659 11660 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11661 if (cast->getCastKind() == CK_ARCConsumeObject) { 11662 Diag(Loc, diag::warn_arc_retained_property_assign) 11663 << RHS->getSourceRange(); 11664 return; 11665 } 11666 RHS = cast->getSubExpr(); 11667 } 11668 } 11669 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11670 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11671 return; 11672 } 11673 } 11674 } 11675 11676 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11677 11678 namespace { 11679 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11680 SourceLocation StmtLoc, 11681 const NullStmt *Body) { 11682 // Do not warn if the body is a macro that expands to nothing, e.g: 11683 // 11684 // #define CALL(x) 11685 // if (condition) 11686 // CALL(0); 11687 // 11688 if (Body->hasLeadingEmptyMacro()) 11689 return false; 11690 11691 // Get line numbers of statement and body. 11692 bool StmtLineInvalid; 11693 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11694 &StmtLineInvalid); 11695 if (StmtLineInvalid) 11696 return false; 11697 11698 bool BodyLineInvalid; 11699 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11700 &BodyLineInvalid); 11701 if (BodyLineInvalid) 11702 return false; 11703 11704 // Warn if null statement and body are on the same line. 11705 if (StmtLine != BodyLine) 11706 return false; 11707 11708 return true; 11709 } 11710 } // end anonymous namespace 11711 11712 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11713 const Stmt *Body, 11714 unsigned DiagID) { 11715 // Since this is a syntactic check, don't emit diagnostic for template 11716 // instantiations, this just adds noise. 11717 if (CurrentInstantiationScope) 11718 return; 11719 11720 // The body should be a null statement. 11721 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11722 if (!NBody) 11723 return; 11724 11725 // Do the usual checks. 11726 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11727 return; 11728 11729 Diag(NBody->getSemiLoc(), DiagID); 11730 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11731 } 11732 11733 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11734 const Stmt *PossibleBody) { 11735 assert(!CurrentInstantiationScope); // Ensured by caller 11736 11737 SourceLocation StmtLoc; 11738 const Stmt *Body; 11739 unsigned DiagID; 11740 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11741 StmtLoc = FS->getRParenLoc(); 11742 Body = FS->getBody(); 11743 DiagID = diag::warn_empty_for_body; 11744 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11745 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11746 Body = WS->getBody(); 11747 DiagID = diag::warn_empty_while_body; 11748 } else 11749 return; // Neither `for' nor `while'. 11750 11751 // The body should be a null statement. 11752 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11753 if (!NBody) 11754 return; 11755 11756 // Skip expensive checks if diagnostic is disabled. 11757 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11758 return; 11759 11760 // Do the usual checks. 11761 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11762 return; 11763 11764 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11765 // noise level low, emit diagnostics only if for/while is followed by a 11766 // CompoundStmt, e.g.: 11767 // for (int i = 0; i < n; i++); 11768 // { 11769 // a(i); 11770 // } 11771 // or if for/while is followed by a statement with more indentation 11772 // than for/while itself: 11773 // for (int i = 0; i < n; i++); 11774 // a(i); 11775 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11776 if (!ProbableTypo) { 11777 bool BodyColInvalid; 11778 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11779 PossibleBody->getLocStart(), 11780 &BodyColInvalid); 11781 if (BodyColInvalid) 11782 return; 11783 11784 bool StmtColInvalid; 11785 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11786 S->getLocStart(), 11787 &StmtColInvalid); 11788 if (StmtColInvalid) 11789 return; 11790 11791 if (BodyCol > StmtCol) 11792 ProbableTypo = true; 11793 } 11794 11795 if (ProbableTypo) { 11796 Diag(NBody->getSemiLoc(), DiagID); 11797 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11798 } 11799 } 11800 11801 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11802 11803 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11804 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11805 SourceLocation OpLoc) { 11806 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11807 return; 11808 11809 if (inTemplateInstantiation()) 11810 return; 11811 11812 // Strip parens and casts away. 11813 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11814 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11815 11816 // Check for a call expression 11817 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11818 if (!CE || CE->getNumArgs() != 1) 11819 return; 11820 11821 // Check for a call to std::move 11822 if (!CE->isCallToStdMove()) 11823 return; 11824 11825 // Get argument from std::move 11826 RHSExpr = CE->getArg(0); 11827 11828 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11829 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11830 11831 // Two DeclRefExpr's, check that the decls are the same. 11832 if (LHSDeclRef && RHSDeclRef) { 11833 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11834 return; 11835 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11836 RHSDeclRef->getDecl()->getCanonicalDecl()) 11837 return; 11838 11839 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11840 << LHSExpr->getSourceRange() 11841 << RHSExpr->getSourceRange(); 11842 return; 11843 } 11844 11845 // Member variables require a different approach to check for self moves. 11846 // MemberExpr's are the same if every nested MemberExpr refers to the same 11847 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11848 // the base Expr's are CXXThisExpr's. 11849 const Expr *LHSBase = LHSExpr; 11850 const Expr *RHSBase = RHSExpr; 11851 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11852 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11853 if (!LHSME || !RHSME) 11854 return; 11855 11856 while (LHSME && RHSME) { 11857 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11858 RHSME->getMemberDecl()->getCanonicalDecl()) 11859 return; 11860 11861 LHSBase = LHSME->getBase(); 11862 RHSBase = RHSME->getBase(); 11863 LHSME = dyn_cast<MemberExpr>(LHSBase); 11864 RHSME = dyn_cast<MemberExpr>(RHSBase); 11865 } 11866 11867 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11868 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11869 if (LHSDeclRef && RHSDeclRef) { 11870 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11871 return; 11872 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11873 RHSDeclRef->getDecl()->getCanonicalDecl()) 11874 return; 11875 11876 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11877 << LHSExpr->getSourceRange() 11878 << RHSExpr->getSourceRange(); 11879 return; 11880 } 11881 11882 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11883 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11884 << LHSExpr->getSourceRange() 11885 << RHSExpr->getSourceRange(); 11886 } 11887 11888 //===--- Layout compatibility ----------------------------------------------// 11889 11890 namespace { 11891 11892 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11893 11894 /// \brief Check if two enumeration types are layout-compatible. 11895 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11896 // C++11 [dcl.enum] p8: 11897 // Two enumeration types are layout-compatible if they have the same 11898 // underlying type. 11899 return ED1->isComplete() && ED2->isComplete() && 11900 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11901 } 11902 11903 /// \brief Check if two fields are layout-compatible. 11904 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11905 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11906 return false; 11907 11908 if (Field1->isBitField() != Field2->isBitField()) 11909 return false; 11910 11911 if (Field1->isBitField()) { 11912 // Make sure that the bit-fields are the same length. 11913 unsigned Bits1 = Field1->getBitWidthValue(C); 11914 unsigned Bits2 = Field2->getBitWidthValue(C); 11915 11916 if (Bits1 != Bits2) 11917 return false; 11918 } 11919 11920 return true; 11921 } 11922 11923 /// \brief Check if two standard-layout structs are layout-compatible. 11924 /// (C++11 [class.mem] p17) 11925 bool isLayoutCompatibleStruct(ASTContext &C, 11926 RecordDecl *RD1, 11927 RecordDecl *RD2) { 11928 // If both records are C++ classes, check that base classes match. 11929 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11930 // If one of records is a CXXRecordDecl we are in C++ mode, 11931 // thus the other one is a CXXRecordDecl, too. 11932 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11933 // Check number of base classes. 11934 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11935 return false; 11936 11937 // Check the base classes. 11938 for (CXXRecordDecl::base_class_const_iterator 11939 Base1 = D1CXX->bases_begin(), 11940 BaseEnd1 = D1CXX->bases_end(), 11941 Base2 = D2CXX->bases_begin(); 11942 Base1 != BaseEnd1; 11943 ++Base1, ++Base2) { 11944 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11945 return false; 11946 } 11947 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11948 // If only RD2 is a C++ class, it should have zero base classes. 11949 if (D2CXX->getNumBases() > 0) 11950 return false; 11951 } 11952 11953 // Check the fields. 11954 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11955 Field2End = RD2->field_end(), 11956 Field1 = RD1->field_begin(), 11957 Field1End = RD1->field_end(); 11958 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11959 if (!isLayoutCompatible(C, *Field1, *Field2)) 11960 return false; 11961 } 11962 if (Field1 != Field1End || Field2 != Field2End) 11963 return false; 11964 11965 return true; 11966 } 11967 11968 /// \brief Check if two standard-layout unions are layout-compatible. 11969 /// (C++11 [class.mem] p18) 11970 bool isLayoutCompatibleUnion(ASTContext &C, 11971 RecordDecl *RD1, 11972 RecordDecl *RD2) { 11973 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11974 for (auto *Field2 : RD2->fields()) 11975 UnmatchedFields.insert(Field2); 11976 11977 for (auto *Field1 : RD1->fields()) { 11978 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11979 I = UnmatchedFields.begin(), 11980 E = UnmatchedFields.end(); 11981 11982 for ( ; I != E; ++I) { 11983 if (isLayoutCompatible(C, Field1, *I)) { 11984 bool Result = UnmatchedFields.erase(*I); 11985 (void) Result; 11986 assert(Result); 11987 break; 11988 } 11989 } 11990 if (I == E) 11991 return false; 11992 } 11993 11994 return UnmatchedFields.empty(); 11995 } 11996 11997 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11998 if (RD1->isUnion() != RD2->isUnion()) 11999 return false; 12000 12001 if (RD1->isUnion()) 12002 return isLayoutCompatibleUnion(C, RD1, RD2); 12003 else 12004 return isLayoutCompatibleStruct(C, RD1, RD2); 12005 } 12006 12007 /// \brief Check if two types are layout-compatible in C++11 sense. 12008 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 12009 if (T1.isNull() || T2.isNull()) 12010 return false; 12011 12012 // C++11 [basic.types] p11: 12013 // If two types T1 and T2 are the same type, then T1 and T2 are 12014 // layout-compatible types. 12015 if (C.hasSameType(T1, T2)) 12016 return true; 12017 12018 T1 = T1.getCanonicalType().getUnqualifiedType(); 12019 T2 = T2.getCanonicalType().getUnqualifiedType(); 12020 12021 const Type::TypeClass TC1 = T1->getTypeClass(); 12022 const Type::TypeClass TC2 = T2->getTypeClass(); 12023 12024 if (TC1 != TC2) 12025 return false; 12026 12027 if (TC1 == Type::Enum) { 12028 return isLayoutCompatible(C, 12029 cast<EnumType>(T1)->getDecl(), 12030 cast<EnumType>(T2)->getDecl()); 12031 } else if (TC1 == Type::Record) { 12032 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 12033 return false; 12034 12035 return isLayoutCompatible(C, 12036 cast<RecordType>(T1)->getDecl(), 12037 cast<RecordType>(T2)->getDecl()); 12038 } 12039 12040 return false; 12041 } 12042 } // end anonymous namespace 12043 12044 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 12045 12046 namespace { 12047 /// \brief Given a type tag expression find the type tag itself. 12048 /// 12049 /// \param TypeExpr Type tag expression, as it appears in user's code. 12050 /// 12051 /// \param VD Declaration of an identifier that appears in a type tag. 12052 /// 12053 /// \param MagicValue Type tag magic value. 12054 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 12055 const ValueDecl **VD, uint64_t *MagicValue) { 12056 while(true) { 12057 if (!TypeExpr) 12058 return false; 12059 12060 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 12061 12062 switch (TypeExpr->getStmtClass()) { 12063 case Stmt::UnaryOperatorClass: { 12064 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 12065 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 12066 TypeExpr = UO->getSubExpr(); 12067 continue; 12068 } 12069 return false; 12070 } 12071 12072 case Stmt::DeclRefExprClass: { 12073 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 12074 *VD = DRE->getDecl(); 12075 return true; 12076 } 12077 12078 case Stmt::IntegerLiteralClass: { 12079 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 12080 llvm::APInt MagicValueAPInt = IL->getValue(); 12081 if (MagicValueAPInt.getActiveBits() <= 64) { 12082 *MagicValue = MagicValueAPInt.getZExtValue(); 12083 return true; 12084 } else 12085 return false; 12086 } 12087 12088 case Stmt::BinaryConditionalOperatorClass: 12089 case Stmt::ConditionalOperatorClass: { 12090 const AbstractConditionalOperator *ACO = 12091 cast<AbstractConditionalOperator>(TypeExpr); 12092 bool Result; 12093 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 12094 if (Result) 12095 TypeExpr = ACO->getTrueExpr(); 12096 else 12097 TypeExpr = ACO->getFalseExpr(); 12098 continue; 12099 } 12100 return false; 12101 } 12102 12103 case Stmt::BinaryOperatorClass: { 12104 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 12105 if (BO->getOpcode() == BO_Comma) { 12106 TypeExpr = BO->getRHS(); 12107 continue; 12108 } 12109 return false; 12110 } 12111 12112 default: 12113 return false; 12114 } 12115 } 12116 } 12117 12118 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 12119 /// 12120 /// \param TypeExpr Expression that specifies a type tag. 12121 /// 12122 /// \param MagicValues Registered magic values. 12123 /// 12124 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12125 /// kind. 12126 /// 12127 /// \param TypeInfo Information about the corresponding C type. 12128 /// 12129 /// \returns true if the corresponding C type was found. 12130 bool GetMatchingCType( 12131 const IdentifierInfo *ArgumentKind, 12132 const Expr *TypeExpr, const ASTContext &Ctx, 12133 const llvm::DenseMap<Sema::TypeTagMagicValue, 12134 Sema::TypeTagData> *MagicValues, 12135 bool &FoundWrongKind, 12136 Sema::TypeTagData &TypeInfo) { 12137 FoundWrongKind = false; 12138 12139 // Variable declaration that has type_tag_for_datatype attribute. 12140 const ValueDecl *VD = nullptr; 12141 12142 uint64_t MagicValue; 12143 12144 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12145 return false; 12146 12147 if (VD) { 12148 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12149 if (I->getArgumentKind() != ArgumentKind) { 12150 FoundWrongKind = true; 12151 return false; 12152 } 12153 TypeInfo.Type = I->getMatchingCType(); 12154 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12155 TypeInfo.MustBeNull = I->getMustBeNull(); 12156 return true; 12157 } 12158 return false; 12159 } 12160 12161 if (!MagicValues) 12162 return false; 12163 12164 llvm::DenseMap<Sema::TypeTagMagicValue, 12165 Sema::TypeTagData>::const_iterator I = 12166 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12167 if (I == MagicValues->end()) 12168 return false; 12169 12170 TypeInfo = I->second; 12171 return true; 12172 } 12173 } // end anonymous namespace 12174 12175 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12176 uint64_t MagicValue, QualType Type, 12177 bool LayoutCompatible, 12178 bool MustBeNull) { 12179 if (!TypeTagForDatatypeMagicValues) 12180 TypeTagForDatatypeMagicValues.reset( 12181 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12182 12183 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12184 (*TypeTagForDatatypeMagicValues)[Magic] = 12185 TypeTagData(Type, LayoutCompatible, MustBeNull); 12186 } 12187 12188 namespace { 12189 bool IsSameCharType(QualType T1, QualType T2) { 12190 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12191 if (!BT1) 12192 return false; 12193 12194 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12195 if (!BT2) 12196 return false; 12197 12198 BuiltinType::Kind T1Kind = BT1->getKind(); 12199 BuiltinType::Kind T2Kind = BT2->getKind(); 12200 12201 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12202 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12203 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12204 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12205 } 12206 } // end anonymous namespace 12207 12208 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12209 const Expr * const *ExprArgs) { 12210 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12211 bool IsPointerAttr = Attr->getIsPointer(); 12212 12213 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 12214 bool FoundWrongKind; 12215 TypeTagData TypeInfo; 12216 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12217 TypeTagForDatatypeMagicValues.get(), 12218 FoundWrongKind, TypeInfo)) { 12219 if (FoundWrongKind) 12220 Diag(TypeTagExpr->getExprLoc(), 12221 diag::warn_type_tag_for_datatype_wrong_kind) 12222 << TypeTagExpr->getSourceRange(); 12223 return; 12224 } 12225 12226 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 12227 if (IsPointerAttr) { 12228 // Skip implicit cast of pointer to `void *' (as a function argument). 12229 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12230 if (ICE->getType()->isVoidPointerType() && 12231 ICE->getCastKind() == CK_BitCast) 12232 ArgumentExpr = ICE->getSubExpr(); 12233 } 12234 QualType ArgumentType = ArgumentExpr->getType(); 12235 12236 // Passing a `void*' pointer shouldn't trigger a warning. 12237 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12238 return; 12239 12240 if (TypeInfo.MustBeNull) { 12241 // Type tag with matching void type requires a null pointer. 12242 if (!ArgumentExpr->isNullPointerConstant(Context, 12243 Expr::NPC_ValueDependentIsNotNull)) { 12244 Diag(ArgumentExpr->getExprLoc(), 12245 diag::warn_type_safety_null_pointer_required) 12246 << ArgumentKind->getName() 12247 << ArgumentExpr->getSourceRange() 12248 << TypeTagExpr->getSourceRange(); 12249 } 12250 return; 12251 } 12252 12253 QualType RequiredType = TypeInfo.Type; 12254 if (IsPointerAttr) 12255 RequiredType = Context.getPointerType(RequiredType); 12256 12257 bool mismatch = false; 12258 if (!TypeInfo.LayoutCompatible) { 12259 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12260 12261 // C++11 [basic.fundamental] p1: 12262 // Plain char, signed char, and unsigned char are three distinct types. 12263 // 12264 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12265 // char' depending on the current char signedness mode. 12266 if (mismatch) 12267 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12268 RequiredType->getPointeeType())) || 12269 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12270 mismatch = false; 12271 } else 12272 if (IsPointerAttr) 12273 mismatch = !isLayoutCompatible(Context, 12274 ArgumentType->getPointeeType(), 12275 RequiredType->getPointeeType()); 12276 else 12277 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12278 12279 if (mismatch) 12280 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12281 << ArgumentType << ArgumentKind 12282 << TypeInfo.LayoutCompatible << RequiredType 12283 << ArgumentExpr->getSourceRange() 12284 << TypeTagExpr->getSourceRange(); 12285 } 12286 12287 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12288 CharUnits Alignment) { 12289 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12290 } 12291 12292 void Sema::DiagnoseMisalignedMembers() { 12293 for (MisalignedMember &m : MisalignedMembers) { 12294 const NamedDecl *ND = m.RD; 12295 if (ND->getName().empty()) { 12296 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12297 ND = TD; 12298 } 12299 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12300 << m.MD << ND << m.E->getSourceRange(); 12301 } 12302 MisalignedMembers.clear(); 12303 } 12304 12305 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12306 E = E->IgnoreParens(); 12307 if (!T->isPointerType() && !T->isIntegerType()) 12308 return; 12309 if (isa<UnaryOperator>(E) && 12310 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 12311 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 12312 if (isa<MemberExpr>(Op)) { 12313 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 12314 MisalignedMember(Op)); 12315 if (MA != MisalignedMembers.end() && 12316 (T->isIntegerType() || 12317 (T->isPointerType() && 12318 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment))) 12319 MisalignedMembers.erase(MA); 12320 } 12321 } 12322 } 12323 12324 void Sema::RefersToMemberWithReducedAlignment( 12325 Expr *E, 12326 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12327 Action) { 12328 const auto *ME = dyn_cast<MemberExpr>(E); 12329 if (!ME) 12330 return; 12331 12332 // No need to check expressions with an __unaligned-qualified type. 12333 if (E->getType().getQualifiers().hasUnaligned()) 12334 return; 12335 12336 // For a chain of MemberExpr like "a.b.c.d" this list 12337 // will keep FieldDecl's like [d, c, b]. 12338 SmallVector<FieldDecl *, 4> ReverseMemberChain; 12339 const MemberExpr *TopME = nullptr; 12340 bool AnyIsPacked = false; 12341 do { 12342 QualType BaseType = ME->getBase()->getType(); 12343 if (ME->isArrow()) 12344 BaseType = BaseType->getPointeeType(); 12345 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 12346 if (RD->isInvalidDecl()) 12347 return; 12348 12349 ValueDecl *MD = ME->getMemberDecl(); 12350 auto *FD = dyn_cast<FieldDecl>(MD); 12351 // We do not care about non-data members. 12352 if (!FD || FD->isInvalidDecl()) 12353 return; 12354 12355 AnyIsPacked = 12356 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 12357 ReverseMemberChain.push_back(FD); 12358 12359 TopME = ME; 12360 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 12361 } while (ME); 12362 assert(TopME && "We did not compute a topmost MemberExpr!"); 12363 12364 // Not the scope of this diagnostic. 12365 if (!AnyIsPacked) 12366 return; 12367 12368 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 12369 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 12370 // TODO: The innermost base of the member expression may be too complicated. 12371 // For now, just disregard these cases. This is left for future 12372 // improvement. 12373 if (!DRE && !isa<CXXThisExpr>(TopBase)) 12374 return; 12375 12376 // Alignment expected by the whole expression. 12377 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 12378 12379 // No need to do anything else with this case. 12380 if (ExpectedAlignment.isOne()) 12381 return; 12382 12383 // Synthesize offset of the whole access. 12384 CharUnits Offset; 12385 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 12386 I++) { 12387 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 12388 } 12389 12390 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 12391 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 12392 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 12393 12394 // The base expression of the innermost MemberExpr may give 12395 // stronger guarantees than the class containing the member. 12396 if (DRE && !TopME->isArrow()) { 12397 const ValueDecl *VD = DRE->getDecl(); 12398 if (!VD->getType()->isReferenceType()) 12399 CompleteObjectAlignment = 12400 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 12401 } 12402 12403 // Check if the synthesized offset fulfills the alignment. 12404 if (Offset % ExpectedAlignment != 0 || 12405 // It may fulfill the offset it but the effective alignment may still be 12406 // lower than the expected expression alignment. 12407 CompleteObjectAlignment < ExpectedAlignment) { 12408 // If this happens, we want to determine a sensible culprit of this. 12409 // Intuitively, watching the chain of member expressions from right to 12410 // left, we start with the required alignment (as required by the field 12411 // type) but some packed attribute in that chain has reduced the alignment. 12412 // It may happen that another packed structure increases it again. But if 12413 // we are here such increase has not been enough. So pointing the first 12414 // FieldDecl that either is packed or else its RecordDecl is, 12415 // seems reasonable. 12416 FieldDecl *FD = nullptr; 12417 CharUnits Alignment; 12418 for (FieldDecl *FDI : ReverseMemberChain) { 12419 if (FDI->hasAttr<PackedAttr>() || 12420 FDI->getParent()->hasAttr<PackedAttr>()) { 12421 FD = FDI; 12422 Alignment = std::min( 12423 Context.getTypeAlignInChars(FD->getType()), 12424 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 12425 break; 12426 } 12427 } 12428 assert(FD && "We did not find a packed FieldDecl!"); 12429 Action(E, FD->getParent(), FD, Alignment); 12430 } 12431 } 12432 12433 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 12434 using namespace std::placeholders; 12435 RefersToMemberWithReducedAlignment( 12436 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 12437 _2, _3, _4)); 12438 } 12439 12440