1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements extra semantic analysis beyond what is enforced 11 // by the C type system. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CharUnits.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/EvaluatedExprVisitor.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/ExprObjC.h" 23 #include "clang/AST/ExprOpenMP.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/AST/StmtObjC.h" 26 #include "clang/Analysis/Analyses/FormatString.h" 27 #include "clang/Basic/CharInfo.h" 28 #include "clang/Basic/TargetBuiltins.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/ScopeInfo.h" 34 #include "clang/Sema/Sema.h" 35 #include "clang/Sema/SemaInternal.h" 36 #include "llvm/ADT/STLExtras.h" 37 #include "llvm/ADT/SmallBitVector.h" 38 #include "llvm/ADT/SmallString.h" 39 #include "llvm/Support/ConvertUTF.h" 40 #include "llvm/Support/Format.h" 41 #include "llvm/Support/Locale.h" 42 #include "llvm/Support/raw_ostream.h" 43 44 using namespace clang; 45 using namespace sema; 46 47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 48 unsigned ByteNo) const { 49 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 50 Context.getTargetInfo()); 51 } 52 53 /// Checks that a call expression's argument count is the desired number. 54 /// This is useful when doing custom type-checking. Returns true on error. 55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 56 unsigned argCount = call->getNumArgs(); 57 if (argCount == desiredArgCount) return false; 58 59 if (argCount < desiredArgCount) 60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 61 << 0 /*function call*/ << desiredArgCount << argCount 62 << call->getSourceRange(); 63 64 // Highlight all the excess arguments. 65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 66 call->getArg(argCount - 1)->getLocEnd()); 67 68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 69 << 0 /*function call*/ << desiredArgCount << argCount 70 << call->getArg(1)->getSourceRange(); 71 } 72 73 /// Check that the first argument to __builtin_annotation is an integer 74 /// and the second argument is a non-wide string literal. 75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 76 if (checkArgCount(S, TheCall, 2)) 77 return true; 78 79 // First argument should be an integer. 80 Expr *ValArg = TheCall->getArg(0); 81 QualType Ty = ValArg->getType(); 82 if (!Ty->isIntegerType()) { 83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 84 << ValArg->getSourceRange(); 85 return true; 86 } 87 88 // Second argument should be a constant string. 89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 91 if (!Literal || !Literal->isAscii()) { 92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 93 << StrArg->getSourceRange(); 94 return true; 95 } 96 97 TheCall->setType(Ty); 98 return false; 99 } 100 101 /// Check that the argument to __builtin_addressof is a glvalue, and set the 102 /// result type to the corresponding pointer type. 103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 104 if (checkArgCount(S, TheCall, 1)) 105 return true; 106 107 ExprResult Arg(TheCall->getArg(0)); 108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 109 if (ResultType.isNull()) 110 return true; 111 112 TheCall->setArg(0, Arg.get()); 113 TheCall->setType(ResultType); 114 return false; 115 } 116 117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 118 if (checkArgCount(S, TheCall, 3)) 119 return true; 120 121 // First two arguments should be integers. 122 for (unsigned I = 0; I < 2; ++I) { 123 Expr *Arg = TheCall->getArg(I); 124 QualType Ty = Arg->getType(); 125 if (!Ty->isIntegerType()) { 126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 127 << Ty << Arg->getSourceRange(); 128 return true; 129 } 130 } 131 132 // Third argument should be a pointer to a non-const integer. 133 // IRGen correctly handles volatile, restrict, and address spaces, and 134 // the other qualifiers aren't possible. 135 { 136 Expr *Arg = TheCall->getArg(2); 137 QualType Ty = Arg->getType(); 138 const auto *PtrTy = Ty->getAs<PointerType>(); 139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 140 !PtrTy->getPointeeType().isConstQualified())) { 141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 142 << Ty << Arg->getSourceRange(); 143 return true; 144 } 145 } 146 147 return false; 148 } 149 150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 151 CallExpr *TheCall, unsigned SizeIdx, 152 unsigned DstSizeIdx) { 153 if (TheCall->getNumArgs() <= SizeIdx || 154 TheCall->getNumArgs() <= DstSizeIdx) 155 return; 156 157 const Expr *SizeArg = TheCall->getArg(SizeIdx); 158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 159 160 llvm::APSInt Size, DstSize; 161 162 // find out if both sizes are known at compile time 163 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 165 return; 166 167 if (Size.ule(DstSize)) 168 return; 169 170 // confirmed overflow so generate the diagnostic. 171 IdentifierInfo *FnName = FDecl->getIdentifier(); 172 SourceLocation SL = TheCall->getLocStart(); 173 SourceRange SR = TheCall->getSourceRange(); 174 175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 176 } 177 178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 179 if (checkArgCount(S, BuiltinCall, 2)) 180 return true; 181 182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 184 Expr *Call = BuiltinCall->getArg(0); 185 Expr *Chain = BuiltinCall->getArg(1); 186 187 if (Call->getStmtClass() != Stmt::CallExprClass) { 188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 189 << Call->getSourceRange(); 190 return true; 191 } 192 193 auto CE = cast<CallExpr>(Call); 194 if (CE->getCallee()->getType()->isBlockPointerType()) { 195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 196 << Call->getSourceRange(); 197 return true; 198 } 199 200 const Decl *TargetDecl = CE->getCalleeDecl(); 201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 202 if (FD->getBuiltinID()) { 203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 204 << Call->getSourceRange(); 205 return true; 206 } 207 208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 210 << Call->getSourceRange(); 211 return true; 212 } 213 214 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 215 if (ChainResult.isInvalid()) 216 return true; 217 if (!ChainResult.get()->getType()->isPointerType()) { 218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 219 << Chain->getSourceRange(); 220 return true; 221 } 222 223 QualType ReturnTy = CE->getCallReturnType(S.Context); 224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 225 QualType BuiltinTy = S.Context.getFunctionType( 226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 228 229 Builtin = 230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 231 232 BuiltinCall->setType(CE->getType()); 233 BuiltinCall->setValueKind(CE->getValueKind()); 234 BuiltinCall->setObjectKind(CE->getObjectKind()); 235 BuiltinCall->setCallee(Builtin); 236 BuiltinCall->setArg(1, ChainResult.get()); 237 238 return false; 239 } 240 241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 242 Scope::ScopeFlags NeededScopeFlags, 243 unsigned DiagID) { 244 // Scopes aren't available during instantiation. Fortunately, builtin 245 // functions cannot be template args so they cannot be formed through template 246 // instantiation. Therefore checking once during the parse is sufficient. 247 if (SemaRef.inTemplateInstantiation()) 248 return false; 249 250 Scope *S = SemaRef.getCurScope(); 251 while (S && !S->isSEHExceptScope()) 252 S = S->getParent(); 253 if (!S || !(S->getFlags() & NeededScopeFlags)) { 254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 255 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 256 << DRE->getDecl()->getIdentifier(); 257 return true; 258 } 259 260 return false; 261 } 262 263 static inline bool isBlockPointer(Expr *Arg) { 264 return Arg->getType()->isBlockPointerType(); 265 } 266 267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 268 /// void*, which is a requirement of device side enqueue. 269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 270 const BlockPointerType *BPT = 271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 272 ArrayRef<QualType> Params = 273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 274 unsigned ArgCounter = 0; 275 bool IllegalParams = false; 276 // Iterate through the block parameters until either one is found that is not 277 // a local void*, or the block is valid. 278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 279 I != E; ++I, ++ArgCounter) { 280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 281 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 282 LangAS::opencl_local) { 283 // Get the location of the error. If a block literal has been passed 284 // (BlockExpr) then we can point straight to the offending argument, 285 // else we just point to the variable reference. 286 SourceLocation ErrorLoc; 287 if (isa<BlockExpr>(BlockArg)) { 288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 290 } else if (isa<DeclRefExpr>(BlockArg)) { 291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 292 } 293 S.Diag(ErrorLoc, 294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 295 IllegalParams = true; 296 } 297 } 298 299 return IllegalParams; 300 } 301 302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 303 /// get_kernel_work_group_size 304 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 306 if (checkArgCount(S, TheCall, 1)) 307 return true; 308 309 Expr *BlockArg = TheCall->getArg(0); 310 if (!isBlockPointer(BlockArg)) { 311 S.Diag(BlockArg->getLocStart(), 312 diag::err_opencl_builtin_expected_type) 313 << TheCall->getDirectCallee() << "block"; 314 return true; 315 } 316 return checkOpenCLBlockArgs(S, BlockArg); 317 } 318 319 /// Diagnose integer type and any valid implicit conversion to it. 320 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 321 const QualType &IntType); 322 323 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 324 unsigned Start, unsigned End) { 325 bool IllegalParams = false; 326 for (unsigned I = Start; I <= End; ++I) 327 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 328 S.Context.getSizeType()); 329 return IllegalParams; 330 } 331 332 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 333 /// 'local void*' parameter of passed block. 334 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 335 Expr *BlockArg, 336 unsigned NumNonVarArgs) { 337 const BlockPointerType *BPT = 338 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 339 unsigned NumBlockParams = 340 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 341 unsigned TotalNumArgs = TheCall->getNumArgs(); 342 343 // For each argument passed to the block, a corresponding uint needs to 344 // be passed to describe the size of the local memory. 345 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 346 S.Diag(TheCall->getLocStart(), 347 diag::err_opencl_enqueue_kernel_local_size_args); 348 return true; 349 } 350 351 // Check that the sizes of the local memory are specified by integers. 352 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 353 TotalNumArgs - 1); 354 } 355 356 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 357 /// overload formats specified in Table 6.13.17.1. 358 /// int enqueue_kernel(queue_t queue, 359 /// kernel_enqueue_flags_t flags, 360 /// const ndrange_t ndrange, 361 /// void (^block)(void)) 362 /// int enqueue_kernel(queue_t queue, 363 /// kernel_enqueue_flags_t flags, 364 /// const ndrange_t ndrange, 365 /// uint num_events_in_wait_list, 366 /// clk_event_t *event_wait_list, 367 /// clk_event_t *event_ret, 368 /// void (^block)(void)) 369 /// int enqueue_kernel(queue_t queue, 370 /// kernel_enqueue_flags_t flags, 371 /// const ndrange_t ndrange, 372 /// void (^block)(local void*, ...), 373 /// uint size0, ...) 374 /// int enqueue_kernel(queue_t queue, 375 /// kernel_enqueue_flags_t flags, 376 /// const ndrange_t ndrange, 377 /// uint num_events_in_wait_list, 378 /// clk_event_t *event_wait_list, 379 /// clk_event_t *event_ret, 380 /// void (^block)(local void*, ...), 381 /// uint size0, ...) 382 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 383 unsigned NumArgs = TheCall->getNumArgs(); 384 385 if (NumArgs < 4) { 386 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 387 return true; 388 } 389 390 Expr *Arg0 = TheCall->getArg(0); 391 Expr *Arg1 = TheCall->getArg(1); 392 Expr *Arg2 = TheCall->getArg(2); 393 Expr *Arg3 = TheCall->getArg(3); 394 395 // First argument always needs to be a queue_t type. 396 if (!Arg0->getType()->isQueueT()) { 397 S.Diag(TheCall->getArg(0)->getLocStart(), 398 diag::err_opencl_builtin_expected_type) 399 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 400 return true; 401 } 402 403 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 404 if (!Arg1->getType()->isIntegerType()) { 405 S.Diag(TheCall->getArg(1)->getLocStart(), 406 diag::err_opencl_builtin_expected_type) 407 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 408 return true; 409 } 410 411 // Third argument is always an ndrange_t type. 412 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 413 S.Diag(TheCall->getArg(2)->getLocStart(), 414 diag::err_opencl_builtin_expected_type) 415 << TheCall->getDirectCallee() << "'ndrange_t'"; 416 return true; 417 } 418 419 // With four arguments, there is only one form that the function could be 420 // called in: no events and no variable arguments. 421 if (NumArgs == 4) { 422 // check that the last argument is the right block type. 423 if (!isBlockPointer(Arg3)) { 424 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type) 425 << TheCall->getDirectCallee() << "block"; 426 return true; 427 } 428 // we have a block type, check the prototype 429 const BlockPointerType *BPT = 430 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 431 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 432 S.Diag(Arg3->getLocStart(), 433 diag::err_opencl_enqueue_kernel_blocks_no_args); 434 return true; 435 } 436 return false; 437 } 438 // we can have block + varargs. 439 if (isBlockPointer(Arg3)) 440 return (checkOpenCLBlockArgs(S, Arg3) || 441 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 442 // last two cases with either exactly 7 args or 7 args and varargs. 443 if (NumArgs >= 7) { 444 // check common block argument. 445 Expr *Arg6 = TheCall->getArg(6); 446 if (!isBlockPointer(Arg6)) { 447 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type) 448 << TheCall->getDirectCallee() << "block"; 449 return true; 450 } 451 if (checkOpenCLBlockArgs(S, Arg6)) 452 return true; 453 454 // Forth argument has to be any integer type. 455 if (!Arg3->getType()->isIntegerType()) { 456 S.Diag(TheCall->getArg(3)->getLocStart(), 457 diag::err_opencl_builtin_expected_type) 458 << TheCall->getDirectCallee() << "integer"; 459 return true; 460 } 461 // check remaining common arguments. 462 Expr *Arg4 = TheCall->getArg(4); 463 Expr *Arg5 = TheCall->getArg(5); 464 465 // Fifth argument is always passed as a pointer to clk_event_t. 466 if (!Arg4->isNullPointerConstant(S.Context, 467 Expr::NPC_ValueDependentIsNotNull) && 468 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 469 S.Diag(TheCall->getArg(4)->getLocStart(), 470 diag::err_opencl_builtin_expected_type) 471 << TheCall->getDirectCallee() 472 << S.Context.getPointerType(S.Context.OCLClkEventTy); 473 return true; 474 } 475 476 // Sixth argument is always passed as a pointer to clk_event_t. 477 if (!Arg5->isNullPointerConstant(S.Context, 478 Expr::NPC_ValueDependentIsNotNull) && 479 !(Arg5->getType()->isPointerType() && 480 Arg5->getType()->getPointeeType()->isClkEventT())) { 481 S.Diag(TheCall->getArg(5)->getLocStart(), 482 diag::err_opencl_builtin_expected_type) 483 << TheCall->getDirectCallee() 484 << S.Context.getPointerType(S.Context.OCLClkEventTy); 485 return true; 486 } 487 488 if (NumArgs == 7) 489 return false; 490 491 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 492 } 493 494 // None of the specific case has been detected, give generic error 495 S.Diag(TheCall->getLocStart(), 496 diag::err_opencl_enqueue_kernel_incorrect_args); 497 return true; 498 } 499 500 /// Returns OpenCL access qual. 501 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 502 return D->getAttr<OpenCLAccessAttr>(); 503 } 504 505 /// Returns true if pipe element type is different from the pointer. 506 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 507 const Expr *Arg0 = Call->getArg(0); 508 // First argument type should always be pipe. 509 if (!Arg0->getType()->isPipeType()) { 510 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 511 << Call->getDirectCallee() << Arg0->getSourceRange(); 512 return true; 513 } 514 OpenCLAccessAttr *AccessQual = 515 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 516 // Validates the access qualifier is compatible with the call. 517 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 518 // read_only and write_only, and assumed to be read_only if no qualifier is 519 // specified. 520 switch (Call->getDirectCallee()->getBuiltinID()) { 521 case Builtin::BIread_pipe: 522 case Builtin::BIreserve_read_pipe: 523 case Builtin::BIcommit_read_pipe: 524 case Builtin::BIwork_group_reserve_read_pipe: 525 case Builtin::BIsub_group_reserve_read_pipe: 526 case Builtin::BIwork_group_commit_read_pipe: 527 case Builtin::BIsub_group_commit_read_pipe: 528 if (!(!AccessQual || AccessQual->isReadOnly())) { 529 S.Diag(Arg0->getLocStart(), 530 diag::err_opencl_builtin_pipe_invalid_access_modifier) 531 << "read_only" << Arg0->getSourceRange(); 532 return true; 533 } 534 break; 535 case Builtin::BIwrite_pipe: 536 case Builtin::BIreserve_write_pipe: 537 case Builtin::BIcommit_write_pipe: 538 case Builtin::BIwork_group_reserve_write_pipe: 539 case Builtin::BIsub_group_reserve_write_pipe: 540 case Builtin::BIwork_group_commit_write_pipe: 541 case Builtin::BIsub_group_commit_write_pipe: 542 if (!(AccessQual && AccessQual->isWriteOnly())) { 543 S.Diag(Arg0->getLocStart(), 544 diag::err_opencl_builtin_pipe_invalid_access_modifier) 545 << "write_only" << Arg0->getSourceRange(); 546 return true; 547 } 548 break; 549 default: 550 break; 551 } 552 return false; 553 } 554 555 /// Returns true if pipe element type is different from the pointer. 556 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 557 const Expr *Arg0 = Call->getArg(0); 558 const Expr *ArgIdx = Call->getArg(Idx); 559 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 560 const QualType EltTy = PipeTy->getElementType(); 561 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 562 // The Idx argument should be a pointer and the type of the pointer and 563 // the type of pipe element should also be the same. 564 if (!ArgTy || 565 !S.Context.hasSameType( 566 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 567 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 568 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 569 << ArgIdx->getType() << ArgIdx->getSourceRange(); 570 return true; 571 } 572 return false; 573 } 574 575 // \brief Performs semantic analysis for the read/write_pipe call. 576 // \param S Reference to the semantic analyzer. 577 // \param Call A pointer to the builtin call. 578 // \return True if a semantic error has been found, false otherwise. 579 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 580 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 581 // functions have two forms. 582 switch (Call->getNumArgs()) { 583 case 2: { 584 if (checkOpenCLPipeArg(S, Call)) 585 return true; 586 // The call with 2 arguments should be 587 // read/write_pipe(pipe T, T*). 588 // Check packet type T. 589 if (checkOpenCLPipePacketType(S, Call, 1)) 590 return true; 591 } break; 592 593 case 4: { 594 if (checkOpenCLPipeArg(S, Call)) 595 return true; 596 // The call with 4 arguments should be 597 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 598 // Check reserve_id_t. 599 if (!Call->getArg(1)->getType()->isReserveIDT()) { 600 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 601 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 602 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 603 return true; 604 } 605 606 // Check the index. 607 const Expr *Arg2 = Call->getArg(2); 608 if (!Arg2->getType()->isIntegerType() && 609 !Arg2->getType()->isUnsignedIntegerType()) { 610 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 611 << Call->getDirectCallee() << S.Context.UnsignedIntTy 612 << Arg2->getType() << Arg2->getSourceRange(); 613 return true; 614 } 615 616 // Check packet type T. 617 if (checkOpenCLPipePacketType(S, Call, 3)) 618 return true; 619 } break; 620 default: 621 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 622 << Call->getDirectCallee() << Call->getSourceRange(); 623 return true; 624 } 625 626 return false; 627 } 628 629 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 630 // /_}reserve_{read/write}_pipe 631 // \param S Reference to the semantic analyzer. 632 // \param Call The call to the builtin function to be analyzed. 633 // \return True if a semantic error was found, false otherwise. 634 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 635 if (checkArgCount(S, Call, 2)) 636 return true; 637 638 if (checkOpenCLPipeArg(S, Call)) 639 return true; 640 641 // Check the reserve size. 642 if (!Call->getArg(1)->getType()->isIntegerType() && 643 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 644 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 645 << Call->getDirectCallee() << S.Context.UnsignedIntTy 646 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 647 return true; 648 } 649 650 return false; 651 } 652 653 // \brief Performs a semantic analysis on {work_group_/sub_group_ 654 // /_}commit_{read/write}_pipe 655 // \param S Reference to the semantic analyzer. 656 // \param Call The call to the builtin function to be analyzed. 657 // \return True if a semantic error was found, false otherwise. 658 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 659 if (checkArgCount(S, Call, 2)) 660 return true; 661 662 if (checkOpenCLPipeArg(S, Call)) 663 return true; 664 665 // Check reserve_id_t. 666 if (!Call->getArg(1)->getType()->isReserveIDT()) { 667 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 668 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 669 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 670 return true; 671 } 672 673 return false; 674 } 675 676 // \brief Performs a semantic analysis on the call to built-in Pipe 677 // Query Functions. 678 // \param S Reference to the semantic analyzer. 679 // \param Call The call to the builtin function to be analyzed. 680 // \return True if a semantic error was found, false otherwise. 681 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 682 if (checkArgCount(S, Call, 1)) 683 return true; 684 685 if (!Call->getArg(0)->getType()->isPipeType()) { 686 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 687 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 688 return true; 689 } 690 691 return false; 692 } 693 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 694 // \brief Performs semantic analysis for the to_global/local/private call. 695 // \param S Reference to the semantic analyzer. 696 // \param BuiltinID ID of the builtin function. 697 // \param Call A pointer to the builtin call. 698 // \return True if a semantic error has been found, false otherwise. 699 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 700 CallExpr *Call) { 701 if (Call->getNumArgs() != 1) { 702 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 703 << Call->getDirectCallee() << Call->getSourceRange(); 704 return true; 705 } 706 707 auto RT = Call->getArg(0)->getType(); 708 if (!RT->isPointerType() || RT->getPointeeType() 709 .getAddressSpace() == LangAS::opencl_constant) { 710 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 711 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 712 return true; 713 } 714 715 RT = RT->getPointeeType(); 716 auto Qual = RT.getQualifiers(); 717 switch (BuiltinID) { 718 case Builtin::BIto_global: 719 Qual.setAddressSpace(LangAS::opencl_global); 720 break; 721 case Builtin::BIto_local: 722 Qual.setAddressSpace(LangAS::opencl_local); 723 break; 724 default: 725 Qual.removeAddressSpace(); 726 } 727 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 728 RT.getUnqualifiedType(), Qual))); 729 730 return false; 731 } 732 733 ExprResult 734 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 735 CallExpr *TheCall) { 736 ExprResult TheCallResult(TheCall); 737 738 // Find out if any arguments are required to be integer constant expressions. 739 unsigned ICEArguments = 0; 740 ASTContext::GetBuiltinTypeError Error; 741 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 742 if (Error != ASTContext::GE_None) 743 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 744 745 // If any arguments are required to be ICE's, check and diagnose. 746 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 747 // Skip arguments not required to be ICE's. 748 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 749 750 llvm::APSInt Result; 751 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 752 return true; 753 ICEArguments &= ~(1 << ArgNo); 754 } 755 756 switch (BuiltinID) { 757 case Builtin::BI__builtin___CFStringMakeConstantString: 758 assert(TheCall->getNumArgs() == 1 && 759 "Wrong # arguments to builtin CFStringMakeConstantString"); 760 if (CheckObjCString(TheCall->getArg(0))) 761 return ExprError(); 762 break; 763 case Builtin::BI__builtin_ms_va_start: 764 case Builtin::BI__builtin_stdarg_start: 765 case Builtin::BI__builtin_va_start: 766 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 767 return ExprError(); 768 break; 769 case Builtin::BI__va_start: { 770 switch (Context.getTargetInfo().getTriple().getArch()) { 771 case llvm::Triple::arm: 772 case llvm::Triple::thumb: 773 if (SemaBuiltinVAStartARM(TheCall)) 774 return ExprError(); 775 break; 776 default: 777 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 778 return ExprError(); 779 break; 780 } 781 break; 782 } 783 case Builtin::BI__builtin_isgreater: 784 case Builtin::BI__builtin_isgreaterequal: 785 case Builtin::BI__builtin_isless: 786 case Builtin::BI__builtin_islessequal: 787 case Builtin::BI__builtin_islessgreater: 788 case Builtin::BI__builtin_isunordered: 789 if (SemaBuiltinUnorderedCompare(TheCall)) 790 return ExprError(); 791 break; 792 case Builtin::BI__builtin_fpclassify: 793 if (SemaBuiltinFPClassification(TheCall, 6)) 794 return ExprError(); 795 break; 796 case Builtin::BI__builtin_isfinite: 797 case Builtin::BI__builtin_isinf: 798 case Builtin::BI__builtin_isinf_sign: 799 case Builtin::BI__builtin_isnan: 800 case Builtin::BI__builtin_isnormal: 801 if (SemaBuiltinFPClassification(TheCall, 1)) 802 return ExprError(); 803 break; 804 case Builtin::BI__builtin_shufflevector: 805 return SemaBuiltinShuffleVector(TheCall); 806 // TheCall will be freed by the smart pointer here, but that's fine, since 807 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 808 case Builtin::BI__builtin_prefetch: 809 if (SemaBuiltinPrefetch(TheCall)) 810 return ExprError(); 811 break; 812 case Builtin::BI__builtin_alloca_with_align: 813 if (SemaBuiltinAllocaWithAlign(TheCall)) 814 return ExprError(); 815 break; 816 case Builtin::BI__assume: 817 case Builtin::BI__builtin_assume: 818 if (SemaBuiltinAssume(TheCall)) 819 return ExprError(); 820 break; 821 case Builtin::BI__builtin_assume_aligned: 822 if (SemaBuiltinAssumeAligned(TheCall)) 823 return ExprError(); 824 break; 825 case Builtin::BI__builtin_object_size: 826 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 827 return ExprError(); 828 break; 829 case Builtin::BI__builtin_longjmp: 830 if (SemaBuiltinLongjmp(TheCall)) 831 return ExprError(); 832 break; 833 case Builtin::BI__builtin_setjmp: 834 if (SemaBuiltinSetjmp(TheCall)) 835 return ExprError(); 836 break; 837 case Builtin::BI_setjmp: 838 case Builtin::BI_setjmpex: 839 if (checkArgCount(*this, TheCall, 1)) 840 return true; 841 break; 842 843 case Builtin::BI__builtin_classify_type: 844 if (checkArgCount(*this, TheCall, 1)) return true; 845 TheCall->setType(Context.IntTy); 846 break; 847 case Builtin::BI__builtin_constant_p: 848 if (checkArgCount(*this, TheCall, 1)) return true; 849 TheCall->setType(Context.IntTy); 850 break; 851 case Builtin::BI__sync_fetch_and_add: 852 case Builtin::BI__sync_fetch_and_add_1: 853 case Builtin::BI__sync_fetch_and_add_2: 854 case Builtin::BI__sync_fetch_and_add_4: 855 case Builtin::BI__sync_fetch_and_add_8: 856 case Builtin::BI__sync_fetch_and_add_16: 857 case Builtin::BI__sync_fetch_and_sub: 858 case Builtin::BI__sync_fetch_and_sub_1: 859 case Builtin::BI__sync_fetch_and_sub_2: 860 case Builtin::BI__sync_fetch_and_sub_4: 861 case Builtin::BI__sync_fetch_and_sub_8: 862 case Builtin::BI__sync_fetch_and_sub_16: 863 case Builtin::BI__sync_fetch_and_or: 864 case Builtin::BI__sync_fetch_and_or_1: 865 case Builtin::BI__sync_fetch_and_or_2: 866 case Builtin::BI__sync_fetch_and_or_4: 867 case Builtin::BI__sync_fetch_and_or_8: 868 case Builtin::BI__sync_fetch_and_or_16: 869 case Builtin::BI__sync_fetch_and_and: 870 case Builtin::BI__sync_fetch_and_and_1: 871 case Builtin::BI__sync_fetch_and_and_2: 872 case Builtin::BI__sync_fetch_and_and_4: 873 case Builtin::BI__sync_fetch_and_and_8: 874 case Builtin::BI__sync_fetch_and_and_16: 875 case Builtin::BI__sync_fetch_and_xor: 876 case Builtin::BI__sync_fetch_and_xor_1: 877 case Builtin::BI__sync_fetch_and_xor_2: 878 case Builtin::BI__sync_fetch_and_xor_4: 879 case Builtin::BI__sync_fetch_and_xor_8: 880 case Builtin::BI__sync_fetch_and_xor_16: 881 case Builtin::BI__sync_fetch_and_nand: 882 case Builtin::BI__sync_fetch_and_nand_1: 883 case Builtin::BI__sync_fetch_and_nand_2: 884 case Builtin::BI__sync_fetch_and_nand_4: 885 case Builtin::BI__sync_fetch_and_nand_8: 886 case Builtin::BI__sync_fetch_and_nand_16: 887 case Builtin::BI__sync_add_and_fetch: 888 case Builtin::BI__sync_add_and_fetch_1: 889 case Builtin::BI__sync_add_and_fetch_2: 890 case Builtin::BI__sync_add_and_fetch_4: 891 case Builtin::BI__sync_add_and_fetch_8: 892 case Builtin::BI__sync_add_and_fetch_16: 893 case Builtin::BI__sync_sub_and_fetch: 894 case Builtin::BI__sync_sub_and_fetch_1: 895 case Builtin::BI__sync_sub_and_fetch_2: 896 case Builtin::BI__sync_sub_and_fetch_4: 897 case Builtin::BI__sync_sub_and_fetch_8: 898 case Builtin::BI__sync_sub_and_fetch_16: 899 case Builtin::BI__sync_and_and_fetch: 900 case Builtin::BI__sync_and_and_fetch_1: 901 case Builtin::BI__sync_and_and_fetch_2: 902 case Builtin::BI__sync_and_and_fetch_4: 903 case Builtin::BI__sync_and_and_fetch_8: 904 case Builtin::BI__sync_and_and_fetch_16: 905 case Builtin::BI__sync_or_and_fetch: 906 case Builtin::BI__sync_or_and_fetch_1: 907 case Builtin::BI__sync_or_and_fetch_2: 908 case Builtin::BI__sync_or_and_fetch_4: 909 case Builtin::BI__sync_or_and_fetch_8: 910 case Builtin::BI__sync_or_and_fetch_16: 911 case Builtin::BI__sync_xor_and_fetch: 912 case Builtin::BI__sync_xor_and_fetch_1: 913 case Builtin::BI__sync_xor_and_fetch_2: 914 case Builtin::BI__sync_xor_and_fetch_4: 915 case Builtin::BI__sync_xor_and_fetch_8: 916 case Builtin::BI__sync_xor_and_fetch_16: 917 case Builtin::BI__sync_nand_and_fetch: 918 case Builtin::BI__sync_nand_and_fetch_1: 919 case Builtin::BI__sync_nand_and_fetch_2: 920 case Builtin::BI__sync_nand_and_fetch_4: 921 case Builtin::BI__sync_nand_and_fetch_8: 922 case Builtin::BI__sync_nand_and_fetch_16: 923 case Builtin::BI__sync_val_compare_and_swap: 924 case Builtin::BI__sync_val_compare_and_swap_1: 925 case Builtin::BI__sync_val_compare_and_swap_2: 926 case Builtin::BI__sync_val_compare_and_swap_4: 927 case Builtin::BI__sync_val_compare_and_swap_8: 928 case Builtin::BI__sync_val_compare_and_swap_16: 929 case Builtin::BI__sync_bool_compare_and_swap: 930 case Builtin::BI__sync_bool_compare_and_swap_1: 931 case Builtin::BI__sync_bool_compare_and_swap_2: 932 case Builtin::BI__sync_bool_compare_and_swap_4: 933 case Builtin::BI__sync_bool_compare_and_swap_8: 934 case Builtin::BI__sync_bool_compare_and_swap_16: 935 case Builtin::BI__sync_lock_test_and_set: 936 case Builtin::BI__sync_lock_test_and_set_1: 937 case Builtin::BI__sync_lock_test_and_set_2: 938 case Builtin::BI__sync_lock_test_and_set_4: 939 case Builtin::BI__sync_lock_test_and_set_8: 940 case Builtin::BI__sync_lock_test_and_set_16: 941 case Builtin::BI__sync_lock_release: 942 case Builtin::BI__sync_lock_release_1: 943 case Builtin::BI__sync_lock_release_2: 944 case Builtin::BI__sync_lock_release_4: 945 case Builtin::BI__sync_lock_release_8: 946 case Builtin::BI__sync_lock_release_16: 947 case Builtin::BI__sync_swap: 948 case Builtin::BI__sync_swap_1: 949 case Builtin::BI__sync_swap_2: 950 case Builtin::BI__sync_swap_4: 951 case Builtin::BI__sync_swap_8: 952 case Builtin::BI__sync_swap_16: 953 return SemaBuiltinAtomicOverloaded(TheCallResult); 954 case Builtin::BI__builtin_nontemporal_load: 955 case Builtin::BI__builtin_nontemporal_store: 956 return SemaBuiltinNontemporalOverloaded(TheCallResult); 957 #define BUILTIN(ID, TYPE, ATTRS) 958 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 959 case Builtin::BI##ID: \ 960 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 961 #include "clang/Basic/Builtins.def" 962 case Builtin::BI__builtin_annotation: 963 if (SemaBuiltinAnnotation(*this, TheCall)) 964 return ExprError(); 965 break; 966 case Builtin::BI__builtin_addressof: 967 if (SemaBuiltinAddressof(*this, TheCall)) 968 return ExprError(); 969 break; 970 case Builtin::BI__builtin_add_overflow: 971 case Builtin::BI__builtin_sub_overflow: 972 case Builtin::BI__builtin_mul_overflow: 973 if (SemaBuiltinOverflow(*this, TheCall)) 974 return ExprError(); 975 break; 976 case Builtin::BI__builtin_operator_new: 977 case Builtin::BI__builtin_operator_delete: 978 if (!getLangOpts().CPlusPlus) { 979 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 980 << (BuiltinID == Builtin::BI__builtin_operator_new 981 ? "__builtin_operator_new" 982 : "__builtin_operator_delete") 983 << "C++"; 984 return ExprError(); 985 } 986 // CodeGen assumes it can find the global new and delete to call, 987 // so ensure that they are declared. 988 DeclareGlobalNewDelete(); 989 break; 990 991 // check secure string manipulation functions where overflows 992 // are detectable at compile time 993 case Builtin::BI__builtin___memcpy_chk: 994 case Builtin::BI__builtin___memmove_chk: 995 case Builtin::BI__builtin___memset_chk: 996 case Builtin::BI__builtin___strlcat_chk: 997 case Builtin::BI__builtin___strlcpy_chk: 998 case Builtin::BI__builtin___strncat_chk: 999 case Builtin::BI__builtin___strncpy_chk: 1000 case Builtin::BI__builtin___stpncpy_chk: 1001 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1002 break; 1003 case Builtin::BI__builtin___memccpy_chk: 1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1005 break; 1006 case Builtin::BI__builtin___snprintf_chk: 1007 case Builtin::BI__builtin___vsnprintf_chk: 1008 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1009 break; 1010 case Builtin::BI__builtin_call_with_static_chain: 1011 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1012 return ExprError(); 1013 break; 1014 case Builtin::BI__exception_code: 1015 case Builtin::BI_exception_code: 1016 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1017 diag::err_seh___except_block)) 1018 return ExprError(); 1019 break; 1020 case Builtin::BI__exception_info: 1021 case Builtin::BI_exception_info: 1022 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1023 diag::err_seh___except_filter)) 1024 return ExprError(); 1025 break; 1026 case Builtin::BI__GetExceptionInfo: 1027 if (checkArgCount(*this, TheCall, 1)) 1028 return ExprError(); 1029 1030 if (CheckCXXThrowOperand( 1031 TheCall->getLocStart(), 1032 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1033 TheCall)) 1034 return ExprError(); 1035 1036 TheCall->setType(Context.VoidPtrTy); 1037 break; 1038 // OpenCL v2.0, s6.13.16 - Pipe functions 1039 case Builtin::BIread_pipe: 1040 case Builtin::BIwrite_pipe: 1041 // Since those two functions are declared with var args, we need a semantic 1042 // check for the argument. 1043 if (SemaBuiltinRWPipe(*this, TheCall)) 1044 return ExprError(); 1045 TheCall->setType(Context.IntTy); 1046 break; 1047 case Builtin::BIreserve_read_pipe: 1048 case Builtin::BIreserve_write_pipe: 1049 case Builtin::BIwork_group_reserve_read_pipe: 1050 case Builtin::BIwork_group_reserve_write_pipe: 1051 case Builtin::BIsub_group_reserve_read_pipe: 1052 case Builtin::BIsub_group_reserve_write_pipe: 1053 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1054 return ExprError(); 1055 // Since return type of reserve_read/write_pipe built-in function is 1056 // reserve_id_t, which is not defined in the builtin def file , we used int 1057 // as return type and need to override the return type of these functions. 1058 TheCall->setType(Context.OCLReserveIDTy); 1059 break; 1060 case Builtin::BIcommit_read_pipe: 1061 case Builtin::BIcommit_write_pipe: 1062 case Builtin::BIwork_group_commit_read_pipe: 1063 case Builtin::BIwork_group_commit_write_pipe: 1064 case Builtin::BIsub_group_commit_read_pipe: 1065 case Builtin::BIsub_group_commit_write_pipe: 1066 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1067 return ExprError(); 1068 break; 1069 case Builtin::BIget_pipe_num_packets: 1070 case Builtin::BIget_pipe_max_packets: 1071 if (SemaBuiltinPipePackets(*this, TheCall)) 1072 return ExprError(); 1073 TheCall->setType(Context.UnsignedIntTy); 1074 break; 1075 case Builtin::BIto_global: 1076 case Builtin::BIto_local: 1077 case Builtin::BIto_private: 1078 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1079 return ExprError(); 1080 break; 1081 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1082 case Builtin::BIenqueue_kernel: 1083 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1084 return ExprError(); 1085 break; 1086 case Builtin::BIget_kernel_work_group_size: 1087 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1088 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1089 return ExprError(); 1090 break; 1091 case Builtin::BI__builtin_os_log_format: 1092 case Builtin::BI__builtin_os_log_format_buffer_size: 1093 if (SemaBuiltinOSLogFormat(TheCall)) { 1094 return ExprError(); 1095 } 1096 break; 1097 } 1098 1099 // Since the target specific builtins for each arch overlap, only check those 1100 // of the arch we are compiling for. 1101 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1102 switch (Context.getTargetInfo().getTriple().getArch()) { 1103 case llvm::Triple::arm: 1104 case llvm::Triple::armeb: 1105 case llvm::Triple::thumb: 1106 case llvm::Triple::thumbeb: 1107 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1108 return ExprError(); 1109 break; 1110 case llvm::Triple::aarch64: 1111 case llvm::Triple::aarch64_be: 1112 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1113 return ExprError(); 1114 break; 1115 case llvm::Triple::mips: 1116 case llvm::Triple::mipsel: 1117 case llvm::Triple::mips64: 1118 case llvm::Triple::mips64el: 1119 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1120 return ExprError(); 1121 break; 1122 case llvm::Triple::systemz: 1123 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1124 return ExprError(); 1125 break; 1126 case llvm::Triple::x86: 1127 case llvm::Triple::x86_64: 1128 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1129 return ExprError(); 1130 break; 1131 case llvm::Triple::ppc: 1132 case llvm::Triple::ppc64: 1133 case llvm::Triple::ppc64le: 1134 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1135 return ExprError(); 1136 break; 1137 default: 1138 break; 1139 } 1140 } 1141 1142 return TheCallResult; 1143 } 1144 1145 // Get the valid immediate range for the specified NEON type code. 1146 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1147 NeonTypeFlags Type(t); 1148 int IsQuad = ForceQuad ? true : Type.isQuad(); 1149 switch (Type.getEltType()) { 1150 case NeonTypeFlags::Int8: 1151 case NeonTypeFlags::Poly8: 1152 return shift ? 7 : (8 << IsQuad) - 1; 1153 case NeonTypeFlags::Int16: 1154 case NeonTypeFlags::Poly16: 1155 return shift ? 15 : (4 << IsQuad) - 1; 1156 case NeonTypeFlags::Int32: 1157 return shift ? 31 : (2 << IsQuad) - 1; 1158 case NeonTypeFlags::Int64: 1159 case NeonTypeFlags::Poly64: 1160 return shift ? 63 : (1 << IsQuad) - 1; 1161 case NeonTypeFlags::Poly128: 1162 return shift ? 127 : (1 << IsQuad) - 1; 1163 case NeonTypeFlags::Float16: 1164 assert(!shift && "cannot shift float types!"); 1165 return (4 << IsQuad) - 1; 1166 case NeonTypeFlags::Float32: 1167 assert(!shift && "cannot shift float types!"); 1168 return (2 << IsQuad) - 1; 1169 case NeonTypeFlags::Float64: 1170 assert(!shift && "cannot shift float types!"); 1171 return (1 << IsQuad) - 1; 1172 } 1173 llvm_unreachable("Invalid NeonTypeFlag!"); 1174 } 1175 1176 /// getNeonEltType - Return the QualType corresponding to the elements of 1177 /// the vector type specified by the NeonTypeFlags. This is used to check 1178 /// the pointer arguments for Neon load/store intrinsics. 1179 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1180 bool IsPolyUnsigned, bool IsInt64Long) { 1181 switch (Flags.getEltType()) { 1182 case NeonTypeFlags::Int8: 1183 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1184 case NeonTypeFlags::Int16: 1185 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1186 case NeonTypeFlags::Int32: 1187 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1188 case NeonTypeFlags::Int64: 1189 if (IsInt64Long) 1190 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1191 else 1192 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1193 : Context.LongLongTy; 1194 case NeonTypeFlags::Poly8: 1195 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1196 case NeonTypeFlags::Poly16: 1197 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1198 case NeonTypeFlags::Poly64: 1199 if (IsInt64Long) 1200 return Context.UnsignedLongTy; 1201 else 1202 return Context.UnsignedLongLongTy; 1203 case NeonTypeFlags::Poly128: 1204 break; 1205 case NeonTypeFlags::Float16: 1206 return Context.HalfTy; 1207 case NeonTypeFlags::Float32: 1208 return Context.FloatTy; 1209 case NeonTypeFlags::Float64: 1210 return Context.DoubleTy; 1211 } 1212 llvm_unreachable("Invalid NeonTypeFlag!"); 1213 } 1214 1215 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1216 llvm::APSInt Result; 1217 uint64_t mask = 0; 1218 unsigned TV = 0; 1219 int PtrArgNum = -1; 1220 bool HasConstPtr = false; 1221 switch (BuiltinID) { 1222 #define GET_NEON_OVERLOAD_CHECK 1223 #include "clang/Basic/arm_neon.inc" 1224 #undef GET_NEON_OVERLOAD_CHECK 1225 } 1226 1227 // For NEON intrinsics which are overloaded on vector element type, validate 1228 // the immediate which specifies which variant to emit. 1229 unsigned ImmArg = TheCall->getNumArgs()-1; 1230 if (mask) { 1231 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1232 return true; 1233 1234 TV = Result.getLimitedValue(64); 1235 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1236 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1237 << TheCall->getArg(ImmArg)->getSourceRange(); 1238 } 1239 1240 if (PtrArgNum >= 0) { 1241 // Check that pointer arguments have the specified type. 1242 Expr *Arg = TheCall->getArg(PtrArgNum); 1243 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1244 Arg = ICE->getSubExpr(); 1245 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1246 QualType RHSTy = RHS.get()->getType(); 1247 1248 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1249 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1250 Arch == llvm::Triple::aarch64_be; 1251 bool IsInt64Long = 1252 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1253 QualType EltTy = 1254 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1255 if (HasConstPtr) 1256 EltTy = EltTy.withConst(); 1257 QualType LHSTy = Context.getPointerType(EltTy); 1258 AssignConvertType ConvTy; 1259 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1260 if (RHS.isInvalid()) 1261 return true; 1262 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1263 RHS.get(), AA_Assigning)) 1264 return true; 1265 } 1266 1267 // For NEON intrinsics which take an immediate value as part of the 1268 // instruction, range check them here. 1269 unsigned i = 0, l = 0, u = 0; 1270 switch (BuiltinID) { 1271 default: 1272 return false; 1273 #define GET_NEON_IMMEDIATE_CHECK 1274 #include "clang/Basic/arm_neon.inc" 1275 #undef GET_NEON_IMMEDIATE_CHECK 1276 } 1277 1278 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1279 } 1280 1281 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1282 unsigned MaxWidth) { 1283 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1284 BuiltinID == ARM::BI__builtin_arm_ldaex || 1285 BuiltinID == ARM::BI__builtin_arm_strex || 1286 BuiltinID == ARM::BI__builtin_arm_stlex || 1287 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1288 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1289 BuiltinID == AArch64::BI__builtin_arm_strex || 1290 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1291 "unexpected ARM builtin"); 1292 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1293 BuiltinID == ARM::BI__builtin_arm_ldaex || 1294 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1295 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1296 1297 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1298 1299 // Ensure that we have the proper number of arguments. 1300 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1301 return true; 1302 1303 // Inspect the pointer argument of the atomic builtin. This should always be 1304 // a pointer type, whose element is an integral scalar or pointer type. 1305 // Because it is a pointer type, we don't have to worry about any implicit 1306 // casts here. 1307 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1308 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1309 if (PointerArgRes.isInvalid()) 1310 return true; 1311 PointerArg = PointerArgRes.get(); 1312 1313 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1314 if (!pointerType) { 1315 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1316 << PointerArg->getType() << PointerArg->getSourceRange(); 1317 return true; 1318 } 1319 1320 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1321 // task is to insert the appropriate casts into the AST. First work out just 1322 // what the appropriate type is. 1323 QualType ValType = pointerType->getPointeeType(); 1324 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1325 if (IsLdrex) 1326 AddrType.addConst(); 1327 1328 // Issue a warning if the cast is dodgy. 1329 CastKind CastNeeded = CK_NoOp; 1330 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1331 CastNeeded = CK_BitCast; 1332 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1333 << PointerArg->getType() 1334 << Context.getPointerType(AddrType) 1335 << AA_Passing << PointerArg->getSourceRange(); 1336 } 1337 1338 // Finally, do the cast and replace the argument with the corrected version. 1339 AddrType = Context.getPointerType(AddrType); 1340 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1341 if (PointerArgRes.isInvalid()) 1342 return true; 1343 PointerArg = PointerArgRes.get(); 1344 1345 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1346 1347 // In general, we allow ints, floats and pointers to be loaded and stored. 1348 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1349 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1350 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1351 << PointerArg->getType() << PointerArg->getSourceRange(); 1352 return true; 1353 } 1354 1355 // But ARM doesn't have instructions to deal with 128-bit versions. 1356 if (Context.getTypeSize(ValType) > MaxWidth) { 1357 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1358 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1359 << PointerArg->getType() << PointerArg->getSourceRange(); 1360 return true; 1361 } 1362 1363 switch (ValType.getObjCLifetime()) { 1364 case Qualifiers::OCL_None: 1365 case Qualifiers::OCL_ExplicitNone: 1366 // okay 1367 break; 1368 1369 case Qualifiers::OCL_Weak: 1370 case Qualifiers::OCL_Strong: 1371 case Qualifiers::OCL_Autoreleasing: 1372 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1373 << ValType << PointerArg->getSourceRange(); 1374 return true; 1375 } 1376 1377 if (IsLdrex) { 1378 TheCall->setType(ValType); 1379 return false; 1380 } 1381 1382 // Initialize the argument to be stored. 1383 ExprResult ValArg = TheCall->getArg(0); 1384 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1385 Context, ValType, /*consume*/ false); 1386 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1387 if (ValArg.isInvalid()) 1388 return true; 1389 TheCall->setArg(0, ValArg.get()); 1390 1391 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1392 // but the custom checker bypasses all default analysis. 1393 TheCall->setType(Context.IntTy); 1394 return false; 1395 } 1396 1397 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1398 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1399 BuiltinID == ARM::BI__builtin_arm_ldaex || 1400 BuiltinID == ARM::BI__builtin_arm_strex || 1401 BuiltinID == ARM::BI__builtin_arm_stlex) { 1402 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1403 } 1404 1405 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1406 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1407 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1408 } 1409 1410 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1411 BuiltinID == ARM::BI__builtin_arm_wsr64) 1412 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1413 1414 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1415 BuiltinID == ARM::BI__builtin_arm_rsrp || 1416 BuiltinID == ARM::BI__builtin_arm_wsr || 1417 BuiltinID == ARM::BI__builtin_arm_wsrp) 1418 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1419 1420 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1421 return true; 1422 1423 // For intrinsics which take an immediate value as part of the instruction, 1424 // range check them here. 1425 unsigned i = 0, l = 0, u = 0; 1426 switch (BuiltinID) { 1427 default: return false; 1428 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1429 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1430 case ARM::BI__builtin_arm_vcvtr_f: 1431 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1432 case ARM::BI__builtin_arm_dmb: 1433 case ARM::BI__builtin_arm_dsb: 1434 case ARM::BI__builtin_arm_isb: 1435 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1436 } 1437 1438 // FIXME: VFP Intrinsics should error if VFP not present. 1439 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1440 } 1441 1442 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1443 CallExpr *TheCall) { 1444 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1445 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1446 BuiltinID == AArch64::BI__builtin_arm_strex || 1447 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1448 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1449 } 1450 1451 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1452 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1453 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1454 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1455 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1456 } 1457 1458 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1459 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1460 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1461 1462 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1463 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1464 BuiltinID == AArch64::BI__builtin_arm_wsr || 1465 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1466 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1467 1468 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1469 return true; 1470 1471 // For intrinsics which take an immediate value as part of the instruction, 1472 // range check them here. 1473 unsigned i = 0, l = 0, u = 0; 1474 switch (BuiltinID) { 1475 default: return false; 1476 case AArch64::BI__builtin_arm_dmb: 1477 case AArch64::BI__builtin_arm_dsb: 1478 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1479 } 1480 1481 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1482 } 1483 1484 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1485 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1486 // ordering for DSP is unspecified. MSA is ordered by the data format used 1487 // by the underlying instruction i.e., df/m, df/n and then by size. 1488 // 1489 // FIXME: The size tests here should instead be tablegen'd along with the 1490 // definitions from include/clang/Basic/BuiltinsMips.def. 1491 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1492 // be too. 1493 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1494 unsigned i = 0, l = 0, u = 0, m = 0; 1495 switch (BuiltinID) { 1496 default: return false; 1497 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1498 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1499 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1500 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1501 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1502 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1503 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1504 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1505 // df/m field. 1506 // These intrinsics take an unsigned 3 bit immediate. 1507 case Mips::BI__builtin_msa_bclri_b: 1508 case Mips::BI__builtin_msa_bnegi_b: 1509 case Mips::BI__builtin_msa_bseti_b: 1510 case Mips::BI__builtin_msa_sat_s_b: 1511 case Mips::BI__builtin_msa_sat_u_b: 1512 case Mips::BI__builtin_msa_slli_b: 1513 case Mips::BI__builtin_msa_srai_b: 1514 case Mips::BI__builtin_msa_srari_b: 1515 case Mips::BI__builtin_msa_srli_b: 1516 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1517 case Mips::BI__builtin_msa_binsli_b: 1518 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1519 // These intrinsics take an unsigned 4 bit immediate. 1520 case Mips::BI__builtin_msa_bclri_h: 1521 case Mips::BI__builtin_msa_bnegi_h: 1522 case Mips::BI__builtin_msa_bseti_h: 1523 case Mips::BI__builtin_msa_sat_s_h: 1524 case Mips::BI__builtin_msa_sat_u_h: 1525 case Mips::BI__builtin_msa_slli_h: 1526 case Mips::BI__builtin_msa_srai_h: 1527 case Mips::BI__builtin_msa_srari_h: 1528 case Mips::BI__builtin_msa_srli_h: 1529 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1530 case Mips::BI__builtin_msa_binsli_h: 1531 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1532 // These intrinsics take an unsigned 5 bit immedate. 1533 // The first block of intrinsics actually have an unsigned 5 bit field, 1534 // not a df/n field. 1535 case Mips::BI__builtin_msa_clei_u_b: 1536 case Mips::BI__builtin_msa_clei_u_h: 1537 case Mips::BI__builtin_msa_clei_u_w: 1538 case Mips::BI__builtin_msa_clei_u_d: 1539 case Mips::BI__builtin_msa_clti_u_b: 1540 case Mips::BI__builtin_msa_clti_u_h: 1541 case Mips::BI__builtin_msa_clti_u_w: 1542 case Mips::BI__builtin_msa_clti_u_d: 1543 case Mips::BI__builtin_msa_maxi_u_b: 1544 case Mips::BI__builtin_msa_maxi_u_h: 1545 case Mips::BI__builtin_msa_maxi_u_w: 1546 case Mips::BI__builtin_msa_maxi_u_d: 1547 case Mips::BI__builtin_msa_mini_u_b: 1548 case Mips::BI__builtin_msa_mini_u_h: 1549 case Mips::BI__builtin_msa_mini_u_w: 1550 case Mips::BI__builtin_msa_mini_u_d: 1551 case Mips::BI__builtin_msa_addvi_b: 1552 case Mips::BI__builtin_msa_addvi_h: 1553 case Mips::BI__builtin_msa_addvi_w: 1554 case Mips::BI__builtin_msa_addvi_d: 1555 case Mips::BI__builtin_msa_bclri_w: 1556 case Mips::BI__builtin_msa_bnegi_w: 1557 case Mips::BI__builtin_msa_bseti_w: 1558 case Mips::BI__builtin_msa_sat_s_w: 1559 case Mips::BI__builtin_msa_sat_u_w: 1560 case Mips::BI__builtin_msa_slli_w: 1561 case Mips::BI__builtin_msa_srai_w: 1562 case Mips::BI__builtin_msa_srari_w: 1563 case Mips::BI__builtin_msa_srli_w: 1564 case Mips::BI__builtin_msa_srlri_w: 1565 case Mips::BI__builtin_msa_subvi_b: 1566 case Mips::BI__builtin_msa_subvi_h: 1567 case Mips::BI__builtin_msa_subvi_w: 1568 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1569 case Mips::BI__builtin_msa_binsli_w: 1570 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1571 // These intrinsics take an unsigned 6 bit immediate. 1572 case Mips::BI__builtin_msa_bclri_d: 1573 case Mips::BI__builtin_msa_bnegi_d: 1574 case Mips::BI__builtin_msa_bseti_d: 1575 case Mips::BI__builtin_msa_sat_s_d: 1576 case Mips::BI__builtin_msa_sat_u_d: 1577 case Mips::BI__builtin_msa_slli_d: 1578 case Mips::BI__builtin_msa_srai_d: 1579 case Mips::BI__builtin_msa_srari_d: 1580 case Mips::BI__builtin_msa_srli_d: 1581 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1582 case Mips::BI__builtin_msa_binsli_d: 1583 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1584 // These intrinsics take a signed 5 bit immediate. 1585 case Mips::BI__builtin_msa_ceqi_b: 1586 case Mips::BI__builtin_msa_ceqi_h: 1587 case Mips::BI__builtin_msa_ceqi_w: 1588 case Mips::BI__builtin_msa_ceqi_d: 1589 case Mips::BI__builtin_msa_clti_s_b: 1590 case Mips::BI__builtin_msa_clti_s_h: 1591 case Mips::BI__builtin_msa_clti_s_w: 1592 case Mips::BI__builtin_msa_clti_s_d: 1593 case Mips::BI__builtin_msa_clei_s_b: 1594 case Mips::BI__builtin_msa_clei_s_h: 1595 case Mips::BI__builtin_msa_clei_s_w: 1596 case Mips::BI__builtin_msa_clei_s_d: 1597 case Mips::BI__builtin_msa_maxi_s_b: 1598 case Mips::BI__builtin_msa_maxi_s_h: 1599 case Mips::BI__builtin_msa_maxi_s_w: 1600 case Mips::BI__builtin_msa_maxi_s_d: 1601 case Mips::BI__builtin_msa_mini_s_b: 1602 case Mips::BI__builtin_msa_mini_s_h: 1603 case Mips::BI__builtin_msa_mini_s_w: 1604 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1605 // These intrinsics take an unsigned 8 bit immediate. 1606 case Mips::BI__builtin_msa_andi_b: 1607 case Mips::BI__builtin_msa_nori_b: 1608 case Mips::BI__builtin_msa_ori_b: 1609 case Mips::BI__builtin_msa_shf_b: 1610 case Mips::BI__builtin_msa_shf_h: 1611 case Mips::BI__builtin_msa_shf_w: 1612 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1613 case Mips::BI__builtin_msa_bseli_b: 1614 case Mips::BI__builtin_msa_bmnzi_b: 1615 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1616 // df/n format 1617 // These intrinsics take an unsigned 4 bit immediate. 1618 case Mips::BI__builtin_msa_copy_s_b: 1619 case Mips::BI__builtin_msa_copy_u_b: 1620 case Mips::BI__builtin_msa_insve_b: 1621 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1622 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1623 // These intrinsics take an unsigned 3 bit immediate. 1624 case Mips::BI__builtin_msa_copy_s_h: 1625 case Mips::BI__builtin_msa_copy_u_h: 1626 case Mips::BI__builtin_msa_insve_h: 1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1628 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1629 // These intrinsics take an unsigned 2 bit immediate. 1630 case Mips::BI__builtin_msa_copy_s_w: 1631 case Mips::BI__builtin_msa_copy_u_w: 1632 case Mips::BI__builtin_msa_insve_w: 1633 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1634 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1635 // These intrinsics take an unsigned 1 bit immediate. 1636 case Mips::BI__builtin_msa_copy_s_d: 1637 case Mips::BI__builtin_msa_copy_u_d: 1638 case Mips::BI__builtin_msa_insve_d: 1639 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1640 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1641 // Memory offsets and immediate loads. 1642 // These intrinsics take a signed 10 bit immediate. 1643 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 1644 case Mips::BI__builtin_msa_ldi_h: 1645 case Mips::BI__builtin_msa_ldi_w: 1646 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1647 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1648 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1649 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1650 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1651 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1652 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1653 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1654 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1655 } 1656 1657 if (!m) 1658 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1659 1660 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1661 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1662 } 1663 1664 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1665 unsigned i = 0, l = 0, u = 0; 1666 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1667 BuiltinID == PPC::BI__builtin_divdeu || 1668 BuiltinID == PPC::BI__builtin_bpermd; 1669 bool IsTarget64Bit = Context.getTargetInfo() 1670 .getTypeWidth(Context 1671 .getTargetInfo() 1672 .getIntPtrType()) == 64; 1673 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1674 BuiltinID == PPC::BI__builtin_divweu || 1675 BuiltinID == PPC::BI__builtin_divde || 1676 BuiltinID == PPC::BI__builtin_divdeu; 1677 1678 if (Is64BitBltin && !IsTarget64Bit) 1679 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1680 << TheCall->getSourceRange(); 1681 1682 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1683 (BuiltinID == PPC::BI__builtin_bpermd && 1684 !Context.getTargetInfo().hasFeature("bpermd"))) 1685 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1686 << TheCall->getSourceRange(); 1687 1688 switch (BuiltinID) { 1689 default: return false; 1690 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1691 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1692 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1693 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1694 case PPC::BI__builtin_tbegin: 1695 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1696 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1697 case PPC::BI__builtin_tabortwc: 1698 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1699 case PPC::BI__builtin_tabortwci: 1700 case PPC::BI__builtin_tabortdci: 1701 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1702 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1703 case PPC::BI__builtin_vsx_xxpermdi: 1704 case PPC::BI__builtin_vsx_xxsldwi: 1705 return SemaBuiltinVSX(TheCall); 1706 } 1707 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1708 } 1709 1710 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1711 CallExpr *TheCall) { 1712 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1713 Expr *Arg = TheCall->getArg(0); 1714 llvm::APSInt AbortCode(32); 1715 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1716 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1717 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1718 << Arg->getSourceRange(); 1719 } 1720 1721 // For intrinsics which take an immediate value as part of the instruction, 1722 // range check them here. 1723 unsigned i = 0, l = 0, u = 0; 1724 switch (BuiltinID) { 1725 default: return false; 1726 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1727 case SystemZ::BI__builtin_s390_verimb: 1728 case SystemZ::BI__builtin_s390_verimh: 1729 case SystemZ::BI__builtin_s390_verimf: 1730 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1731 case SystemZ::BI__builtin_s390_vfaeb: 1732 case SystemZ::BI__builtin_s390_vfaeh: 1733 case SystemZ::BI__builtin_s390_vfaef: 1734 case SystemZ::BI__builtin_s390_vfaebs: 1735 case SystemZ::BI__builtin_s390_vfaehs: 1736 case SystemZ::BI__builtin_s390_vfaefs: 1737 case SystemZ::BI__builtin_s390_vfaezb: 1738 case SystemZ::BI__builtin_s390_vfaezh: 1739 case SystemZ::BI__builtin_s390_vfaezf: 1740 case SystemZ::BI__builtin_s390_vfaezbs: 1741 case SystemZ::BI__builtin_s390_vfaezhs: 1742 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1743 case SystemZ::BI__builtin_s390_vfisb: 1744 case SystemZ::BI__builtin_s390_vfidb: 1745 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1746 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1747 case SystemZ::BI__builtin_s390_vftcisb: 1748 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1749 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1750 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1751 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1752 case SystemZ::BI__builtin_s390_vstrcb: 1753 case SystemZ::BI__builtin_s390_vstrch: 1754 case SystemZ::BI__builtin_s390_vstrcf: 1755 case SystemZ::BI__builtin_s390_vstrczb: 1756 case SystemZ::BI__builtin_s390_vstrczh: 1757 case SystemZ::BI__builtin_s390_vstrczf: 1758 case SystemZ::BI__builtin_s390_vstrcbs: 1759 case SystemZ::BI__builtin_s390_vstrchs: 1760 case SystemZ::BI__builtin_s390_vstrcfs: 1761 case SystemZ::BI__builtin_s390_vstrczbs: 1762 case SystemZ::BI__builtin_s390_vstrczhs: 1763 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1764 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 1765 case SystemZ::BI__builtin_s390_vfminsb: 1766 case SystemZ::BI__builtin_s390_vfmaxsb: 1767 case SystemZ::BI__builtin_s390_vfmindb: 1768 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 1769 } 1770 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1771 } 1772 1773 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1774 /// This checks that the target supports __builtin_cpu_supports and 1775 /// that the string argument is constant and valid. 1776 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1777 Expr *Arg = TheCall->getArg(0); 1778 1779 // Check if the argument is a string literal. 1780 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1781 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1782 << Arg->getSourceRange(); 1783 1784 // Check the contents of the string. 1785 StringRef Feature = 1786 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1787 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1788 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1789 << Arg->getSourceRange(); 1790 return false; 1791 } 1792 1793 // Check if the rounding mode is legal. 1794 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1795 // Indicates if this instruction has rounding control or just SAE. 1796 bool HasRC = false; 1797 1798 unsigned ArgNum = 0; 1799 switch (BuiltinID) { 1800 default: 1801 return false; 1802 case X86::BI__builtin_ia32_vcvttsd2si32: 1803 case X86::BI__builtin_ia32_vcvttsd2si64: 1804 case X86::BI__builtin_ia32_vcvttsd2usi32: 1805 case X86::BI__builtin_ia32_vcvttsd2usi64: 1806 case X86::BI__builtin_ia32_vcvttss2si32: 1807 case X86::BI__builtin_ia32_vcvttss2si64: 1808 case X86::BI__builtin_ia32_vcvttss2usi32: 1809 case X86::BI__builtin_ia32_vcvttss2usi64: 1810 ArgNum = 1; 1811 break; 1812 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1813 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1814 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1815 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1816 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1817 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1818 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1819 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1820 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1821 case X86::BI__builtin_ia32_exp2pd_mask: 1822 case X86::BI__builtin_ia32_exp2ps_mask: 1823 case X86::BI__builtin_ia32_getexppd512_mask: 1824 case X86::BI__builtin_ia32_getexpps512_mask: 1825 case X86::BI__builtin_ia32_rcp28pd_mask: 1826 case X86::BI__builtin_ia32_rcp28ps_mask: 1827 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1828 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1829 case X86::BI__builtin_ia32_vcomisd: 1830 case X86::BI__builtin_ia32_vcomiss: 1831 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1832 ArgNum = 3; 1833 break; 1834 case X86::BI__builtin_ia32_cmppd512_mask: 1835 case X86::BI__builtin_ia32_cmpps512_mask: 1836 case X86::BI__builtin_ia32_cmpsd_mask: 1837 case X86::BI__builtin_ia32_cmpss_mask: 1838 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1839 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1840 case X86::BI__builtin_ia32_getexpss128_round_mask: 1841 case X86::BI__builtin_ia32_maxpd512_mask: 1842 case X86::BI__builtin_ia32_maxps512_mask: 1843 case X86::BI__builtin_ia32_maxsd_round_mask: 1844 case X86::BI__builtin_ia32_maxss_round_mask: 1845 case X86::BI__builtin_ia32_minpd512_mask: 1846 case X86::BI__builtin_ia32_minps512_mask: 1847 case X86::BI__builtin_ia32_minsd_round_mask: 1848 case X86::BI__builtin_ia32_minss_round_mask: 1849 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1850 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1851 case X86::BI__builtin_ia32_reducepd512_mask: 1852 case X86::BI__builtin_ia32_reduceps512_mask: 1853 case X86::BI__builtin_ia32_rndscalepd_mask: 1854 case X86::BI__builtin_ia32_rndscaleps_mask: 1855 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1856 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1857 ArgNum = 4; 1858 break; 1859 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1860 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1861 case X86::BI__builtin_ia32_fixupimmps512_mask: 1862 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1863 case X86::BI__builtin_ia32_fixupimmsd_mask: 1864 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1865 case X86::BI__builtin_ia32_fixupimmss_mask: 1866 case X86::BI__builtin_ia32_fixupimmss_maskz: 1867 case X86::BI__builtin_ia32_rangepd512_mask: 1868 case X86::BI__builtin_ia32_rangeps512_mask: 1869 case X86::BI__builtin_ia32_rangesd128_round_mask: 1870 case X86::BI__builtin_ia32_rangess128_round_mask: 1871 case X86::BI__builtin_ia32_reducesd_mask: 1872 case X86::BI__builtin_ia32_reducess_mask: 1873 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1874 case X86::BI__builtin_ia32_rndscaless_round_mask: 1875 ArgNum = 5; 1876 break; 1877 case X86::BI__builtin_ia32_vcvtsd2si64: 1878 case X86::BI__builtin_ia32_vcvtsd2si32: 1879 case X86::BI__builtin_ia32_vcvtsd2usi32: 1880 case X86::BI__builtin_ia32_vcvtsd2usi64: 1881 case X86::BI__builtin_ia32_vcvtss2si32: 1882 case X86::BI__builtin_ia32_vcvtss2si64: 1883 case X86::BI__builtin_ia32_vcvtss2usi32: 1884 case X86::BI__builtin_ia32_vcvtss2usi64: 1885 ArgNum = 1; 1886 HasRC = true; 1887 break; 1888 case X86::BI__builtin_ia32_cvtsi2sd64: 1889 case X86::BI__builtin_ia32_cvtsi2ss32: 1890 case X86::BI__builtin_ia32_cvtsi2ss64: 1891 case X86::BI__builtin_ia32_cvtusi2sd64: 1892 case X86::BI__builtin_ia32_cvtusi2ss32: 1893 case X86::BI__builtin_ia32_cvtusi2ss64: 1894 ArgNum = 2; 1895 HasRC = true; 1896 break; 1897 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1898 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1899 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1900 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1901 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1902 case X86::BI__builtin_ia32_cvtps2qq512_mask: 1903 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 1904 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 1905 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 1906 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 1907 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 1908 case X86::BI__builtin_ia32_sqrtpd512_mask: 1909 case X86::BI__builtin_ia32_sqrtps512_mask: 1910 ArgNum = 3; 1911 HasRC = true; 1912 break; 1913 case X86::BI__builtin_ia32_addpd512_mask: 1914 case X86::BI__builtin_ia32_addps512_mask: 1915 case X86::BI__builtin_ia32_divpd512_mask: 1916 case X86::BI__builtin_ia32_divps512_mask: 1917 case X86::BI__builtin_ia32_mulpd512_mask: 1918 case X86::BI__builtin_ia32_mulps512_mask: 1919 case X86::BI__builtin_ia32_subpd512_mask: 1920 case X86::BI__builtin_ia32_subps512_mask: 1921 case X86::BI__builtin_ia32_addss_round_mask: 1922 case X86::BI__builtin_ia32_addsd_round_mask: 1923 case X86::BI__builtin_ia32_divss_round_mask: 1924 case X86::BI__builtin_ia32_divsd_round_mask: 1925 case X86::BI__builtin_ia32_mulss_round_mask: 1926 case X86::BI__builtin_ia32_mulsd_round_mask: 1927 case X86::BI__builtin_ia32_subss_round_mask: 1928 case X86::BI__builtin_ia32_subsd_round_mask: 1929 case X86::BI__builtin_ia32_scalefpd512_mask: 1930 case X86::BI__builtin_ia32_scalefps512_mask: 1931 case X86::BI__builtin_ia32_scalefsd_round_mask: 1932 case X86::BI__builtin_ia32_scalefss_round_mask: 1933 case X86::BI__builtin_ia32_getmantpd512_mask: 1934 case X86::BI__builtin_ia32_getmantps512_mask: 1935 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 1936 case X86::BI__builtin_ia32_sqrtsd_round_mask: 1937 case X86::BI__builtin_ia32_sqrtss_round_mask: 1938 case X86::BI__builtin_ia32_vfmaddpd512_mask: 1939 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 1940 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 1941 case X86::BI__builtin_ia32_vfmaddps512_mask: 1942 case X86::BI__builtin_ia32_vfmaddps512_mask3: 1943 case X86::BI__builtin_ia32_vfmaddps512_maskz: 1944 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 1945 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 1946 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 1947 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 1948 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 1949 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 1950 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 1951 case X86::BI__builtin_ia32_vfmsubps512_mask3: 1952 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 1953 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 1954 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 1955 case X86::BI__builtin_ia32_vfnmaddps512_mask: 1956 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 1957 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 1958 case X86::BI__builtin_ia32_vfnmsubps512_mask: 1959 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 1960 case X86::BI__builtin_ia32_vfmaddsd3_mask: 1961 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 1962 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 1963 case X86::BI__builtin_ia32_vfmaddss3_mask: 1964 case X86::BI__builtin_ia32_vfmaddss3_maskz: 1965 case X86::BI__builtin_ia32_vfmaddss3_mask3: 1966 ArgNum = 4; 1967 HasRC = true; 1968 break; 1969 case X86::BI__builtin_ia32_getmantsd_round_mask: 1970 case X86::BI__builtin_ia32_getmantss_round_mask: 1971 ArgNum = 5; 1972 HasRC = true; 1973 break; 1974 } 1975 1976 llvm::APSInt Result; 1977 1978 // We can't check the value of a dependent argument. 1979 Expr *Arg = TheCall->getArg(ArgNum); 1980 if (Arg->isTypeDependent() || Arg->isValueDependent()) 1981 return false; 1982 1983 // Check constant-ness first. 1984 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 1985 return true; 1986 1987 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 1988 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 1989 // combined with ROUND_NO_EXC. 1990 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 1991 Result == 8/*ROUND_NO_EXC*/ || 1992 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 1993 return false; 1994 1995 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 1996 << Arg->getSourceRange(); 1997 } 1998 1999 // Check if the gather/scatter scale is legal. 2000 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2001 CallExpr *TheCall) { 2002 unsigned ArgNum = 0; 2003 switch (BuiltinID) { 2004 default: 2005 return false; 2006 case X86::BI__builtin_ia32_gatherpfdpd: 2007 case X86::BI__builtin_ia32_gatherpfdps: 2008 case X86::BI__builtin_ia32_gatherpfqpd: 2009 case X86::BI__builtin_ia32_gatherpfqps: 2010 case X86::BI__builtin_ia32_scatterpfdpd: 2011 case X86::BI__builtin_ia32_scatterpfdps: 2012 case X86::BI__builtin_ia32_scatterpfqpd: 2013 case X86::BI__builtin_ia32_scatterpfqps: 2014 ArgNum = 3; 2015 break; 2016 case X86::BI__builtin_ia32_gatherd_pd: 2017 case X86::BI__builtin_ia32_gatherd_pd256: 2018 case X86::BI__builtin_ia32_gatherq_pd: 2019 case X86::BI__builtin_ia32_gatherq_pd256: 2020 case X86::BI__builtin_ia32_gatherd_ps: 2021 case X86::BI__builtin_ia32_gatherd_ps256: 2022 case X86::BI__builtin_ia32_gatherq_ps: 2023 case X86::BI__builtin_ia32_gatherq_ps256: 2024 case X86::BI__builtin_ia32_gatherd_q: 2025 case X86::BI__builtin_ia32_gatherd_q256: 2026 case X86::BI__builtin_ia32_gatherq_q: 2027 case X86::BI__builtin_ia32_gatherq_q256: 2028 case X86::BI__builtin_ia32_gatherd_d: 2029 case X86::BI__builtin_ia32_gatherd_d256: 2030 case X86::BI__builtin_ia32_gatherq_d: 2031 case X86::BI__builtin_ia32_gatherq_d256: 2032 case X86::BI__builtin_ia32_gather3div2df: 2033 case X86::BI__builtin_ia32_gather3div2di: 2034 case X86::BI__builtin_ia32_gather3div4df: 2035 case X86::BI__builtin_ia32_gather3div4di: 2036 case X86::BI__builtin_ia32_gather3div4sf: 2037 case X86::BI__builtin_ia32_gather3div4si: 2038 case X86::BI__builtin_ia32_gather3div8sf: 2039 case X86::BI__builtin_ia32_gather3div8si: 2040 case X86::BI__builtin_ia32_gather3siv2df: 2041 case X86::BI__builtin_ia32_gather3siv2di: 2042 case X86::BI__builtin_ia32_gather3siv4df: 2043 case X86::BI__builtin_ia32_gather3siv4di: 2044 case X86::BI__builtin_ia32_gather3siv4sf: 2045 case X86::BI__builtin_ia32_gather3siv4si: 2046 case X86::BI__builtin_ia32_gather3siv8sf: 2047 case X86::BI__builtin_ia32_gather3siv8si: 2048 case X86::BI__builtin_ia32_gathersiv8df: 2049 case X86::BI__builtin_ia32_gathersiv16sf: 2050 case X86::BI__builtin_ia32_gatherdiv8df: 2051 case X86::BI__builtin_ia32_gatherdiv16sf: 2052 case X86::BI__builtin_ia32_gathersiv8di: 2053 case X86::BI__builtin_ia32_gathersiv16si: 2054 case X86::BI__builtin_ia32_gatherdiv8di: 2055 case X86::BI__builtin_ia32_gatherdiv16si: 2056 case X86::BI__builtin_ia32_scatterdiv2df: 2057 case X86::BI__builtin_ia32_scatterdiv2di: 2058 case X86::BI__builtin_ia32_scatterdiv4df: 2059 case X86::BI__builtin_ia32_scatterdiv4di: 2060 case X86::BI__builtin_ia32_scatterdiv4sf: 2061 case X86::BI__builtin_ia32_scatterdiv4si: 2062 case X86::BI__builtin_ia32_scatterdiv8sf: 2063 case X86::BI__builtin_ia32_scatterdiv8si: 2064 case X86::BI__builtin_ia32_scattersiv2df: 2065 case X86::BI__builtin_ia32_scattersiv2di: 2066 case X86::BI__builtin_ia32_scattersiv4df: 2067 case X86::BI__builtin_ia32_scattersiv4di: 2068 case X86::BI__builtin_ia32_scattersiv4sf: 2069 case X86::BI__builtin_ia32_scattersiv4si: 2070 case X86::BI__builtin_ia32_scattersiv8sf: 2071 case X86::BI__builtin_ia32_scattersiv8si: 2072 case X86::BI__builtin_ia32_scattersiv8df: 2073 case X86::BI__builtin_ia32_scattersiv16sf: 2074 case X86::BI__builtin_ia32_scatterdiv8df: 2075 case X86::BI__builtin_ia32_scatterdiv16sf: 2076 case X86::BI__builtin_ia32_scattersiv8di: 2077 case X86::BI__builtin_ia32_scattersiv16si: 2078 case X86::BI__builtin_ia32_scatterdiv8di: 2079 case X86::BI__builtin_ia32_scatterdiv16si: 2080 ArgNum = 4; 2081 break; 2082 } 2083 2084 llvm::APSInt Result; 2085 2086 // We can't check the value of a dependent argument. 2087 Expr *Arg = TheCall->getArg(ArgNum); 2088 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2089 return false; 2090 2091 // Check constant-ness first. 2092 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2093 return true; 2094 2095 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2096 return false; 2097 2098 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2099 << Arg->getSourceRange(); 2100 } 2101 2102 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2103 if (BuiltinID == X86::BI__builtin_cpu_supports) 2104 return SemaBuiltinCpuSupports(*this, TheCall); 2105 2106 // If the intrinsic has rounding or SAE make sure its valid. 2107 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2108 return true; 2109 2110 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2111 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2112 return true; 2113 2114 // For intrinsics which take an immediate value as part of the instruction, 2115 // range check them here. 2116 int i = 0, l = 0, u = 0; 2117 switch (BuiltinID) { 2118 default: 2119 return false; 2120 case X86::BI_mm_prefetch: 2121 i = 1; l = 0; u = 3; 2122 break; 2123 case X86::BI__builtin_ia32_sha1rnds4: 2124 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2125 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2126 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2127 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2128 i = 2; l = 0; u = 3; 2129 break; 2130 case X86::BI__builtin_ia32_vpermil2pd: 2131 case X86::BI__builtin_ia32_vpermil2pd256: 2132 case X86::BI__builtin_ia32_vpermil2ps: 2133 case X86::BI__builtin_ia32_vpermil2ps256: 2134 i = 3; l = 0; u = 3; 2135 break; 2136 case X86::BI__builtin_ia32_cmpb128_mask: 2137 case X86::BI__builtin_ia32_cmpw128_mask: 2138 case X86::BI__builtin_ia32_cmpd128_mask: 2139 case X86::BI__builtin_ia32_cmpq128_mask: 2140 case X86::BI__builtin_ia32_cmpb256_mask: 2141 case X86::BI__builtin_ia32_cmpw256_mask: 2142 case X86::BI__builtin_ia32_cmpd256_mask: 2143 case X86::BI__builtin_ia32_cmpq256_mask: 2144 case X86::BI__builtin_ia32_cmpb512_mask: 2145 case X86::BI__builtin_ia32_cmpw512_mask: 2146 case X86::BI__builtin_ia32_cmpd512_mask: 2147 case X86::BI__builtin_ia32_cmpq512_mask: 2148 case X86::BI__builtin_ia32_ucmpb128_mask: 2149 case X86::BI__builtin_ia32_ucmpw128_mask: 2150 case X86::BI__builtin_ia32_ucmpd128_mask: 2151 case X86::BI__builtin_ia32_ucmpq128_mask: 2152 case X86::BI__builtin_ia32_ucmpb256_mask: 2153 case X86::BI__builtin_ia32_ucmpw256_mask: 2154 case X86::BI__builtin_ia32_ucmpd256_mask: 2155 case X86::BI__builtin_ia32_ucmpq256_mask: 2156 case X86::BI__builtin_ia32_ucmpb512_mask: 2157 case X86::BI__builtin_ia32_ucmpw512_mask: 2158 case X86::BI__builtin_ia32_ucmpd512_mask: 2159 case X86::BI__builtin_ia32_ucmpq512_mask: 2160 case X86::BI__builtin_ia32_vpcomub: 2161 case X86::BI__builtin_ia32_vpcomuw: 2162 case X86::BI__builtin_ia32_vpcomud: 2163 case X86::BI__builtin_ia32_vpcomuq: 2164 case X86::BI__builtin_ia32_vpcomb: 2165 case X86::BI__builtin_ia32_vpcomw: 2166 case X86::BI__builtin_ia32_vpcomd: 2167 case X86::BI__builtin_ia32_vpcomq: 2168 i = 2; l = 0; u = 7; 2169 break; 2170 case X86::BI__builtin_ia32_roundps: 2171 case X86::BI__builtin_ia32_roundpd: 2172 case X86::BI__builtin_ia32_roundps256: 2173 case X86::BI__builtin_ia32_roundpd256: 2174 i = 1; l = 0; u = 15; 2175 break; 2176 case X86::BI__builtin_ia32_roundss: 2177 case X86::BI__builtin_ia32_roundsd: 2178 case X86::BI__builtin_ia32_rangepd128_mask: 2179 case X86::BI__builtin_ia32_rangepd256_mask: 2180 case X86::BI__builtin_ia32_rangepd512_mask: 2181 case X86::BI__builtin_ia32_rangeps128_mask: 2182 case X86::BI__builtin_ia32_rangeps256_mask: 2183 case X86::BI__builtin_ia32_rangeps512_mask: 2184 case X86::BI__builtin_ia32_getmantsd_round_mask: 2185 case X86::BI__builtin_ia32_getmantss_round_mask: 2186 i = 2; l = 0; u = 15; 2187 break; 2188 case X86::BI__builtin_ia32_cmpps: 2189 case X86::BI__builtin_ia32_cmpss: 2190 case X86::BI__builtin_ia32_cmppd: 2191 case X86::BI__builtin_ia32_cmpsd: 2192 case X86::BI__builtin_ia32_cmpps256: 2193 case X86::BI__builtin_ia32_cmppd256: 2194 case X86::BI__builtin_ia32_cmpps128_mask: 2195 case X86::BI__builtin_ia32_cmppd128_mask: 2196 case X86::BI__builtin_ia32_cmpps256_mask: 2197 case X86::BI__builtin_ia32_cmppd256_mask: 2198 case X86::BI__builtin_ia32_cmpps512_mask: 2199 case X86::BI__builtin_ia32_cmppd512_mask: 2200 case X86::BI__builtin_ia32_cmpsd_mask: 2201 case X86::BI__builtin_ia32_cmpss_mask: 2202 i = 2; l = 0; u = 31; 2203 break; 2204 case X86::BI__builtin_ia32_xabort: 2205 i = 0; l = -128; u = 255; 2206 break; 2207 case X86::BI__builtin_ia32_pshufw: 2208 case X86::BI__builtin_ia32_aeskeygenassist128: 2209 i = 1; l = -128; u = 255; 2210 break; 2211 case X86::BI__builtin_ia32_vcvtps2ph: 2212 case X86::BI__builtin_ia32_vcvtps2ph256: 2213 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2214 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2215 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2216 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2217 case X86::BI__builtin_ia32_rndscaleps_mask: 2218 case X86::BI__builtin_ia32_rndscalepd_mask: 2219 case X86::BI__builtin_ia32_reducepd128_mask: 2220 case X86::BI__builtin_ia32_reducepd256_mask: 2221 case X86::BI__builtin_ia32_reducepd512_mask: 2222 case X86::BI__builtin_ia32_reduceps128_mask: 2223 case X86::BI__builtin_ia32_reduceps256_mask: 2224 case X86::BI__builtin_ia32_reduceps512_mask: 2225 case X86::BI__builtin_ia32_prold512_mask: 2226 case X86::BI__builtin_ia32_prolq512_mask: 2227 case X86::BI__builtin_ia32_prold128_mask: 2228 case X86::BI__builtin_ia32_prold256_mask: 2229 case X86::BI__builtin_ia32_prolq128_mask: 2230 case X86::BI__builtin_ia32_prolq256_mask: 2231 case X86::BI__builtin_ia32_prord128_mask: 2232 case X86::BI__builtin_ia32_prord256_mask: 2233 case X86::BI__builtin_ia32_prorq128_mask: 2234 case X86::BI__builtin_ia32_prorq256_mask: 2235 case X86::BI__builtin_ia32_fpclasspd128_mask: 2236 case X86::BI__builtin_ia32_fpclasspd256_mask: 2237 case X86::BI__builtin_ia32_fpclassps128_mask: 2238 case X86::BI__builtin_ia32_fpclassps256_mask: 2239 case X86::BI__builtin_ia32_fpclassps512_mask: 2240 case X86::BI__builtin_ia32_fpclasspd512_mask: 2241 case X86::BI__builtin_ia32_fpclasssd_mask: 2242 case X86::BI__builtin_ia32_fpclassss_mask: 2243 i = 1; l = 0; u = 255; 2244 break; 2245 case X86::BI__builtin_ia32_palignr: 2246 case X86::BI__builtin_ia32_insertps128: 2247 case X86::BI__builtin_ia32_dpps: 2248 case X86::BI__builtin_ia32_dppd: 2249 case X86::BI__builtin_ia32_dpps256: 2250 case X86::BI__builtin_ia32_mpsadbw128: 2251 case X86::BI__builtin_ia32_mpsadbw256: 2252 case X86::BI__builtin_ia32_pcmpistrm128: 2253 case X86::BI__builtin_ia32_pcmpistri128: 2254 case X86::BI__builtin_ia32_pcmpistria128: 2255 case X86::BI__builtin_ia32_pcmpistric128: 2256 case X86::BI__builtin_ia32_pcmpistrio128: 2257 case X86::BI__builtin_ia32_pcmpistris128: 2258 case X86::BI__builtin_ia32_pcmpistriz128: 2259 case X86::BI__builtin_ia32_pclmulqdq128: 2260 case X86::BI__builtin_ia32_vperm2f128_pd256: 2261 case X86::BI__builtin_ia32_vperm2f128_ps256: 2262 case X86::BI__builtin_ia32_vperm2f128_si256: 2263 case X86::BI__builtin_ia32_permti256: 2264 i = 2; l = -128; u = 255; 2265 break; 2266 case X86::BI__builtin_ia32_palignr128: 2267 case X86::BI__builtin_ia32_palignr256: 2268 case X86::BI__builtin_ia32_palignr512_mask: 2269 case X86::BI__builtin_ia32_vcomisd: 2270 case X86::BI__builtin_ia32_vcomiss: 2271 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2272 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2273 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2274 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2275 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2276 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2277 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2278 i = 2; l = 0; u = 255; 2279 break; 2280 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2281 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2282 case X86::BI__builtin_ia32_fixupimmps512_mask: 2283 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2284 case X86::BI__builtin_ia32_fixupimmsd_mask: 2285 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2286 case X86::BI__builtin_ia32_fixupimmss_mask: 2287 case X86::BI__builtin_ia32_fixupimmss_maskz: 2288 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2289 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2290 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2291 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2292 case X86::BI__builtin_ia32_fixupimmps128_mask: 2293 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2294 case X86::BI__builtin_ia32_fixupimmps256_mask: 2295 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2296 case X86::BI__builtin_ia32_pternlogd512_mask: 2297 case X86::BI__builtin_ia32_pternlogd512_maskz: 2298 case X86::BI__builtin_ia32_pternlogq512_mask: 2299 case X86::BI__builtin_ia32_pternlogq512_maskz: 2300 case X86::BI__builtin_ia32_pternlogd128_mask: 2301 case X86::BI__builtin_ia32_pternlogd128_maskz: 2302 case X86::BI__builtin_ia32_pternlogd256_mask: 2303 case X86::BI__builtin_ia32_pternlogd256_maskz: 2304 case X86::BI__builtin_ia32_pternlogq128_mask: 2305 case X86::BI__builtin_ia32_pternlogq128_maskz: 2306 case X86::BI__builtin_ia32_pternlogq256_mask: 2307 case X86::BI__builtin_ia32_pternlogq256_maskz: 2308 i = 3; l = 0; u = 255; 2309 break; 2310 case X86::BI__builtin_ia32_gatherpfdpd: 2311 case X86::BI__builtin_ia32_gatherpfdps: 2312 case X86::BI__builtin_ia32_gatherpfqpd: 2313 case X86::BI__builtin_ia32_gatherpfqps: 2314 case X86::BI__builtin_ia32_scatterpfdpd: 2315 case X86::BI__builtin_ia32_scatterpfdps: 2316 case X86::BI__builtin_ia32_scatterpfqpd: 2317 case X86::BI__builtin_ia32_scatterpfqps: 2318 i = 4; l = 2; u = 3; 2319 break; 2320 case X86::BI__builtin_ia32_pcmpestrm128: 2321 case X86::BI__builtin_ia32_pcmpestri128: 2322 case X86::BI__builtin_ia32_pcmpestria128: 2323 case X86::BI__builtin_ia32_pcmpestric128: 2324 case X86::BI__builtin_ia32_pcmpestrio128: 2325 case X86::BI__builtin_ia32_pcmpestris128: 2326 case X86::BI__builtin_ia32_pcmpestriz128: 2327 i = 4; l = -128; u = 255; 2328 break; 2329 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2330 case X86::BI__builtin_ia32_rndscaless_round_mask: 2331 i = 4; l = 0; u = 255; 2332 break; 2333 } 2334 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2335 } 2336 2337 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2338 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2339 /// Returns true when the format fits the function and the FormatStringInfo has 2340 /// been populated. 2341 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2342 FormatStringInfo *FSI) { 2343 FSI->HasVAListArg = Format->getFirstArg() == 0; 2344 FSI->FormatIdx = Format->getFormatIdx() - 1; 2345 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2346 2347 // The way the format attribute works in GCC, the implicit this argument 2348 // of member functions is counted. However, it doesn't appear in our own 2349 // lists, so decrement format_idx in that case. 2350 if (IsCXXMember) { 2351 if(FSI->FormatIdx == 0) 2352 return false; 2353 --FSI->FormatIdx; 2354 if (FSI->FirstDataArg != 0) 2355 --FSI->FirstDataArg; 2356 } 2357 return true; 2358 } 2359 2360 /// Checks if a the given expression evaluates to null. 2361 /// 2362 /// \brief Returns true if the value evaluates to null. 2363 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2364 // If the expression has non-null type, it doesn't evaluate to null. 2365 if (auto nullability 2366 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2367 if (*nullability == NullabilityKind::NonNull) 2368 return false; 2369 } 2370 2371 // As a special case, transparent unions initialized with zero are 2372 // considered null for the purposes of the nonnull attribute. 2373 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2374 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2375 if (const CompoundLiteralExpr *CLE = 2376 dyn_cast<CompoundLiteralExpr>(Expr)) 2377 if (const InitListExpr *ILE = 2378 dyn_cast<InitListExpr>(CLE->getInitializer())) 2379 Expr = ILE->getInit(0); 2380 } 2381 2382 bool Result; 2383 return (!Expr->isValueDependent() && 2384 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2385 !Result); 2386 } 2387 2388 static void CheckNonNullArgument(Sema &S, 2389 const Expr *ArgExpr, 2390 SourceLocation CallSiteLoc) { 2391 if (CheckNonNullExpr(S, ArgExpr)) 2392 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2393 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2394 } 2395 2396 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2397 FormatStringInfo FSI; 2398 if ((GetFormatStringType(Format) == FST_NSString) && 2399 getFormatStringInfo(Format, false, &FSI)) { 2400 Idx = FSI.FormatIdx; 2401 return true; 2402 } 2403 return false; 2404 } 2405 /// \brief Diagnose use of %s directive in an NSString which is being passed 2406 /// as formatting string to formatting method. 2407 static void 2408 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2409 const NamedDecl *FDecl, 2410 Expr **Args, 2411 unsigned NumArgs) { 2412 unsigned Idx = 0; 2413 bool Format = false; 2414 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2415 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2416 Idx = 2; 2417 Format = true; 2418 } 2419 else 2420 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2421 if (S.GetFormatNSStringIdx(I, Idx)) { 2422 Format = true; 2423 break; 2424 } 2425 } 2426 if (!Format || NumArgs <= Idx) 2427 return; 2428 const Expr *FormatExpr = Args[Idx]; 2429 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2430 FormatExpr = CSCE->getSubExpr(); 2431 const StringLiteral *FormatString; 2432 if (const ObjCStringLiteral *OSL = 2433 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2434 FormatString = OSL->getString(); 2435 else 2436 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2437 if (!FormatString) 2438 return; 2439 if (S.FormatStringHasSArg(FormatString)) { 2440 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2441 << "%s" << 1 << 1; 2442 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2443 << FDecl->getDeclName(); 2444 } 2445 } 2446 2447 /// Determine whether the given type has a non-null nullability annotation. 2448 static bool isNonNullType(ASTContext &ctx, QualType type) { 2449 if (auto nullability = type->getNullability(ctx)) 2450 return *nullability == NullabilityKind::NonNull; 2451 2452 return false; 2453 } 2454 2455 static void CheckNonNullArguments(Sema &S, 2456 const NamedDecl *FDecl, 2457 const FunctionProtoType *Proto, 2458 ArrayRef<const Expr *> Args, 2459 SourceLocation CallSiteLoc) { 2460 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2461 2462 // Check the attributes attached to the method/function itself. 2463 llvm::SmallBitVector NonNullArgs; 2464 if (FDecl) { 2465 // Handle the nonnull attribute on the function/method declaration itself. 2466 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2467 if (!NonNull->args_size()) { 2468 // Easy case: all pointer arguments are nonnull. 2469 for (const auto *Arg : Args) 2470 if (S.isValidPointerAttrType(Arg->getType())) 2471 CheckNonNullArgument(S, Arg, CallSiteLoc); 2472 return; 2473 } 2474 2475 for (unsigned Val : NonNull->args()) { 2476 if (Val >= Args.size()) 2477 continue; 2478 if (NonNullArgs.empty()) 2479 NonNullArgs.resize(Args.size()); 2480 NonNullArgs.set(Val); 2481 } 2482 } 2483 } 2484 2485 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2486 // Handle the nonnull attribute on the parameters of the 2487 // function/method. 2488 ArrayRef<ParmVarDecl*> parms; 2489 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2490 parms = FD->parameters(); 2491 else 2492 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2493 2494 unsigned ParamIndex = 0; 2495 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2496 I != E; ++I, ++ParamIndex) { 2497 const ParmVarDecl *PVD = *I; 2498 if (PVD->hasAttr<NonNullAttr>() || 2499 isNonNullType(S.Context, PVD->getType())) { 2500 if (NonNullArgs.empty()) 2501 NonNullArgs.resize(Args.size()); 2502 2503 NonNullArgs.set(ParamIndex); 2504 } 2505 } 2506 } else { 2507 // If we have a non-function, non-method declaration but no 2508 // function prototype, try to dig out the function prototype. 2509 if (!Proto) { 2510 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2511 QualType type = VD->getType().getNonReferenceType(); 2512 if (auto pointerType = type->getAs<PointerType>()) 2513 type = pointerType->getPointeeType(); 2514 else if (auto blockType = type->getAs<BlockPointerType>()) 2515 type = blockType->getPointeeType(); 2516 // FIXME: data member pointers? 2517 2518 // Dig out the function prototype, if there is one. 2519 Proto = type->getAs<FunctionProtoType>(); 2520 } 2521 } 2522 2523 // Fill in non-null argument information from the nullability 2524 // information on the parameter types (if we have them). 2525 if (Proto) { 2526 unsigned Index = 0; 2527 for (auto paramType : Proto->getParamTypes()) { 2528 if (isNonNullType(S.Context, paramType)) { 2529 if (NonNullArgs.empty()) 2530 NonNullArgs.resize(Args.size()); 2531 2532 NonNullArgs.set(Index); 2533 } 2534 2535 ++Index; 2536 } 2537 } 2538 } 2539 2540 // Check for non-null arguments. 2541 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2542 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2543 if (NonNullArgs[ArgIndex]) 2544 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2545 } 2546 } 2547 2548 /// Handles the checks for format strings, non-POD arguments to vararg 2549 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2550 /// attributes. 2551 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2552 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2553 bool IsMemberFunction, SourceLocation Loc, 2554 SourceRange Range, VariadicCallType CallType) { 2555 // FIXME: We should check as much as we can in the template definition. 2556 if (CurContext->isDependentContext()) 2557 return; 2558 2559 // Printf and scanf checking. 2560 llvm::SmallBitVector CheckedVarArgs; 2561 if (FDecl) { 2562 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2563 // Only create vector if there are format attributes. 2564 CheckedVarArgs.resize(Args.size()); 2565 2566 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2567 CheckedVarArgs); 2568 } 2569 } 2570 2571 // Refuse POD arguments that weren't caught by the format string 2572 // checks above. 2573 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2574 if (CallType != VariadicDoesNotApply && 2575 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2576 unsigned NumParams = Proto ? Proto->getNumParams() 2577 : FDecl && isa<FunctionDecl>(FDecl) 2578 ? cast<FunctionDecl>(FDecl)->getNumParams() 2579 : FDecl && isa<ObjCMethodDecl>(FDecl) 2580 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2581 : 0; 2582 2583 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2584 // Args[ArgIdx] can be null in malformed code. 2585 if (const Expr *Arg = Args[ArgIdx]) { 2586 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2587 checkVariadicArgument(Arg, CallType); 2588 } 2589 } 2590 } 2591 2592 if (FDecl || Proto) { 2593 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2594 2595 // Type safety checking. 2596 if (FDecl) { 2597 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2598 CheckArgumentWithTypeTag(I, Args.data()); 2599 } 2600 } 2601 2602 if (FD) 2603 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 2604 } 2605 2606 /// CheckConstructorCall - Check a constructor call for correctness and safety 2607 /// properties not enforced by the C type system. 2608 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2609 ArrayRef<const Expr *> Args, 2610 const FunctionProtoType *Proto, 2611 SourceLocation Loc) { 2612 VariadicCallType CallType = 2613 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2614 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 2615 Loc, SourceRange(), CallType); 2616 } 2617 2618 /// CheckFunctionCall - Check a direct function call for various correctness 2619 /// and safety properties not strictly enforced by the C type system. 2620 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2621 const FunctionProtoType *Proto) { 2622 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2623 isa<CXXMethodDecl>(FDecl); 2624 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2625 IsMemberOperatorCall; 2626 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2627 TheCall->getCallee()); 2628 Expr** Args = TheCall->getArgs(); 2629 unsigned NumArgs = TheCall->getNumArgs(); 2630 2631 Expr *ImplicitThis = nullptr; 2632 if (IsMemberOperatorCall) { 2633 // If this is a call to a member operator, hide the first argument 2634 // from checkCall. 2635 // FIXME: Our choice of AST representation here is less than ideal. 2636 ImplicitThis = Args[0]; 2637 ++Args; 2638 --NumArgs; 2639 } else if (IsMemberFunction) 2640 ImplicitThis = 2641 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 2642 2643 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 2644 IsMemberFunction, TheCall->getRParenLoc(), 2645 TheCall->getCallee()->getSourceRange(), CallType); 2646 2647 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2648 // None of the checks below are needed for functions that don't have 2649 // simple names (e.g., C++ conversion functions). 2650 if (!FnInfo) 2651 return false; 2652 2653 CheckAbsoluteValueFunction(TheCall, FDecl); 2654 CheckMaxUnsignedZero(TheCall, FDecl); 2655 2656 if (getLangOpts().ObjC1) 2657 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2658 2659 unsigned CMId = FDecl->getMemoryFunctionKind(); 2660 if (CMId == 0) 2661 return false; 2662 2663 // Handle memory setting and copying functions. 2664 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2665 CheckStrlcpycatArguments(TheCall, FnInfo); 2666 else if (CMId == Builtin::BIstrncat) 2667 CheckStrncatArguments(TheCall, FnInfo); 2668 else 2669 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2670 2671 return false; 2672 } 2673 2674 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2675 ArrayRef<const Expr *> Args) { 2676 VariadicCallType CallType = 2677 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2678 2679 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 2680 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2681 CallType); 2682 2683 return false; 2684 } 2685 2686 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2687 const FunctionProtoType *Proto) { 2688 QualType Ty; 2689 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2690 Ty = V->getType().getNonReferenceType(); 2691 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2692 Ty = F->getType().getNonReferenceType(); 2693 else 2694 return false; 2695 2696 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2697 !Ty->isFunctionProtoType()) 2698 return false; 2699 2700 VariadicCallType CallType; 2701 if (!Proto || !Proto->isVariadic()) { 2702 CallType = VariadicDoesNotApply; 2703 } else if (Ty->isBlockPointerType()) { 2704 CallType = VariadicBlock; 2705 } else { // Ty->isFunctionPointerType() 2706 CallType = VariadicFunction; 2707 } 2708 2709 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 2710 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2711 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2712 TheCall->getCallee()->getSourceRange(), CallType); 2713 2714 return false; 2715 } 2716 2717 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2718 /// such as function pointers returned from functions. 2719 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2720 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2721 TheCall->getCallee()); 2722 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 2723 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2724 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2725 TheCall->getCallee()->getSourceRange(), CallType); 2726 2727 return false; 2728 } 2729 2730 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2731 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2732 return false; 2733 2734 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2735 switch (Op) { 2736 case AtomicExpr::AO__c11_atomic_init: 2737 llvm_unreachable("There is no ordering argument for an init"); 2738 2739 case AtomicExpr::AO__c11_atomic_load: 2740 case AtomicExpr::AO__atomic_load_n: 2741 case AtomicExpr::AO__atomic_load: 2742 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2743 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2744 2745 case AtomicExpr::AO__c11_atomic_store: 2746 case AtomicExpr::AO__atomic_store: 2747 case AtomicExpr::AO__atomic_store_n: 2748 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2749 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2750 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2751 2752 default: 2753 return true; 2754 } 2755 } 2756 2757 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2758 AtomicExpr::AtomicOp Op) { 2759 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2760 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2761 2762 // All these operations take one of the following forms: 2763 enum { 2764 // C __c11_atomic_init(A *, C) 2765 Init, 2766 // C __c11_atomic_load(A *, int) 2767 Load, 2768 // void __atomic_load(A *, CP, int) 2769 LoadCopy, 2770 // void __atomic_store(A *, CP, int) 2771 Copy, 2772 // C __c11_atomic_add(A *, M, int) 2773 Arithmetic, 2774 // C __atomic_exchange_n(A *, CP, int) 2775 Xchg, 2776 // void __atomic_exchange(A *, C *, CP, int) 2777 GNUXchg, 2778 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2779 C11CmpXchg, 2780 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2781 GNUCmpXchg 2782 } Form = Init; 2783 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2784 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2785 // where: 2786 // C is an appropriate type, 2787 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2788 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2789 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2790 // the int parameters are for orderings. 2791 2792 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2793 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2794 AtomicExpr::AO__atomic_load, 2795 "need to update code for modified C11 atomics"); 2796 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 2797 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 2798 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2799 Op == AtomicExpr::AO__atomic_store_n || 2800 Op == AtomicExpr::AO__atomic_exchange_n || 2801 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2802 bool IsAddSub = false; 2803 2804 switch (Op) { 2805 case AtomicExpr::AO__c11_atomic_init: 2806 Form = Init; 2807 break; 2808 2809 case AtomicExpr::AO__c11_atomic_load: 2810 case AtomicExpr::AO__atomic_load_n: 2811 Form = Load; 2812 break; 2813 2814 case AtomicExpr::AO__atomic_load: 2815 Form = LoadCopy; 2816 break; 2817 2818 case AtomicExpr::AO__c11_atomic_store: 2819 case AtomicExpr::AO__atomic_store: 2820 case AtomicExpr::AO__atomic_store_n: 2821 Form = Copy; 2822 break; 2823 2824 case AtomicExpr::AO__c11_atomic_fetch_add: 2825 case AtomicExpr::AO__c11_atomic_fetch_sub: 2826 case AtomicExpr::AO__atomic_fetch_add: 2827 case AtomicExpr::AO__atomic_fetch_sub: 2828 case AtomicExpr::AO__atomic_add_fetch: 2829 case AtomicExpr::AO__atomic_sub_fetch: 2830 IsAddSub = true; 2831 // Fall through. 2832 case AtomicExpr::AO__c11_atomic_fetch_and: 2833 case AtomicExpr::AO__c11_atomic_fetch_or: 2834 case AtomicExpr::AO__c11_atomic_fetch_xor: 2835 case AtomicExpr::AO__atomic_fetch_and: 2836 case AtomicExpr::AO__atomic_fetch_or: 2837 case AtomicExpr::AO__atomic_fetch_xor: 2838 case AtomicExpr::AO__atomic_fetch_nand: 2839 case AtomicExpr::AO__atomic_and_fetch: 2840 case AtomicExpr::AO__atomic_or_fetch: 2841 case AtomicExpr::AO__atomic_xor_fetch: 2842 case AtomicExpr::AO__atomic_nand_fetch: 2843 Form = Arithmetic; 2844 break; 2845 2846 case AtomicExpr::AO__c11_atomic_exchange: 2847 case AtomicExpr::AO__atomic_exchange_n: 2848 Form = Xchg; 2849 break; 2850 2851 case AtomicExpr::AO__atomic_exchange: 2852 Form = GNUXchg; 2853 break; 2854 2855 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2856 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2857 Form = C11CmpXchg; 2858 break; 2859 2860 case AtomicExpr::AO__atomic_compare_exchange: 2861 case AtomicExpr::AO__atomic_compare_exchange_n: 2862 Form = GNUCmpXchg; 2863 break; 2864 } 2865 2866 // Check we have the right number of arguments. 2867 if (TheCall->getNumArgs() < NumArgs[Form]) { 2868 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2869 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2870 << TheCall->getCallee()->getSourceRange(); 2871 return ExprError(); 2872 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 2873 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 2874 diag::err_typecheck_call_too_many_args) 2875 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2876 << TheCall->getCallee()->getSourceRange(); 2877 return ExprError(); 2878 } 2879 2880 // Inspect the first argument of the atomic operation. 2881 Expr *Ptr = TheCall->getArg(0); 2882 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2883 if (ConvertedPtr.isInvalid()) 2884 return ExprError(); 2885 2886 Ptr = ConvertedPtr.get(); 2887 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2888 if (!pointerType) { 2889 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2890 << Ptr->getType() << Ptr->getSourceRange(); 2891 return ExprError(); 2892 } 2893 2894 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2895 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2896 QualType ValType = AtomTy; // 'C' 2897 if (IsC11) { 2898 if (!AtomTy->isAtomicType()) { 2899 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 2900 << Ptr->getType() << Ptr->getSourceRange(); 2901 return ExprError(); 2902 } 2903 if (AtomTy.isConstQualified()) { 2904 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 2905 << Ptr->getType() << Ptr->getSourceRange(); 2906 return ExprError(); 2907 } 2908 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 2909 } else if (Form != Load && Form != LoadCopy) { 2910 if (ValType.isConstQualified()) { 2911 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 2912 << Ptr->getType() << Ptr->getSourceRange(); 2913 return ExprError(); 2914 } 2915 } 2916 2917 // For an arithmetic operation, the implied arithmetic must be well-formed. 2918 if (Form == Arithmetic) { 2919 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 2920 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 2921 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2922 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2923 return ExprError(); 2924 } 2925 if (!IsAddSub && !ValType->isIntegerType()) { 2926 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 2927 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2928 return ExprError(); 2929 } 2930 if (IsC11 && ValType->isPointerType() && 2931 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 2932 diag::err_incomplete_type)) { 2933 return ExprError(); 2934 } 2935 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 2936 // For __atomic_*_n operations, the value type must be a scalar integral or 2937 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 2938 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2939 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2940 return ExprError(); 2941 } 2942 2943 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 2944 !AtomTy->isScalarType()) { 2945 // For GNU atomics, require a trivially-copyable type. This is not part of 2946 // the GNU atomics specification, but we enforce it for sanity. 2947 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 2948 << Ptr->getType() << Ptr->getSourceRange(); 2949 return ExprError(); 2950 } 2951 2952 switch (ValType.getObjCLifetime()) { 2953 case Qualifiers::OCL_None: 2954 case Qualifiers::OCL_ExplicitNone: 2955 // okay 2956 break; 2957 2958 case Qualifiers::OCL_Weak: 2959 case Qualifiers::OCL_Strong: 2960 case Qualifiers::OCL_Autoreleasing: 2961 // FIXME: Can this happen? By this point, ValType should be known 2962 // to be trivially copyable. 2963 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 2964 << ValType << Ptr->getSourceRange(); 2965 return ExprError(); 2966 } 2967 2968 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 2969 // volatile-ness of the pointee-type inject itself into the result or the 2970 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 2971 ValType.removeLocalVolatile(); 2972 ValType.removeLocalConst(); 2973 QualType ResultType = ValType; 2974 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init) 2975 ResultType = Context.VoidTy; 2976 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 2977 ResultType = Context.BoolTy; 2978 2979 // The type of a parameter passed 'by value'. In the GNU atomics, such 2980 // arguments are actually passed as pointers. 2981 QualType ByValType = ValType; // 'CP' 2982 if (!IsC11 && !IsN) 2983 ByValType = Ptr->getType(); 2984 2985 // The first argument --- the pointer --- has a fixed type; we 2986 // deduce the types of the rest of the arguments accordingly. Walk 2987 // the remaining arguments, converting them to the deduced value type. 2988 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 2989 QualType Ty; 2990 if (i < NumVals[Form] + 1) { 2991 switch (i) { 2992 case 1: 2993 // The second argument is the non-atomic operand. For arithmetic, this 2994 // is always passed by value, and for a compare_exchange it is always 2995 // passed by address. For the rest, GNU uses by-address and C11 uses 2996 // by-value. 2997 assert(Form != Load); 2998 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 2999 Ty = ValType; 3000 else if (Form == Copy || Form == Xchg) 3001 Ty = ByValType; 3002 else if (Form == Arithmetic) 3003 Ty = Context.getPointerDiffType(); 3004 else { 3005 Expr *ValArg = TheCall->getArg(i); 3006 // Treat this argument as _Nonnull as we want to show a warning if 3007 // NULL is passed into it. 3008 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3009 unsigned AS = 0; 3010 // Keep address space of non-atomic pointer type. 3011 if (const PointerType *PtrTy = 3012 ValArg->getType()->getAs<PointerType>()) { 3013 AS = PtrTy->getPointeeType().getAddressSpace(); 3014 } 3015 Ty = Context.getPointerType( 3016 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3017 } 3018 break; 3019 case 2: 3020 // The third argument to compare_exchange / GNU exchange is a 3021 // (pointer to a) desired value. 3022 Ty = ByValType; 3023 break; 3024 case 3: 3025 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3026 Ty = Context.BoolTy; 3027 break; 3028 } 3029 } else { 3030 // The order(s) are always converted to int. 3031 Ty = Context.IntTy; 3032 } 3033 3034 InitializedEntity Entity = 3035 InitializedEntity::InitializeParameter(Context, Ty, false); 3036 ExprResult Arg = TheCall->getArg(i); 3037 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3038 if (Arg.isInvalid()) 3039 return true; 3040 TheCall->setArg(i, Arg.get()); 3041 } 3042 3043 // Permute the arguments into a 'consistent' order. 3044 SmallVector<Expr*, 5> SubExprs; 3045 SubExprs.push_back(Ptr); 3046 switch (Form) { 3047 case Init: 3048 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3049 SubExprs.push_back(TheCall->getArg(1)); // Val1 3050 break; 3051 case Load: 3052 SubExprs.push_back(TheCall->getArg(1)); // Order 3053 break; 3054 case LoadCopy: 3055 case Copy: 3056 case Arithmetic: 3057 case Xchg: 3058 SubExprs.push_back(TheCall->getArg(2)); // Order 3059 SubExprs.push_back(TheCall->getArg(1)); // Val1 3060 break; 3061 case GNUXchg: 3062 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3063 SubExprs.push_back(TheCall->getArg(3)); // Order 3064 SubExprs.push_back(TheCall->getArg(1)); // Val1 3065 SubExprs.push_back(TheCall->getArg(2)); // Val2 3066 break; 3067 case C11CmpXchg: 3068 SubExprs.push_back(TheCall->getArg(3)); // Order 3069 SubExprs.push_back(TheCall->getArg(1)); // Val1 3070 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3071 SubExprs.push_back(TheCall->getArg(2)); // Val2 3072 break; 3073 case GNUCmpXchg: 3074 SubExprs.push_back(TheCall->getArg(4)); // Order 3075 SubExprs.push_back(TheCall->getArg(1)); // Val1 3076 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3077 SubExprs.push_back(TheCall->getArg(2)); // Val2 3078 SubExprs.push_back(TheCall->getArg(3)); // Weak 3079 break; 3080 } 3081 3082 if (SubExprs.size() >= 2 && Form != Init) { 3083 llvm::APSInt Result(32); 3084 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3085 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3086 Diag(SubExprs[1]->getLocStart(), 3087 diag::warn_atomic_op_has_invalid_memory_order) 3088 << SubExprs[1]->getSourceRange(); 3089 } 3090 3091 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3092 SubExprs, ResultType, Op, 3093 TheCall->getRParenLoc()); 3094 3095 if ((Op == AtomicExpr::AO__c11_atomic_load || 3096 (Op == AtomicExpr::AO__c11_atomic_store)) && 3097 Context.AtomicUsesUnsupportedLibcall(AE)) 3098 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 3099 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 3100 3101 return AE; 3102 } 3103 3104 /// checkBuiltinArgument - Given a call to a builtin function, perform 3105 /// normal type-checking on the given argument, updating the call in 3106 /// place. This is useful when a builtin function requires custom 3107 /// type-checking for some of its arguments but not necessarily all of 3108 /// them. 3109 /// 3110 /// Returns true on error. 3111 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3112 FunctionDecl *Fn = E->getDirectCallee(); 3113 assert(Fn && "builtin call without direct callee!"); 3114 3115 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3116 InitializedEntity Entity = 3117 InitializedEntity::InitializeParameter(S.Context, Param); 3118 3119 ExprResult Arg = E->getArg(0); 3120 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3121 if (Arg.isInvalid()) 3122 return true; 3123 3124 E->setArg(ArgIndex, Arg.get()); 3125 return false; 3126 } 3127 3128 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3129 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3130 /// type of its first argument. The main ActOnCallExpr routines have already 3131 /// promoted the types of arguments because all of these calls are prototyped as 3132 /// void(...). 3133 /// 3134 /// This function goes through and does final semantic checking for these 3135 /// builtins, 3136 ExprResult 3137 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3138 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3139 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3140 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3141 3142 // Ensure that we have at least one argument to do type inference from. 3143 if (TheCall->getNumArgs() < 1) { 3144 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3145 << 0 << 1 << TheCall->getNumArgs() 3146 << TheCall->getCallee()->getSourceRange(); 3147 return ExprError(); 3148 } 3149 3150 // Inspect the first argument of the atomic builtin. This should always be 3151 // a pointer type, whose element is an integral scalar or pointer type. 3152 // Because it is a pointer type, we don't have to worry about any implicit 3153 // casts here. 3154 // FIXME: We don't allow floating point scalars as input. 3155 Expr *FirstArg = TheCall->getArg(0); 3156 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3157 if (FirstArgResult.isInvalid()) 3158 return ExprError(); 3159 FirstArg = FirstArgResult.get(); 3160 TheCall->setArg(0, FirstArg); 3161 3162 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3163 if (!pointerType) { 3164 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3165 << FirstArg->getType() << FirstArg->getSourceRange(); 3166 return ExprError(); 3167 } 3168 3169 QualType ValType = pointerType->getPointeeType(); 3170 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3171 !ValType->isBlockPointerType()) { 3172 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3173 << FirstArg->getType() << FirstArg->getSourceRange(); 3174 return ExprError(); 3175 } 3176 3177 switch (ValType.getObjCLifetime()) { 3178 case Qualifiers::OCL_None: 3179 case Qualifiers::OCL_ExplicitNone: 3180 // okay 3181 break; 3182 3183 case Qualifiers::OCL_Weak: 3184 case Qualifiers::OCL_Strong: 3185 case Qualifiers::OCL_Autoreleasing: 3186 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3187 << ValType << FirstArg->getSourceRange(); 3188 return ExprError(); 3189 } 3190 3191 // Strip any qualifiers off ValType. 3192 ValType = ValType.getUnqualifiedType(); 3193 3194 // The majority of builtins return a value, but a few have special return 3195 // types, so allow them to override appropriately below. 3196 QualType ResultType = ValType; 3197 3198 // We need to figure out which concrete builtin this maps onto. For example, 3199 // __sync_fetch_and_add with a 2 byte object turns into 3200 // __sync_fetch_and_add_2. 3201 #define BUILTIN_ROW(x) \ 3202 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3203 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3204 3205 static const unsigned BuiltinIndices[][5] = { 3206 BUILTIN_ROW(__sync_fetch_and_add), 3207 BUILTIN_ROW(__sync_fetch_and_sub), 3208 BUILTIN_ROW(__sync_fetch_and_or), 3209 BUILTIN_ROW(__sync_fetch_and_and), 3210 BUILTIN_ROW(__sync_fetch_and_xor), 3211 BUILTIN_ROW(__sync_fetch_and_nand), 3212 3213 BUILTIN_ROW(__sync_add_and_fetch), 3214 BUILTIN_ROW(__sync_sub_and_fetch), 3215 BUILTIN_ROW(__sync_and_and_fetch), 3216 BUILTIN_ROW(__sync_or_and_fetch), 3217 BUILTIN_ROW(__sync_xor_and_fetch), 3218 BUILTIN_ROW(__sync_nand_and_fetch), 3219 3220 BUILTIN_ROW(__sync_val_compare_and_swap), 3221 BUILTIN_ROW(__sync_bool_compare_and_swap), 3222 BUILTIN_ROW(__sync_lock_test_and_set), 3223 BUILTIN_ROW(__sync_lock_release), 3224 BUILTIN_ROW(__sync_swap) 3225 }; 3226 #undef BUILTIN_ROW 3227 3228 // Determine the index of the size. 3229 unsigned SizeIndex; 3230 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3231 case 1: SizeIndex = 0; break; 3232 case 2: SizeIndex = 1; break; 3233 case 4: SizeIndex = 2; break; 3234 case 8: SizeIndex = 3; break; 3235 case 16: SizeIndex = 4; break; 3236 default: 3237 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3238 << FirstArg->getType() << FirstArg->getSourceRange(); 3239 return ExprError(); 3240 } 3241 3242 // Each of these builtins has one pointer argument, followed by some number of 3243 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3244 // that we ignore. Find out which row of BuiltinIndices to read from as well 3245 // as the number of fixed args. 3246 unsigned BuiltinID = FDecl->getBuiltinID(); 3247 unsigned BuiltinIndex, NumFixed = 1; 3248 bool WarnAboutSemanticsChange = false; 3249 switch (BuiltinID) { 3250 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3251 case Builtin::BI__sync_fetch_and_add: 3252 case Builtin::BI__sync_fetch_and_add_1: 3253 case Builtin::BI__sync_fetch_and_add_2: 3254 case Builtin::BI__sync_fetch_and_add_4: 3255 case Builtin::BI__sync_fetch_and_add_8: 3256 case Builtin::BI__sync_fetch_and_add_16: 3257 BuiltinIndex = 0; 3258 break; 3259 3260 case Builtin::BI__sync_fetch_and_sub: 3261 case Builtin::BI__sync_fetch_and_sub_1: 3262 case Builtin::BI__sync_fetch_and_sub_2: 3263 case Builtin::BI__sync_fetch_and_sub_4: 3264 case Builtin::BI__sync_fetch_and_sub_8: 3265 case Builtin::BI__sync_fetch_and_sub_16: 3266 BuiltinIndex = 1; 3267 break; 3268 3269 case Builtin::BI__sync_fetch_and_or: 3270 case Builtin::BI__sync_fetch_and_or_1: 3271 case Builtin::BI__sync_fetch_and_or_2: 3272 case Builtin::BI__sync_fetch_and_or_4: 3273 case Builtin::BI__sync_fetch_and_or_8: 3274 case Builtin::BI__sync_fetch_and_or_16: 3275 BuiltinIndex = 2; 3276 break; 3277 3278 case Builtin::BI__sync_fetch_and_and: 3279 case Builtin::BI__sync_fetch_and_and_1: 3280 case Builtin::BI__sync_fetch_and_and_2: 3281 case Builtin::BI__sync_fetch_and_and_4: 3282 case Builtin::BI__sync_fetch_and_and_8: 3283 case Builtin::BI__sync_fetch_and_and_16: 3284 BuiltinIndex = 3; 3285 break; 3286 3287 case Builtin::BI__sync_fetch_and_xor: 3288 case Builtin::BI__sync_fetch_and_xor_1: 3289 case Builtin::BI__sync_fetch_and_xor_2: 3290 case Builtin::BI__sync_fetch_and_xor_4: 3291 case Builtin::BI__sync_fetch_and_xor_8: 3292 case Builtin::BI__sync_fetch_and_xor_16: 3293 BuiltinIndex = 4; 3294 break; 3295 3296 case Builtin::BI__sync_fetch_and_nand: 3297 case Builtin::BI__sync_fetch_and_nand_1: 3298 case Builtin::BI__sync_fetch_and_nand_2: 3299 case Builtin::BI__sync_fetch_and_nand_4: 3300 case Builtin::BI__sync_fetch_and_nand_8: 3301 case Builtin::BI__sync_fetch_and_nand_16: 3302 BuiltinIndex = 5; 3303 WarnAboutSemanticsChange = true; 3304 break; 3305 3306 case Builtin::BI__sync_add_and_fetch: 3307 case Builtin::BI__sync_add_and_fetch_1: 3308 case Builtin::BI__sync_add_and_fetch_2: 3309 case Builtin::BI__sync_add_and_fetch_4: 3310 case Builtin::BI__sync_add_and_fetch_8: 3311 case Builtin::BI__sync_add_and_fetch_16: 3312 BuiltinIndex = 6; 3313 break; 3314 3315 case Builtin::BI__sync_sub_and_fetch: 3316 case Builtin::BI__sync_sub_and_fetch_1: 3317 case Builtin::BI__sync_sub_and_fetch_2: 3318 case Builtin::BI__sync_sub_and_fetch_4: 3319 case Builtin::BI__sync_sub_and_fetch_8: 3320 case Builtin::BI__sync_sub_and_fetch_16: 3321 BuiltinIndex = 7; 3322 break; 3323 3324 case Builtin::BI__sync_and_and_fetch: 3325 case Builtin::BI__sync_and_and_fetch_1: 3326 case Builtin::BI__sync_and_and_fetch_2: 3327 case Builtin::BI__sync_and_and_fetch_4: 3328 case Builtin::BI__sync_and_and_fetch_8: 3329 case Builtin::BI__sync_and_and_fetch_16: 3330 BuiltinIndex = 8; 3331 break; 3332 3333 case Builtin::BI__sync_or_and_fetch: 3334 case Builtin::BI__sync_or_and_fetch_1: 3335 case Builtin::BI__sync_or_and_fetch_2: 3336 case Builtin::BI__sync_or_and_fetch_4: 3337 case Builtin::BI__sync_or_and_fetch_8: 3338 case Builtin::BI__sync_or_and_fetch_16: 3339 BuiltinIndex = 9; 3340 break; 3341 3342 case Builtin::BI__sync_xor_and_fetch: 3343 case Builtin::BI__sync_xor_and_fetch_1: 3344 case Builtin::BI__sync_xor_and_fetch_2: 3345 case Builtin::BI__sync_xor_and_fetch_4: 3346 case Builtin::BI__sync_xor_and_fetch_8: 3347 case Builtin::BI__sync_xor_and_fetch_16: 3348 BuiltinIndex = 10; 3349 break; 3350 3351 case Builtin::BI__sync_nand_and_fetch: 3352 case Builtin::BI__sync_nand_and_fetch_1: 3353 case Builtin::BI__sync_nand_and_fetch_2: 3354 case Builtin::BI__sync_nand_and_fetch_4: 3355 case Builtin::BI__sync_nand_and_fetch_8: 3356 case Builtin::BI__sync_nand_and_fetch_16: 3357 BuiltinIndex = 11; 3358 WarnAboutSemanticsChange = true; 3359 break; 3360 3361 case Builtin::BI__sync_val_compare_and_swap: 3362 case Builtin::BI__sync_val_compare_and_swap_1: 3363 case Builtin::BI__sync_val_compare_and_swap_2: 3364 case Builtin::BI__sync_val_compare_and_swap_4: 3365 case Builtin::BI__sync_val_compare_and_swap_8: 3366 case Builtin::BI__sync_val_compare_and_swap_16: 3367 BuiltinIndex = 12; 3368 NumFixed = 2; 3369 break; 3370 3371 case Builtin::BI__sync_bool_compare_and_swap: 3372 case Builtin::BI__sync_bool_compare_and_swap_1: 3373 case Builtin::BI__sync_bool_compare_and_swap_2: 3374 case Builtin::BI__sync_bool_compare_and_swap_4: 3375 case Builtin::BI__sync_bool_compare_and_swap_8: 3376 case Builtin::BI__sync_bool_compare_and_swap_16: 3377 BuiltinIndex = 13; 3378 NumFixed = 2; 3379 ResultType = Context.BoolTy; 3380 break; 3381 3382 case Builtin::BI__sync_lock_test_and_set: 3383 case Builtin::BI__sync_lock_test_and_set_1: 3384 case Builtin::BI__sync_lock_test_and_set_2: 3385 case Builtin::BI__sync_lock_test_and_set_4: 3386 case Builtin::BI__sync_lock_test_and_set_8: 3387 case Builtin::BI__sync_lock_test_and_set_16: 3388 BuiltinIndex = 14; 3389 break; 3390 3391 case Builtin::BI__sync_lock_release: 3392 case Builtin::BI__sync_lock_release_1: 3393 case Builtin::BI__sync_lock_release_2: 3394 case Builtin::BI__sync_lock_release_4: 3395 case Builtin::BI__sync_lock_release_8: 3396 case Builtin::BI__sync_lock_release_16: 3397 BuiltinIndex = 15; 3398 NumFixed = 0; 3399 ResultType = Context.VoidTy; 3400 break; 3401 3402 case Builtin::BI__sync_swap: 3403 case Builtin::BI__sync_swap_1: 3404 case Builtin::BI__sync_swap_2: 3405 case Builtin::BI__sync_swap_4: 3406 case Builtin::BI__sync_swap_8: 3407 case Builtin::BI__sync_swap_16: 3408 BuiltinIndex = 16; 3409 break; 3410 } 3411 3412 // Now that we know how many fixed arguments we expect, first check that we 3413 // have at least that many. 3414 if (TheCall->getNumArgs() < 1+NumFixed) { 3415 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3416 << 0 << 1+NumFixed << TheCall->getNumArgs() 3417 << TheCall->getCallee()->getSourceRange(); 3418 return ExprError(); 3419 } 3420 3421 if (WarnAboutSemanticsChange) { 3422 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3423 << TheCall->getCallee()->getSourceRange(); 3424 } 3425 3426 // Get the decl for the concrete builtin from this, we can tell what the 3427 // concrete integer type we should convert to is. 3428 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3429 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3430 FunctionDecl *NewBuiltinDecl; 3431 if (NewBuiltinID == BuiltinID) 3432 NewBuiltinDecl = FDecl; 3433 else { 3434 // Perform builtin lookup to avoid redeclaring it. 3435 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3436 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3437 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3438 assert(Res.getFoundDecl()); 3439 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3440 if (!NewBuiltinDecl) 3441 return ExprError(); 3442 } 3443 3444 // The first argument --- the pointer --- has a fixed type; we 3445 // deduce the types of the rest of the arguments accordingly. Walk 3446 // the remaining arguments, converting them to the deduced value type. 3447 for (unsigned i = 0; i != NumFixed; ++i) { 3448 ExprResult Arg = TheCall->getArg(i+1); 3449 3450 // GCC does an implicit conversion to the pointer or integer ValType. This 3451 // can fail in some cases (1i -> int**), check for this error case now. 3452 // Initialize the argument. 3453 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3454 ValType, /*consume*/ false); 3455 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3456 if (Arg.isInvalid()) 3457 return ExprError(); 3458 3459 // Okay, we have something that *can* be converted to the right type. Check 3460 // to see if there is a potentially weird extension going on here. This can 3461 // happen when you do an atomic operation on something like an char* and 3462 // pass in 42. The 42 gets converted to char. This is even more strange 3463 // for things like 45.123 -> char, etc. 3464 // FIXME: Do this check. 3465 TheCall->setArg(i+1, Arg.get()); 3466 } 3467 3468 ASTContext& Context = this->getASTContext(); 3469 3470 // Create a new DeclRefExpr to refer to the new decl. 3471 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3472 Context, 3473 DRE->getQualifierLoc(), 3474 SourceLocation(), 3475 NewBuiltinDecl, 3476 /*enclosing*/ false, 3477 DRE->getLocation(), 3478 Context.BuiltinFnTy, 3479 DRE->getValueKind()); 3480 3481 // Set the callee in the CallExpr. 3482 // FIXME: This loses syntactic information. 3483 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3484 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3485 CK_BuiltinFnToFnPtr); 3486 TheCall->setCallee(PromotedCall.get()); 3487 3488 // Change the result type of the call to match the original value type. This 3489 // is arbitrary, but the codegen for these builtins ins design to handle it 3490 // gracefully. 3491 TheCall->setType(ResultType); 3492 3493 return TheCallResult; 3494 } 3495 3496 /// SemaBuiltinNontemporalOverloaded - We have a call to 3497 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3498 /// overloaded function based on the pointer type of its last argument. 3499 /// 3500 /// This function goes through and does final semantic checking for these 3501 /// builtins. 3502 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3503 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3504 DeclRefExpr *DRE = 3505 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3506 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3507 unsigned BuiltinID = FDecl->getBuiltinID(); 3508 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3509 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3510 "Unexpected nontemporal load/store builtin!"); 3511 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3512 unsigned numArgs = isStore ? 2 : 1; 3513 3514 // Ensure that we have the proper number of arguments. 3515 if (checkArgCount(*this, TheCall, numArgs)) 3516 return ExprError(); 3517 3518 // Inspect the last argument of the nontemporal builtin. This should always 3519 // be a pointer type, from which we imply the type of the memory access. 3520 // Because it is a pointer type, we don't have to worry about any implicit 3521 // casts here. 3522 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3523 ExprResult PointerArgResult = 3524 DefaultFunctionArrayLvalueConversion(PointerArg); 3525 3526 if (PointerArgResult.isInvalid()) 3527 return ExprError(); 3528 PointerArg = PointerArgResult.get(); 3529 TheCall->setArg(numArgs - 1, PointerArg); 3530 3531 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3532 if (!pointerType) { 3533 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3534 << PointerArg->getType() << PointerArg->getSourceRange(); 3535 return ExprError(); 3536 } 3537 3538 QualType ValType = pointerType->getPointeeType(); 3539 3540 // Strip any qualifiers off ValType. 3541 ValType = ValType.getUnqualifiedType(); 3542 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3543 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3544 !ValType->isVectorType()) { 3545 Diag(DRE->getLocStart(), 3546 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3547 << PointerArg->getType() << PointerArg->getSourceRange(); 3548 return ExprError(); 3549 } 3550 3551 if (!isStore) { 3552 TheCall->setType(ValType); 3553 return TheCallResult; 3554 } 3555 3556 ExprResult ValArg = TheCall->getArg(0); 3557 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3558 Context, ValType, /*consume*/ false); 3559 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3560 if (ValArg.isInvalid()) 3561 return ExprError(); 3562 3563 TheCall->setArg(0, ValArg.get()); 3564 TheCall->setType(Context.VoidTy); 3565 return TheCallResult; 3566 } 3567 3568 /// CheckObjCString - Checks that the argument to the builtin 3569 /// CFString constructor is correct 3570 /// Note: It might also make sense to do the UTF-16 conversion here (would 3571 /// simplify the backend). 3572 bool Sema::CheckObjCString(Expr *Arg) { 3573 Arg = Arg->IgnoreParenCasts(); 3574 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3575 3576 if (!Literal || !Literal->isAscii()) { 3577 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3578 << Arg->getSourceRange(); 3579 return true; 3580 } 3581 3582 if (Literal->containsNonAsciiOrNull()) { 3583 StringRef String = Literal->getString(); 3584 unsigned NumBytes = String.size(); 3585 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3586 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3587 llvm::UTF16 *ToPtr = &ToBuf[0]; 3588 3589 llvm::ConversionResult Result = 3590 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3591 ToPtr + NumBytes, llvm::strictConversion); 3592 // Check for conversion failure. 3593 if (Result != llvm::conversionOK) 3594 Diag(Arg->getLocStart(), 3595 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3596 } 3597 return false; 3598 } 3599 3600 /// CheckObjCString - Checks that the format string argument to the os_log() 3601 /// and os_trace() functions is correct, and converts it to const char *. 3602 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3603 Arg = Arg->IgnoreParenCasts(); 3604 auto *Literal = dyn_cast<StringLiteral>(Arg); 3605 if (!Literal) { 3606 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3607 Literal = ObjcLiteral->getString(); 3608 } 3609 } 3610 3611 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3612 return ExprError( 3613 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3614 << Arg->getSourceRange()); 3615 } 3616 3617 ExprResult Result(Literal); 3618 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3619 InitializedEntity Entity = 3620 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3621 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3622 return Result; 3623 } 3624 3625 /// Check that the user is calling the appropriate va_start builtin for the 3626 /// target and calling convention. 3627 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 3628 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 3629 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 3630 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 3631 bool IsWindows = TT.isOSWindows(); 3632 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 3633 if (IsX64 || IsAArch64) { 3634 clang::CallingConv CC = CC_C; 3635 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 3636 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3637 if (IsMSVAStart) { 3638 // Don't allow this in System V ABI functions. 3639 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 3640 return S.Diag(Fn->getLocStart(), 3641 diag::err_ms_va_start_used_in_sysv_function); 3642 } else { 3643 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 3644 // On x64 Windows, don't allow this in System V ABI functions. 3645 // (Yes, that means there's no corresponding way to support variadic 3646 // System V ABI functions on Windows.) 3647 if ((IsWindows && CC == CC_X86_64SysV) || 3648 (!IsWindows && CC == CC_Win64)) 3649 return S.Diag(Fn->getLocStart(), 3650 diag::err_va_start_used_in_wrong_abi_function) 3651 << !IsWindows; 3652 } 3653 return false; 3654 } 3655 3656 if (IsMSVAStart) 3657 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 3658 return false; 3659 } 3660 3661 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 3662 ParmVarDecl **LastParam = nullptr) { 3663 // Determine whether the current function, block, or obj-c method is variadic 3664 // and get its parameter list. 3665 bool IsVariadic = false; 3666 ArrayRef<ParmVarDecl *> Params; 3667 DeclContext *Caller = S.CurContext; 3668 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 3669 IsVariadic = Block->isVariadic(); 3670 Params = Block->parameters(); 3671 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 3672 IsVariadic = FD->isVariadic(); 3673 Params = FD->parameters(); 3674 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 3675 IsVariadic = MD->isVariadic(); 3676 // FIXME: This isn't correct for methods (results in bogus warning). 3677 Params = MD->parameters(); 3678 } else if (isa<CapturedDecl>(Caller)) { 3679 // We don't support va_start in a CapturedDecl. 3680 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 3681 return true; 3682 } else { 3683 // This must be some other declcontext that parses exprs. 3684 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 3685 return true; 3686 } 3687 3688 if (!IsVariadic) { 3689 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 3690 return true; 3691 } 3692 3693 if (LastParam) 3694 *LastParam = Params.empty() ? nullptr : Params.back(); 3695 3696 return false; 3697 } 3698 3699 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3700 /// for validity. Emit an error and return true on failure; return false 3701 /// on success. 3702 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 3703 Expr *Fn = TheCall->getCallee(); 3704 3705 if (checkVAStartABI(*this, BuiltinID, Fn)) 3706 return true; 3707 3708 if (TheCall->getNumArgs() > 2) { 3709 Diag(TheCall->getArg(2)->getLocStart(), 3710 diag::err_typecheck_call_too_many_args) 3711 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3712 << Fn->getSourceRange() 3713 << SourceRange(TheCall->getArg(2)->getLocStart(), 3714 (*(TheCall->arg_end()-1))->getLocEnd()); 3715 return true; 3716 } 3717 3718 if (TheCall->getNumArgs() < 2) { 3719 return Diag(TheCall->getLocEnd(), 3720 diag::err_typecheck_call_too_few_args_at_least) 3721 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3722 } 3723 3724 // Type-check the first argument normally. 3725 if (checkBuiltinArgument(*this, TheCall, 0)) 3726 return true; 3727 3728 // Check that the current function is variadic, and get its last parameter. 3729 ParmVarDecl *LastParam; 3730 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 3731 return true; 3732 3733 // Verify that the second argument to the builtin is the last argument of the 3734 // current function or method. 3735 bool SecondArgIsLastNamedArgument = false; 3736 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3737 3738 // These are valid if SecondArgIsLastNamedArgument is false after the next 3739 // block. 3740 QualType Type; 3741 SourceLocation ParamLoc; 3742 bool IsCRegister = false; 3743 3744 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3745 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3746 SecondArgIsLastNamedArgument = PV == LastParam; 3747 3748 Type = PV->getType(); 3749 ParamLoc = PV->getLocation(); 3750 IsCRegister = 3751 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3752 } 3753 } 3754 3755 if (!SecondArgIsLastNamedArgument) 3756 Diag(TheCall->getArg(1)->getLocStart(), 3757 diag::warn_second_arg_of_va_start_not_last_named_param); 3758 else if (IsCRegister || Type->isReferenceType() || 3759 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3760 // Promotable integers are UB, but enumerations need a bit of 3761 // extra checking to see what their promotable type actually is. 3762 if (!Type->isPromotableIntegerType()) 3763 return false; 3764 if (!Type->isEnumeralType()) 3765 return true; 3766 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3767 return !(ED && 3768 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3769 }()) { 3770 unsigned Reason = 0; 3771 if (Type->isReferenceType()) Reason = 1; 3772 else if (IsCRegister) Reason = 2; 3773 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3774 Diag(ParamLoc, diag::note_parameter_type) << Type; 3775 } 3776 3777 TheCall->setType(Context.VoidTy); 3778 return false; 3779 } 3780 3781 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3782 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3783 // const char *named_addr); 3784 3785 Expr *Func = Call->getCallee(); 3786 3787 if (Call->getNumArgs() < 3) 3788 return Diag(Call->getLocEnd(), 3789 diag::err_typecheck_call_too_few_args_at_least) 3790 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3791 3792 // Type-check the first argument normally. 3793 if (checkBuiltinArgument(*this, Call, 0)) 3794 return true; 3795 3796 // Check that the current function is variadic. 3797 if (checkVAStartIsInVariadicFunction(*this, Func)) 3798 return true; 3799 3800 const struct { 3801 unsigned ArgNo; 3802 QualType Type; 3803 } ArgumentTypes[] = { 3804 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3805 { 2, Context.getSizeType() }, 3806 }; 3807 3808 for (const auto &AT : ArgumentTypes) { 3809 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3810 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3811 continue; 3812 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3813 << Arg->getType() << AT.Type << 1 /* different class */ 3814 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3815 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3816 } 3817 3818 return false; 3819 } 3820 3821 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3822 /// friends. This is declared to take (...), so we have to check everything. 3823 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3824 if (TheCall->getNumArgs() < 2) 3825 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3826 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3827 if (TheCall->getNumArgs() > 2) 3828 return Diag(TheCall->getArg(2)->getLocStart(), 3829 diag::err_typecheck_call_too_many_args) 3830 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3831 << SourceRange(TheCall->getArg(2)->getLocStart(), 3832 (*(TheCall->arg_end()-1))->getLocEnd()); 3833 3834 ExprResult OrigArg0 = TheCall->getArg(0); 3835 ExprResult OrigArg1 = TheCall->getArg(1); 3836 3837 // Do standard promotions between the two arguments, returning their common 3838 // type. 3839 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3840 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3841 return true; 3842 3843 // Make sure any conversions are pushed back into the call; this is 3844 // type safe since unordered compare builtins are declared as "_Bool 3845 // foo(...)". 3846 TheCall->setArg(0, OrigArg0.get()); 3847 TheCall->setArg(1, OrigArg1.get()); 3848 3849 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3850 return false; 3851 3852 // If the common type isn't a real floating type, then the arguments were 3853 // invalid for this operation. 3854 if (Res.isNull() || !Res->isRealFloatingType()) 3855 return Diag(OrigArg0.get()->getLocStart(), 3856 diag::err_typecheck_call_invalid_ordered_compare) 3857 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3858 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3859 3860 return false; 3861 } 3862 3863 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3864 /// __builtin_isnan and friends. This is declared to take (...), so we have 3865 /// to check everything. We expect the last argument to be a floating point 3866 /// value. 3867 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3868 if (TheCall->getNumArgs() < NumArgs) 3869 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3870 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3871 if (TheCall->getNumArgs() > NumArgs) 3872 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3873 diag::err_typecheck_call_too_many_args) 3874 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3875 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3876 (*(TheCall->arg_end()-1))->getLocEnd()); 3877 3878 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3879 3880 if (OrigArg->isTypeDependent()) 3881 return false; 3882 3883 // This operation requires a non-_Complex floating-point number. 3884 if (!OrigArg->getType()->isRealFloatingType()) 3885 return Diag(OrigArg->getLocStart(), 3886 diag::err_typecheck_call_invalid_unary_fp) 3887 << OrigArg->getType() << OrigArg->getSourceRange(); 3888 3889 // If this is an implicit conversion from float -> float or double, remove it. 3890 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 3891 // Only remove standard FloatCasts, leaving other casts inplace 3892 if (Cast->getCastKind() == CK_FloatingCast) { 3893 Expr *CastArg = Cast->getSubExpr(); 3894 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 3895 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 3896 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 3897 "promotion from float to either float or double is the only expected cast here"); 3898 Cast->setSubExpr(nullptr); 3899 TheCall->setArg(NumArgs-1, CastArg); 3900 } 3901 } 3902 } 3903 3904 return false; 3905 } 3906 3907 // Customized Sema Checking for VSX builtins that have the following signature: 3908 // vector [...] builtinName(vector [...], vector [...], const int); 3909 // Which takes the same type of vectors (any legal vector type) for the first 3910 // two arguments and takes compile time constant for the third argument. 3911 // Example builtins are : 3912 // vector double vec_xxpermdi(vector double, vector double, int); 3913 // vector short vec_xxsldwi(vector short, vector short, int); 3914 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 3915 unsigned ExpectedNumArgs = 3; 3916 if (TheCall->getNumArgs() < ExpectedNumArgs) 3917 return Diag(TheCall->getLocEnd(), 3918 diag::err_typecheck_call_too_few_args_at_least) 3919 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 3920 << TheCall->getSourceRange(); 3921 3922 if (TheCall->getNumArgs() > ExpectedNumArgs) 3923 return Diag(TheCall->getLocEnd(), 3924 diag::err_typecheck_call_too_many_args_at_most) 3925 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 3926 << TheCall->getSourceRange(); 3927 3928 // Check the third argument is a compile time constant 3929 llvm::APSInt Value; 3930 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 3931 return Diag(TheCall->getLocStart(), 3932 diag::err_vsx_builtin_nonconstant_argument) 3933 << 3 /* argument index */ << TheCall->getDirectCallee() 3934 << SourceRange(TheCall->getArg(2)->getLocStart(), 3935 TheCall->getArg(2)->getLocEnd()); 3936 3937 QualType Arg1Ty = TheCall->getArg(0)->getType(); 3938 QualType Arg2Ty = TheCall->getArg(1)->getType(); 3939 3940 // Check the type of argument 1 and argument 2 are vectors. 3941 SourceLocation BuiltinLoc = TheCall->getLocStart(); 3942 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 3943 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 3944 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 3945 << TheCall->getDirectCallee() 3946 << SourceRange(TheCall->getArg(0)->getLocStart(), 3947 TheCall->getArg(1)->getLocEnd()); 3948 } 3949 3950 // Check the first two arguments are the same type. 3951 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 3952 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 3953 << TheCall->getDirectCallee() 3954 << SourceRange(TheCall->getArg(0)->getLocStart(), 3955 TheCall->getArg(1)->getLocEnd()); 3956 } 3957 3958 // When default clang type checking is turned off and the customized type 3959 // checking is used, the returning type of the function must be explicitly 3960 // set. Otherwise it is _Bool by default. 3961 TheCall->setType(Arg1Ty); 3962 3963 return false; 3964 } 3965 3966 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 3967 // This is declared to take (...), so we have to check everything. 3968 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 3969 if (TheCall->getNumArgs() < 2) 3970 return ExprError(Diag(TheCall->getLocEnd(), 3971 diag::err_typecheck_call_too_few_args_at_least) 3972 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3973 << TheCall->getSourceRange()); 3974 3975 // Determine which of the following types of shufflevector we're checking: 3976 // 1) unary, vector mask: (lhs, mask) 3977 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 3978 QualType resType = TheCall->getArg(0)->getType(); 3979 unsigned numElements = 0; 3980 3981 if (!TheCall->getArg(0)->isTypeDependent() && 3982 !TheCall->getArg(1)->isTypeDependent()) { 3983 QualType LHSType = TheCall->getArg(0)->getType(); 3984 QualType RHSType = TheCall->getArg(1)->getType(); 3985 3986 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 3987 return ExprError(Diag(TheCall->getLocStart(), 3988 diag::err_vec_builtin_non_vector) 3989 << TheCall->getDirectCallee() 3990 << SourceRange(TheCall->getArg(0)->getLocStart(), 3991 TheCall->getArg(1)->getLocEnd())); 3992 3993 numElements = LHSType->getAs<VectorType>()->getNumElements(); 3994 unsigned numResElements = TheCall->getNumArgs() - 2; 3995 3996 // Check to see if we have a call with 2 vector arguments, the unary shuffle 3997 // with mask. If so, verify that RHS is an integer vector type with the 3998 // same number of elts as lhs. 3999 if (TheCall->getNumArgs() == 2) { 4000 if (!RHSType->hasIntegerRepresentation() || 4001 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4002 return ExprError(Diag(TheCall->getLocStart(), 4003 diag::err_vec_builtin_incompatible_vector) 4004 << TheCall->getDirectCallee() 4005 << SourceRange(TheCall->getArg(1)->getLocStart(), 4006 TheCall->getArg(1)->getLocEnd())); 4007 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4008 return ExprError(Diag(TheCall->getLocStart(), 4009 diag::err_vec_builtin_incompatible_vector) 4010 << TheCall->getDirectCallee() 4011 << SourceRange(TheCall->getArg(0)->getLocStart(), 4012 TheCall->getArg(1)->getLocEnd())); 4013 } else if (numElements != numResElements) { 4014 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4015 resType = Context.getVectorType(eltType, numResElements, 4016 VectorType::GenericVector); 4017 } 4018 } 4019 4020 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4021 if (TheCall->getArg(i)->isTypeDependent() || 4022 TheCall->getArg(i)->isValueDependent()) 4023 continue; 4024 4025 llvm::APSInt Result(32); 4026 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4027 return ExprError(Diag(TheCall->getLocStart(), 4028 diag::err_shufflevector_nonconstant_argument) 4029 << TheCall->getArg(i)->getSourceRange()); 4030 4031 // Allow -1 which will be translated to undef in the IR. 4032 if (Result.isSigned() && Result.isAllOnesValue()) 4033 continue; 4034 4035 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4036 return ExprError(Diag(TheCall->getLocStart(), 4037 diag::err_shufflevector_argument_too_large) 4038 << TheCall->getArg(i)->getSourceRange()); 4039 } 4040 4041 SmallVector<Expr*, 32> exprs; 4042 4043 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4044 exprs.push_back(TheCall->getArg(i)); 4045 TheCall->setArg(i, nullptr); 4046 } 4047 4048 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4049 TheCall->getCallee()->getLocStart(), 4050 TheCall->getRParenLoc()); 4051 } 4052 4053 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4054 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4055 SourceLocation BuiltinLoc, 4056 SourceLocation RParenLoc) { 4057 ExprValueKind VK = VK_RValue; 4058 ExprObjectKind OK = OK_Ordinary; 4059 QualType DstTy = TInfo->getType(); 4060 QualType SrcTy = E->getType(); 4061 4062 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4063 return ExprError(Diag(BuiltinLoc, 4064 diag::err_convertvector_non_vector) 4065 << E->getSourceRange()); 4066 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4067 return ExprError(Diag(BuiltinLoc, 4068 diag::err_convertvector_non_vector_type)); 4069 4070 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4071 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4072 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4073 if (SrcElts != DstElts) 4074 return ExprError(Diag(BuiltinLoc, 4075 diag::err_convertvector_incompatible_vector) 4076 << E->getSourceRange()); 4077 } 4078 4079 return new (Context) 4080 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4081 } 4082 4083 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4084 // This is declared to take (const void*, ...) and can take two 4085 // optional constant int args. 4086 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4087 unsigned NumArgs = TheCall->getNumArgs(); 4088 4089 if (NumArgs > 3) 4090 return Diag(TheCall->getLocEnd(), 4091 diag::err_typecheck_call_too_many_args_at_most) 4092 << 0 /*function call*/ << 3 << NumArgs 4093 << TheCall->getSourceRange(); 4094 4095 // Argument 0 is checked for us and the remaining arguments must be 4096 // constant integers. 4097 for (unsigned i = 1; i != NumArgs; ++i) 4098 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4099 return true; 4100 4101 return false; 4102 } 4103 4104 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4105 // __assume does not evaluate its arguments, and should warn if its argument 4106 // has side effects. 4107 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4108 Expr *Arg = TheCall->getArg(0); 4109 if (Arg->isInstantiationDependent()) return false; 4110 4111 if (Arg->HasSideEffects(Context)) 4112 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4113 << Arg->getSourceRange() 4114 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4115 4116 return false; 4117 } 4118 4119 /// Handle __builtin_alloca_with_align. This is declared 4120 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4121 /// than 8. 4122 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4123 // The alignment must be a constant integer. 4124 Expr *Arg = TheCall->getArg(1); 4125 4126 // We can't check the value of a dependent argument. 4127 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4128 if (const auto *UE = 4129 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4130 if (UE->getKind() == UETT_AlignOf) 4131 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4132 << Arg->getSourceRange(); 4133 4134 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4135 4136 if (!Result.isPowerOf2()) 4137 return Diag(TheCall->getLocStart(), 4138 diag::err_alignment_not_power_of_two) 4139 << Arg->getSourceRange(); 4140 4141 if (Result < Context.getCharWidth()) 4142 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4143 << (unsigned)Context.getCharWidth() 4144 << Arg->getSourceRange(); 4145 4146 if (Result > INT32_MAX) 4147 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4148 << INT32_MAX 4149 << Arg->getSourceRange(); 4150 } 4151 4152 return false; 4153 } 4154 4155 /// Handle __builtin_assume_aligned. This is declared 4156 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4157 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4158 unsigned NumArgs = TheCall->getNumArgs(); 4159 4160 if (NumArgs > 3) 4161 return Diag(TheCall->getLocEnd(), 4162 diag::err_typecheck_call_too_many_args_at_most) 4163 << 0 /*function call*/ << 3 << NumArgs 4164 << TheCall->getSourceRange(); 4165 4166 // The alignment must be a constant integer. 4167 Expr *Arg = TheCall->getArg(1); 4168 4169 // We can't check the value of a dependent argument. 4170 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4171 llvm::APSInt Result; 4172 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4173 return true; 4174 4175 if (!Result.isPowerOf2()) 4176 return Diag(TheCall->getLocStart(), 4177 diag::err_alignment_not_power_of_two) 4178 << Arg->getSourceRange(); 4179 } 4180 4181 if (NumArgs > 2) { 4182 ExprResult Arg(TheCall->getArg(2)); 4183 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4184 Context.getSizeType(), false); 4185 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4186 if (Arg.isInvalid()) return true; 4187 TheCall->setArg(2, Arg.get()); 4188 } 4189 4190 return false; 4191 } 4192 4193 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4194 unsigned BuiltinID = 4195 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4196 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4197 4198 unsigned NumArgs = TheCall->getNumArgs(); 4199 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4200 if (NumArgs < NumRequiredArgs) { 4201 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4202 << 0 /* function call */ << NumRequiredArgs << NumArgs 4203 << TheCall->getSourceRange(); 4204 } 4205 if (NumArgs >= NumRequiredArgs + 0x100) { 4206 return Diag(TheCall->getLocEnd(), 4207 diag::err_typecheck_call_too_many_args_at_most) 4208 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4209 << TheCall->getSourceRange(); 4210 } 4211 unsigned i = 0; 4212 4213 // For formatting call, check buffer arg. 4214 if (!IsSizeCall) { 4215 ExprResult Arg(TheCall->getArg(i)); 4216 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4217 Context, Context.VoidPtrTy, false); 4218 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4219 if (Arg.isInvalid()) 4220 return true; 4221 TheCall->setArg(i, Arg.get()); 4222 i++; 4223 } 4224 4225 // Check string literal arg. 4226 unsigned FormatIdx = i; 4227 { 4228 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4229 if (Arg.isInvalid()) 4230 return true; 4231 TheCall->setArg(i, Arg.get()); 4232 i++; 4233 } 4234 4235 // Make sure variadic args are scalar. 4236 unsigned FirstDataArg = i; 4237 while (i < NumArgs) { 4238 ExprResult Arg = DefaultVariadicArgumentPromotion( 4239 TheCall->getArg(i), VariadicFunction, nullptr); 4240 if (Arg.isInvalid()) 4241 return true; 4242 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4243 if (ArgSize.getQuantity() >= 0x100) { 4244 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4245 << i << (int)ArgSize.getQuantity() << 0xff 4246 << TheCall->getSourceRange(); 4247 } 4248 TheCall->setArg(i, Arg.get()); 4249 i++; 4250 } 4251 4252 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4253 // call to avoid duplicate diagnostics. 4254 if (!IsSizeCall) { 4255 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4256 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4257 bool Success = CheckFormatArguments( 4258 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4259 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4260 CheckedVarArgs); 4261 if (!Success) 4262 return true; 4263 } 4264 4265 if (IsSizeCall) { 4266 TheCall->setType(Context.getSizeType()); 4267 } else { 4268 TheCall->setType(Context.VoidPtrTy); 4269 } 4270 return false; 4271 } 4272 4273 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4274 /// TheCall is a constant expression. 4275 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4276 llvm::APSInt &Result) { 4277 Expr *Arg = TheCall->getArg(ArgNum); 4278 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4279 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4280 4281 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4282 4283 if (!Arg->isIntegerConstantExpr(Result, Context)) 4284 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4285 << FDecl->getDeclName() << Arg->getSourceRange(); 4286 4287 return false; 4288 } 4289 4290 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4291 /// TheCall is a constant expression in the range [Low, High]. 4292 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4293 int Low, int High) { 4294 llvm::APSInt Result; 4295 4296 // We can't check the value of a dependent argument. 4297 Expr *Arg = TheCall->getArg(ArgNum); 4298 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4299 return false; 4300 4301 // Check constant-ness first. 4302 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4303 return true; 4304 4305 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4306 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4307 << Low << High << Arg->getSourceRange(); 4308 4309 return false; 4310 } 4311 4312 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4313 /// TheCall is a constant expression is a multiple of Num.. 4314 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4315 unsigned Num) { 4316 llvm::APSInt Result; 4317 4318 // We can't check the value of a dependent argument. 4319 Expr *Arg = TheCall->getArg(ArgNum); 4320 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4321 return false; 4322 4323 // Check constant-ness first. 4324 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4325 return true; 4326 4327 if (Result.getSExtValue() % Num != 0) 4328 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4329 << Num << Arg->getSourceRange(); 4330 4331 return false; 4332 } 4333 4334 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4335 /// TheCall is an ARM/AArch64 special register string literal. 4336 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4337 int ArgNum, unsigned ExpectedFieldNum, 4338 bool AllowName) { 4339 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4340 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4341 BuiltinID == ARM::BI__builtin_arm_rsr || 4342 BuiltinID == ARM::BI__builtin_arm_rsrp || 4343 BuiltinID == ARM::BI__builtin_arm_wsr || 4344 BuiltinID == ARM::BI__builtin_arm_wsrp; 4345 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4346 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4347 BuiltinID == AArch64::BI__builtin_arm_rsr || 4348 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4349 BuiltinID == AArch64::BI__builtin_arm_wsr || 4350 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4351 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4352 4353 // We can't check the value of a dependent argument. 4354 Expr *Arg = TheCall->getArg(ArgNum); 4355 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4356 return false; 4357 4358 // Check if the argument is a string literal. 4359 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4360 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4361 << Arg->getSourceRange(); 4362 4363 // Check the type of special register given. 4364 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4365 SmallVector<StringRef, 6> Fields; 4366 Reg.split(Fields, ":"); 4367 4368 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4369 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4370 << Arg->getSourceRange(); 4371 4372 // If the string is the name of a register then we cannot check that it is 4373 // valid here but if the string is of one the forms described in ACLE then we 4374 // can check that the supplied fields are integers and within the valid 4375 // ranges. 4376 if (Fields.size() > 1) { 4377 bool FiveFields = Fields.size() == 5; 4378 4379 bool ValidString = true; 4380 if (IsARMBuiltin) { 4381 ValidString &= Fields[0].startswith_lower("cp") || 4382 Fields[0].startswith_lower("p"); 4383 if (ValidString) 4384 Fields[0] = 4385 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4386 4387 ValidString &= Fields[2].startswith_lower("c"); 4388 if (ValidString) 4389 Fields[2] = Fields[2].drop_front(1); 4390 4391 if (FiveFields) { 4392 ValidString &= Fields[3].startswith_lower("c"); 4393 if (ValidString) 4394 Fields[3] = Fields[3].drop_front(1); 4395 } 4396 } 4397 4398 SmallVector<int, 5> Ranges; 4399 if (FiveFields) 4400 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4401 else 4402 Ranges.append({15, 7, 15}); 4403 4404 for (unsigned i=0; i<Fields.size(); ++i) { 4405 int IntField; 4406 ValidString &= !Fields[i].getAsInteger(10, IntField); 4407 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4408 } 4409 4410 if (!ValidString) 4411 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4412 << Arg->getSourceRange(); 4413 4414 } else if (IsAArch64Builtin && Fields.size() == 1) { 4415 // If the register name is one of those that appear in the condition below 4416 // and the special register builtin being used is one of the write builtins, 4417 // then we require that the argument provided for writing to the register 4418 // is an integer constant expression. This is because it will be lowered to 4419 // an MSR (immediate) instruction, so we need to know the immediate at 4420 // compile time. 4421 if (TheCall->getNumArgs() != 2) 4422 return false; 4423 4424 std::string RegLower = Reg.lower(); 4425 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4426 RegLower != "pan" && RegLower != "uao") 4427 return false; 4428 4429 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4430 } 4431 4432 return false; 4433 } 4434 4435 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4436 /// This checks that the target supports __builtin_longjmp and 4437 /// that val is a constant 1. 4438 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4439 if (!Context.getTargetInfo().hasSjLjLowering()) 4440 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4441 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4442 4443 Expr *Arg = TheCall->getArg(1); 4444 llvm::APSInt Result; 4445 4446 // TODO: This is less than ideal. Overload this to take a value. 4447 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4448 return true; 4449 4450 if (Result != 1) 4451 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4452 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4453 4454 return false; 4455 } 4456 4457 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4458 /// This checks that the target supports __builtin_setjmp. 4459 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4460 if (!Context.getTargetInfo().hasSjLjLowering()) 4461 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4462 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4463 return false; 4464 } 4465 4466 namespace { 4467 class UncoveredArgHandler { 4468 enum { Unknown = -1, AllCovered = -2 }; 4469 signed FirstUncoveredArg; 4470 SmallVector<const Expr *, 4> DiagnosticExprs; 4471 4472 public: 4473 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4474 4475 bool hasUncoveredArg() const { 4476 return (FirstUncoveredArg >= 0); 4477 } 4478 4479 unsigned getUncoveredArg() const { 4480 assert(hasUncoveredArg() && "no uncovered argument"); 4481 return FirstUncoveredArg; 4482 } 4483 4484 void setAllCovered() { 4485 // A string has been found with all arguments covered, so clear out 4486 // the diagnostics. 4487 DiagnosticExprs.clear(); 4488 FirstUncoveredArg = AllCovered; 4489 } 4490 4491 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4492 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4493 4494 // Don't update if a previous string covers all arguments. 4495 if (FirstUncoveredArg == AllCovered) 4496 return; 4497 4498 // UncoveredArgHandler tracks the highest uncovered argument index 4499 // and with it all the strings that match this index. 4500 if (NewFirstUncoveredArg == FirstUncoveredArg) 4501 DiagnosticExprs.push_back(StrExpr); 4502 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4503 DiagnosticExprs.clear(); 4504 DiagnosticExprs.push_back(StrExpr); 4505 FirstUncoveredArg = NewFirstUncoveredArg; 4506 } 4507 } 4508 4509 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4510 }; 4511 4512 enum StringLiteralCheckType { 4513 SLCT_NotALiteral, 4514 SLCT_UncheckedLiteral, 4515 SLCT_CheckedLiteral 4516 }; 4517 } // end anonymous namespace 4518 4519 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4520 BinaryOperatorKind BinOpKind, 4521 bool AddendIsRight) { 4522 unsigned BitWidth = Offset.getBitWidth(); 4523 unsigned AddendBitWidth = Addend.getBitWidth(); 4524 // There might be negative interim results. 4525 if (Addend.isUnsigned()) { 4526 Addend = Addend.zext(++AddendBitWidth); 4527 Addend.setIsSigned(true); 4528 } 4529 // Adjust the bit width of the APSInts. 4530 if (AddendBitWidth > BitWidth) { 4531 Offset = Offset.sext(AddendBitWidth); 4532 BitWidth = AddendBitWidth; 4533 } else if (BitWidth > AddendBitWidth) { 4534 Addend = Addend.sext(BitWidth); 4535 } 4536 4537 bool Ov = false; 4538 llvm::APSInt ResOffset = Offset; 4539 if (BinOpKind == BO_Add) 4540 ResOffset = Offset.sadd_ov(Addend, Ov); 4541 else { 4542 assert(AddendIsRight && BinOpKind == BO_Sub && 4543 "operator must be add or sub with addend on the right"); 4544 ResOffset = Offset.ssub_ov(Addend, Ov); 4545 } 4546 4547 // We add an offset to a pointer here so we should support an offset as big as 4548 // possible. 4549 if (Ov) { 4550 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4551 Offset = Offset.sext(2 * BitWidth); 4552 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4553 return; 4554 } 4555 4556 Offset = ResOffset; 4557 } 4558 4559 namespace { 4560 // This is a wrapper class around StringLiteral to support offsetted string 4561 // literals as format strings. It takes the offset into account when returning 4562 // the string and its length or the source locations to display notes correctly. 4563 class FormatStringLiteral { 4564 const StringLiteral *FExpr; 4565 int64_t Offset; 4566 4567 public: 4568 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4569 : FExpr(fexpr), Offset(Offset) {} 4570 4571 StringRef getString() const { 4572 return FExpr->getString().drop_front(Offset); 4573 } 4574 4575 unsigned getByteLength() const { 4576 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4577 } 4578 unsigned getLength() const { return FExpr->getLength() - Offset; } 4579 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4580 4581 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4582 4583 QualType getType() const { return FExpr->getType(); } 4584 4585 bool isAscii() const { return FExpr->isAscii(); } 4586 bool isWide() const { return FExpr->isWide(); } 4587 bool isUTF8() const { return FExpr->isUTF8(); } 4588 bool isUTF16() const { return FExpr->isUTF16(); } 4589 bool isUTF32() const { return FExpr->isUTF32(); } 4590 bool isPascal() const { return FExpr->isPascal(); } 4591 4592 SourceLocation getLocationOfByte( 4593 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4594 const TargetInfo &Target, unsigned *StartToken = nullptr, 4595 unsigned *StartTokenByteOffset = nullptr) const { 4596 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4597 StartToken, StartTokenByteOffset); 4598 } 4599 4600 SourceLocation getLocStart() const LLVM_READONLY { 4601 return FExpr->getLocStart().getLocWithOffset(Offset); 4602 } 4603 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4604 }; 4605 } // end anonymous namespace 4606 4607 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4608 const Expr *OrigFormatExpr, 4609 ArrayRef<const Expr *> Args, 4610 bool HasVAListArg, unsigned format_idx, 4611 unsigned firstDataArg, 4612 Sema::FormatStringType Type, 4613 bool inFunctionCall, 4614 Sema::VariadicCallType CallType, 4615 llvm::SmallBitVector &CheckedVarArgs, 4616 UncoveredArgHandler &UncoveredArg); 4617 4618 // Determine if an expression is a string literal or constant string. 4619 // If this function returns false on the arguments to a function expecting a 4620 // format string, we will usually need to emit a warning. 4621 // True string literals are then checked by CheckFormatString. 4622 static StringLiteralCheckType 4623 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4624 bool HasVAListArg, unsigned format_idx, 4625 unsigned firstDataArg, Sema::FormatStringType Type, 4626 Sema::VariadicCallType CallType, bool InFunctionCall, 4627 llvm::SmallBitVector &CheckedVarArgs, 4628 UncoveredArgHandler &UncoveredArg, 4629 llvm::APSInt Offset) { 4630 tryAgain: 4631 assert(Offset.isSigned() && "invalid offset"); 4632 4633 if (E->isTypeDependent() || E->isValueDependent()) 4634 return SLCT_NotALiteral; 4635 4636 E = E->IgnoreParenCasts(); 4637 4638 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4639 // Technically -Wformat-nonliteral does not warn about this case. 4640 // The behavior of printf and friends in this case is implementation 4641 // dependent. Ideally if the format string cannot be null then 4642 // it should have a 'nonnull' attribute in the function prototype. 4643 return SLCT_UncheckedLiteral; 4644 4645 switch (E->getStmtClass()) { 4646 case Stmt::BinaryConditionalOperatorClass: 4647 case Stmt::ConditionalOperatorClass: { 4648 // The expression is a literal if both sub-expressions were, and it was 4649 // completely checked only if both sub-expressions were checked. 4650 const AbstractConditionalOperator *C = 4651 cast<AbstractConditionalOperator>(E); 4652 4653 // Determine whether it is necessary to check both sub-expressions, for 4654 // example, because the condition expression is a constant that can be 4655 // evaluated at compile time. 4656 bool CheckLeft = true, CheckRight = true; 4657 4658 bool Cond; 4659 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4660 if (Cond) 4661 CheckRight = false; 4662 else 4663 CheckLeft = false; 4664 } 4665 4666 // We need to maintain the offsets for the right and the left hand side 4667 // separately to check if every possible indexed expression is a valid 4668 // string literal. They might have different offsets for different string 4669 // literals in the end. 4670 StringLiteralCheckType Left; 4671 if (!CheckLeft) 4672 Left = SLCT_UncheckedLiteral; 4673 else { 4674 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4675 HasVAListArg, format_idx, firstDataArg, 4676 Type, CallType, InFunctionCall, 4677 CheckedVarArgs, UncoveredArg, Offset); 4678 if (Left == SLCT_NotALiteral || !CheckRight) { 4679 return Left; 4680 } 4681 } 4682 4683 StringLiteralCheckType Right = 4684 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4685 HasVAListArg, format_idx, firstDataArg, 4686 Type, CallType, InFunctionCall, CheckedVarArgs, 4687 UncoveredArg, Offset); 4688 4689 return (CheckLeft && Left < Right) ? Left : Right; 4690 } 4691 4692 case Stmt::ImplicitCastExprClass: { 4693 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4694 goto tryAgain; 4695 } 4696 4697 case Stmt::OpaqueValueExprClass: 4698 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4699 E = src; 4700 goto tryAgain; 4701 } 4702 return SLCT_NotALiteral; 4703 4704 case Stmt::PredefinedExprClass: 4705 // While __func__, etc., are technically not string literals, they 4706 // cannot contain format specifiers and thus are not a security 4707 // liability. 4708 return SLCT_UncheckedLiteral; 4709 4710 case Stmt::DeclRefExprClass: { 4711 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4712 4713 // As an exception, do not flag errors for variables binding to 4714 // const string literals. 4715 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4716 bool isConstant = false; 4717 QualType T = DR->getType(); 4718 4719 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4720 isConstant = AT->getElementType().isConstant(S.Context); 4721 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4722 isConstant = T.isConstant(S.Context) && 4723 PT->getPointeeType().isConstant(S.Context); 4724 } else if (T->isObjCObjectPointerType()) { 4725 // In ObjC, there is usually no "const ObjectPointer" type, 4726 // so don't check if the pointee type is constant. 4727 isConstant = T.isConstant(S.Context); 4728 } 4729 4730 if (isConstant) { 4731 if (const Expr *Init = VD->getAnyInitializer()) { 4732 // Look through initializers like const char c[] = { "foo" } 4733 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4734 if (InitList->isStringLiteralInit()) 4735 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4736 } 4737 return checkFormatStringExpr(S, Init, Args, 4738 HasVAListArg, format_idx, 4739 firstDataArg, Type, CallType, 4740 /*InFunctionCall*/ false, CheckedVarArgs, 4741 UncoveredArg, Offset); 4742 } 4743 } 4744 4745 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4746 // special check to see if the format string is a function parameter 4747 // of the function calling the printf function. If the function 4748 // has an attribute indicating it is a printf-like function, then we 4749 // should suppress warnings concerning non-literals being used in a call 4750 // to a vprintf function. For example: 4751 // 4752 // void 4753 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4754 // va_list ap; 4755 // va_start(ap, fmt); 4756 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4757 // ... 4758 // } 4759 if (HasVAListArg) { 4760 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4761 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4762 int PVIndex = PV->getFunctionScopeIndex() + 1; 4763 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4764 // adjust for implicit parameter 4765 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4766 if (MD->isInstance()) 4767 ++PVIndex; 4768 // We also check if the formats are compatible. 4769 // We can't pass a 'scanf' string to a 'printf' function. 4770 if (PVIndex == PVFormat->getFormatIdx() && 4771 Type == S.GetFormatStringType(PVFormat)) 4772 return SLCT_UncheckedLiteral; 4773 } 4774 } 4775 } 4776 } 4777 } 4778 4779 return SLCT_NotALiteral; 4780 } 4781 4782 case Stmt::CallExprClass: 4783 case Stmt::CXXMemberCallExprClass: { 4784 const CallExpr *CE = cast<CallExpr>(E); 4785 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4786 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4787 unsigned ArgIndex = FA->getFormatIdx(); 4788 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4789 if (MD->isInstance()) 4790 --ArgIndex; 4791 const Expr *Arg = CE->getArg(ArgIndex - 1); 4792 4793 return checkFormatStringExpr(S, Arg, Args, 4794 HasVAListArg, format_idx, firstDataArg, 4795 Type, CallType, InFunctionCall, 4796 CheckedVarArgs, UncoveredArg, Offset); 4797 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4798 unsigned BuiltinID = FD->getBuiltinID(); 4799 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4800 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4801 const Expr *Arg = CE->getArg(0); 4802 return checkFormatStringExpr(S, Arg, Args, 4803 HasVAListArg, format_idx, 4804 firstDataArg, Type, CallType, 4805 InFunctionCall, CheckedVarArgs, 4806 UncoveredArg, Offset); 4807 } 4808 } 4809 } 4810 4811 return SLCT_NotALiteral; 4812 } 4813 case Stmt::ObjCMessageExprClass: { 4814 const auto *ME = cast<ObjCMessageExpr>(E); 4815 if (const auto *ND = ME->getMethodDecl()) { 4816 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4817 unsigned ArgIndex = FA->getFormatIdx(); 4818 const Expr *Arg = ME->getArg(ArgIndex - 1); 4819 return checkFormatStringExpr( 4820 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4821 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4822 } 4823 } 4824 4825 return SLCT_NotALiteral; 4826 } 4827 case Stmt::ObjCStringLiteralClass: 4828 case Stmt::StringLiteralClass: { 4829 const StringLiteral *StrE = nullptr; 4830 4831 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4832 StrE = ObjCFExpr->getString(); 4833 else 4834 StrE = cast<StringLiteral>(E); 4835 4836 if (StrE) { 4837 if (Offset.isNegative() || Offset > StrE->getLength()) { 4838 // TODO: It would be better to have an explicit warning for out of 4839 // bounds literals. 4840 return SLCT_NotALiteral; 4841 } 4842 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4843 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4844 firstDataArg, Type, InFunctionCall, CallType, 4845 CheckedVarArgs, UncoveredArg); 4846 return SLCT_CheckedLiteral; 4847 } 4848 4849 return SLCT_NotALiteral; 4850 } 4851 case Stmt::BinaryOperatorClass: { 4852 llvm::APSInt LResult; 4853 llvm::APSInt RResult; 4854 4855 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 4856 4857 // A string literal + an int offset is still a string literal. 4858 if (BinOp->isAdditiveOp()) { 4859 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 4860 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 4861 4862 if (LIsInt != RIsInt) { 4863 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 4864 4865 if (LIsInt) { 4866 if (BinOpKind == BO_Add) { 4867 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 4868 E = BinOp->getRHS(); 4869 goto tryAgain; 4870 } 4871 } else { 4872 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 4873 E = BinOp->getLHS(); 4874 goto tryAgain; 4875 } 4876 } 4877 } 4878 4879 return SLCT_NotALiteral; 4880 } 4881 case Stmt::UnaryOperatorClass: { 4882 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 4883 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 4884 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 4885 llvm::APSInt IndexResult; 4886 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 4887 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 4888 E = ASE->getBase(); 4889 goto tryAgain; 4890 } 4891 } 4892 4893 return SLCT_NotALiteral; 4894 } 4895 4896 default: 4897 return SLCT_NotALiteral; 4898 } 4899 } 4900 4901 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 4902 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 4903 .Case("scanf", FST_Scanf) 4904 .Cases("printf", "printf0", FST_Printf) 4905 .Cases("NSString", "CFString", FST_NSString) 4906 .Case("strftime", FST_Strftime) 4907 .Case("strfmon", FST_Strfmon) 4908 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 4909 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 4910 .Case("os_trace", FST_OSLog) 4911 .Case("os_log", FST_OSLog) 4912 .Default(FST_Unknown); 4913 } 4914 4915 /// CheckFormatArguments - Check calls to printf and scanf (and similar 4916 /// functions) for correct use of format strings. 4917 /// Returns true if a format string has been fully checked. 4918 bool Sema::CheckFormatArguments(const FormatAttr *Format, 4919 ArrayRef<const Expr *> Args, 4920 bool IsCXXMember, 4921 VariadicCallType CallType, 4922 SourceLocation Loc, SourceRange Range, 4923 llvm::SmallBitVector &CheckedVarArgs) { 4924 FormatStringInfo FSI; 4925 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 4926 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 4927 FSI.FirstDataArg, GetFormatStringType(Format), 4928 CallType, Loc, Range, CheckedVarArgs); 4929 return false; 4930 } 4931 4932 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 4933 bool HasVAListArg, unsigned format_idx, 4934 unsigned firstDataArg, FormatStringType Type, 4935 VariadicCallType CallType, 4936 SourceLocation Loc, SourceRange Range, 4937 llvm::SmallBitVector &CheckedVarArgs) { 4938 // CHECK: printf/scanf-like function is called with no format string. 4939 if (format_idx >= Args.size()) { 4940 Diag(Loc, diag::warn_missing_format_string) << Range; 4941 return false; 4942 } 4943 4944 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 4945 4946 // CHECK: format string is not a string literal. 4947 // 4948 // Dynamically generated format strings are difficult to 4949 // automatically vet at compile time. Requiring that format strings 4950 // are string literals: (1) permits the checking of format strings by 4951 // the compiler and thereby (2) can practically remove the source of 4952 // many format string exploits. 4953 4954 // Format string can be either ObjC string (e.g. @"%d") or 4955 // C string (e.g. "%d") 4956 // ObjC string uses the same format specifiers as C string, so we can use 4957 // the same format string checking logic for both ObjC and C strings. 4958 UncoveredArgHandler UncoveredArg; 4959 StringLiteralCheckType CT = 4960 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 4961 format_idx, firstDataArg, Type, CallType, 4962 /*IsFunctionCall*/ true, CheckedVarArgs, 4963 UncoveredArg, 4964 /*no string offset*/ llvm::APSInt(64, false) = 0); 4965 4966 // Generate a diagnostic where an uncovered argument is detected. 4967 if (UncoveredArg.hasUncoveredArg()) { 4968 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 4969 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 4970 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 4971 } 4972 4973 if (CT != SLCT_NotALiteral) 4974 // Literal format string found, check done! 4975 return CT == SLCT_CheckedLiteral; 4976 4977 // Strftime is particular as it always uses a single 'time' argument, 4978 // so it is safe to pass a non-literal string. 4979 if (Type == FST_Strftime) 4980 return false; 4981 4982 // Do not emit diag when the string param is a macro expansion and the 4983 // format is either NSString or CFString. This is a hack to prevent 4984 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 4985 // which are usually used in place of NS and CF string literals. 4986 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 4987 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 4988 return false; 4989 4990 // If there are no arguments specified, warn with -Wformat-security, otherwise 4991 // warn only with -Wformat-nonliteral. 4992 if (Args.size() == firstDataArg) { 4993 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 4994 << OrigFormatExpr->getSourceRange(); 4995 switch (Type) { 4996 default: 4997 break; 4998 case FST_Kprintf: 4999 case FST_FreeBSDKPrintf: 5000 case FST_Printf: 5001 Diag(FormatLoc, diag::note_format_security_fixit) 5002 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5003 break; 5004 case FST_NSString: 5005 Diag(FormatLoc, diag::note_format_security_fixit) 5006 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5007 break; 5008 } 5009 } else { 5010 Diag(FormatLoc, diag::warn_format_nonliteral) 5011 << OrigFormatExpr->getSourceRange(); 5012 } 5013 return false; 5014 } 5015 5016 namespace { 5017 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5018 protected: 5019 Sema &S; 5020 const FormatStringLiteral *FExpr; 5021 const Expr *OrigFormatExpr; 5022 const Sema::FormatStringType FSType; 5023 const unsigned FirstDataArg; 5024 const unsigned NumDataArgs; 5025 const char *Beg; // Start of format string. 5026 const bool HasVAListArg; 5027 ArrayRef<const Expr *> Args; 5028 unsigned FormatIdx; 5029 llvm::SmallBitVector CoveredArgs; 5030 bool usesPositionalArgs; 5031 bool atFirstArg; 5032 bool inFunctionCall; 5033 Sema::VariadicCallType CallType; 5034 llvm::SmallBitVector &CheckedVarArgs; 5035 UncoveredArgHandler &UncoveredArg; 5036 5037 public: 5038 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5039 const Expr *origFormatExpr, 5040 const Sema::FormatStringType type, unsigned firstDataArg, 5041 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5042 ArrayRef<const Expr *> Args, unsigned formatIdx, 5043 bool inFunctionCall, Sema::VariadicCallType callType, 5044 llvm::SmallBitVector &CheckedVarArgs, 5045 UncoveredArgHandler &UncoveredArg) 5046 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5047 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5048 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5049 usesPositionalArgs(false), atFirstArg(true), 5050 inFunctionCall(inFunctionCall), CallType(callType), 5051 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5052 CoveredArgs.resize(numDataArgs); 5053 CoveredArgs.reset(); 5054 } 5055 5056 void DoneProcessing(); 5057 5058 void HandleIncompleteSpecifier(const char *startSpecifier, 5059 unsigned specifierLen) override; 5060 5061 void HandleInvalidLengthModifier( 5062 const analyze_format_string::FormatSpecifier &FS, 5063 const analyze_format_string::ConversionSpecifier &CS, 5064 const char *startSpecifier, unsigned specifierLen, 5065 unsigned DiagID); 5066 5067 void HandleNonStandardLengthModifier( 5068 const analyze_format_string::FormatSpecifier &FS, 5069 const char *startSpecifier, unsigned specifierLen); 5070 5071 void HandleNonStandardConversionSpecifier( 5072 const analyze_format_string::ConversionSpecifier &CS, 5073 const char *startSpecifier, unsigned specifierLen); 5074 5075 void HandlePosition(const char *startPos, unsigned posLen) override; 5076 5077 void HandleInvalidPosition(const char *startSpecifier, 5078 unsigned specifierLen, 5079 analyze_format_string::PositionContext p) override; 5080 5081 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5082 5083 void HandleNullChar(const char *nullCharacter) override; 5084 5085 template <typename Range> 5086 static void 5087 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5088 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5089 bool IsStringLocation, Range StringRange, 5090 ArrayRef<FixItHint> Fixit = None); 5091 5092 protected: 5093 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5094 const char *startSpec, 5095 unsigned specifierLen, 5096 const char *csStart, unsigned csLen); 5097 5098 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5099 const char *startSpec, 5100 unsigned specifierLen); 5101 5102 SourceRange getFormatStringRange(); 5103 CharSourceRange getSpecifierRange(const char *startSpecifier, 5104 unsigned specifierLen); 5105 SourceLocation getLocationOfByte(const char *x); 5106 5107 const Expr *getDataArg(unsigned i) const; 5108 5109 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5110 const analyze_format_string::ConversionSpecifier &CS, 5111 const char *startSpecifier, unsigned specifierLen, 5112 unsigned argIndex); 5113 5114 template <typename Range> 5115 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5116 bool IsStringLocation, Range StringRange, 5117 ArrayRef<FixItHint> Fixit = None); 5118 }; 5119 } // end anonymous namespace 5120 5121 SourceRange CheckFormatHandler::getFormatStringRange() { 5122 return OrigFormatExpr->getSourceRange(); 5123 } 5124 5125 CharSourceRange CheckFormatHandler:: 5126 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5127 SourceLocation Start = getLocationOfByte(startSpecifier); 5128 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5129 5130 // Advance the end SourceLocation by one due to half-open ranges. 5131 End = End.getLocWithOffset(1); 5132 5133 return CharSourceRange::getCharRange(Start, End); 5134 } 5135 5136 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5137 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5138 S.getLangOpts(), S.Context.getTargetInfo()); 5139 } 5140 5141 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5142 unsigned specifierLen){ 5143 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5144 getLocationOfByte(startSpecifier), 5145 /*IsStringLocation*/true, 5146 getSpecifierRange(startSpecifier, specifierLen)); 5147 } 5148 5149 void CheckFormatHandler::HandleInvalidLengthModifier( 5150 const analyze_format_string::FormatSpecifier &FS, 5151 const analyze_format_string::ConversionSpecifier &CS, 5152 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5153 using namespace analyze_format_string; 5154 5155 const LengthModifier &LM = FS.getLengthModifier(); 5156 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5157 5158 // See if we know how to fix this length modifier. 5159 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5160 if (FixedLM) { 5161 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5162 getLocationOfByte(LM.getStart()), 5163 /*IsStringLocation*/true, 5164 getSpecifierRange(startSpecifier, specifierLen)); 5165 5166 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5167 << FixedLM->toString() 5168 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5169 5170 } else { 5171 FixItHint Hint; 5172 if (DiagID == diag::warn_format_nonsensical_length) 5173 Hint = FixItHint::CreateRemoval(LMRange); 5174 5175 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5176 getLocationOfByte(LM.getStart()), 5177 /*IsStringLocation*/true, 5178 getSpecifierRange(startSpecifier, specifierLen), 5179 Hint); 5180 } 5181 } 5182 5183 void CheckFormatHandler::HandleNonStandardLengthModifier( 5184 const analyze_format_string::FormatSpecifier &FS, 5185 const char *startSpecifier, unsigned specifierLen) { 5186 using namespace analyze_format_string; 5187 5188 const LengthModifier &LM = FS.getLengthModifier(); 5189 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5190 5191 // See if we know how to fix this length modifier. 5192 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5193 if (FixedLM) { 5194 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5195 << LM.toString() << 0, 5196 getLocationOfByte(LM.getStart()), 5197 /*IsStringLocation*/true, 5198 getSpecifierRange(startSpecifier, specifierLen)); 5199 5200 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5201 << FixedLM->toString() 5202 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5203 5204 } else { 5205 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5206 << LM.toString() << 0, 5207 getLocationOfByte(LM.getStart()), 5208 /*IsStringLocation*/true, 5209 getSpecifierRange(startSpecifier, specifierLen)); 5210 } 5211 } 5212 5213 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5214 const analyze_format_string::ConversionSpecifier &CS, 5215 const char *startSpecifier, unsigned specifierLen) { 5216 using namespace analyze_format_string; 5217 5218 // See if we know how to fix this conversion specifier. 5219 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5220 if (FixedCS) { 5221 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5222 << CS.toString() << /*conversion specifier*/1, 5223 getLocationOfByte(CS.getStart()), 5224 /*IsStringLocation*/true, 5225 getSpecifierRange(startSpecifier, specifierLen)); 5226 5227 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5228 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5229 << FixedCS->toString() 5230 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5231 } else { 5232 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5233 << CS.toString() << /*conversion specifier*/1, 5234 getLocationOfByte(CS.getStart()), 5235 /*IsStringLocation*/true, 5236 getSpecifierRange(startSpecifier, specifierLen)); 5237 } 5238 } 5239 5240 void CheckFormatHandler::HandlePosition(const char *startPos, 5241 unsigned posLen) { 5242 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5243 getLocationOfByte(startPos), 5244 /*IsStringLocation*/true, 5245 getSpecifierRange(startPos, posLen)); 5246 } 5247 5248 void 5249 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5250 analyze_format_string::PositionContext p) { 5251 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5252 << (unsigned) p, 5253 getLocationOfByte(startPos), /*IsStringLocation*/true, 5254 getSpecifierRange(startPos, posLen)); 5255 } 5256 5257 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5258 unsigned posLen) { 5259 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5260 getLocationOfByte(startPos), 5261 /*IsStringLocation*/true, 5262 getSpecifierRange(startPos, posLen)); 5263 } 5264 5265 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5266 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5267 // The presence of a null character is likely an error. 5268 EmitFormatDiagnostic( 5269 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5270 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5271 getFormatStringRange()); 5272 } 5273 } 5274 5275 // Note that this may return NULL if there was an error parsing or building 5276 // one of the argument expressions. 5277 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5278 return Args[FirstDataArg + i]; 5279 } 5280 5281 void CheckFormatHandler::DoneProcessing() { 5282 // Does the number of data arguments exceed the number of 5283 // format conversions in the format string? 5284 if (!HasVAListArg) { 5285 // Find any arguments that weren't covered. 5286 CoveredArgs.flip(); 5287 signed notCoveredArg = CoveredArgs.find_first(); 5288 if (notCoveredArg >= 0) { 5289 assert((unsigned)notCoveredArg < NumDataArgs); 5290 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5291 } else { 5292 UncoveredArg.setAllCovered(); 5293 } 5294 } 5295 } 5296 5297 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5298 const Expr *ArgExpr) { 5299 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5300 "Invalid state"); 5301 5302 if (!ArgExpr) 5303 return; 5304 5305 SourceLocation Loc = ArgExpr->getLocStart(); 5306 5307 if (S.getSourceManager().isInSystemMacro(Loc)) 5308 return; 5309 5310 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5311 for (auto E : DiagnosticExprs) 5312 PDiag << E->getSourceRange(); 5313 5314 CheckFormatHandler::EmitFormatDiagnostic( 5315 S, IsFunctionCall, DiagnosticExprs[0], 5316 PDiag, Loc, /*IsStringLocation*/false, 5317 DiagnosticExprs[0]->getSourceRange()); 5318 } 5319 5320 bool 5321 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5322 SourceLocation Loc, 5323 const char *startSpec, 5324 unsigned specifierLen, 5325 const char *csStart, 5326 unsigned csLen) { 5327 bool keepGoing = true; 5328 if (argIndex < NumDataArgs) { 5329 // Consider the argument coverered, even though the specifier doesn't 5330 // make sense. 5331 CoveredArgs.set(argIndex); 5332 } 5333 else { 5334 // If argIndex exceeds the number of data arguments we 5335 // don't issue a warning because that is just a cascade of warnings (and 5336 // they may have intended '%%' anyway). We don't want to continue processing 5337 // the format string after this point, however, as we will like just get 5338 // gibberish when trying to match arguments. 5339 keepGoing = false; 5340 } 5341 5342 StringRef Specifier(csStart, csLen); 5343 5344 // If the specifier in non-printable, it could be the first byte of a UTF-8 5345 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5346 // hex value. 5347 std::string CodePointStr; 5348 if (!llvm::sys::locale::isPrint(*csStart)) { 5349 llvm::UTF32 CodePoint; 5350 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5351 const llvm::UTF8 *E = 5352 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5353 llvm::ConversionResult Result = 5354 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5355 5356 if (Result != llvm::conversionOK) { 5357 unsigned char FirstChar = *csStart; 5358 CodePoint = (llvm::UTF32)FirstChar; 5359 } 5360 5361 llvm::raw_string_ostream OS(CodePointStr); 5362 if (CodePoint < 256) 5363 OS << "\\x" << llvm::format("%02x", CodePoint); 5364 else if (CodePoint <= 0xFFFF) 5365 OS << "\\u" << llvm::format("%04x", CodePoint); 5366 else 5367 OS << "\\U" << llvm::format("%08x", CodePoint); 5368 OS.flush(); 5369 Specifier = CodePointStr; 5370 } 5371 5372 EmitFormatDiagnostic( 5373 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5374 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5375 5376 return keepGoing; 5377 } 5378 5379 void 5380 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5381 const char *startSpec, 5382 unsigned specifierLen) { 5383 EmitFormatDiagnostic( 5384 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5385 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5386 } 5387 5388 bool 5389 CheckFormatHandler::CheckNumArgs( 5390 const analyze_format_string::FormatSpecifier &FS, 5391 const analyze_format_string::ConversionSpecifier &CS, 5392 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5393 5394 if (argIndex >= NumDataArgs) { 5395 PartialDiagnostic PDiag = FS.usesPositionalArg() 5396 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5397 << (argIndex+1) << NumDataArgs) 5398 : S.PDiag(diag::warn_printf_insufficient_data_args); 5399 EmitFormatDiagnostic( 5400 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5401 getSpecifierRange(startSpecifier, specifierLen)); 5402 5403 // Since more arguments than conversion tokens are given, by extension 5404 // all arguments are covered, so mark this as so. 5405 UncoveredArg.setAllCovered(); 5406 return false; 5407 } 5408 return true; 5409 } 5410 5411 template<typename Range> 5412 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5413 SourceLocation Loc, 5414 bool IsStringLocation, 5415 Range StringRange, 5416 ArrayRef<FixItHint> FixIt) { 5417 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5418 Loc, IsStringLocation, StringRange, FixIt); 5419 } 5420 5421 /// \brief If the format string is not within the funcion call, emit a note 5422 /// so that the function call and string are in diagnostic messages. 5423 /// 5424 /// \param InFunctionCall if true, the format string is within the function 5425 /// call and only one diagnostic message will be produced. Otherwise, an 5426 /// extra note will be emitted pointing to location of the format string. 5427 /// 5428 /// \param ArgumentExpr the expression that is passed as the format string 5429 /// argument in the function call. Used for getting locations when two 5430 /// diagnostics are emitted. 5431 /// 5432 /// \param PDiag the callee should already have provided any strings for the 5433 /// diagnostic message. This function only adds locations and fixits 5434 /// to diagnostics. 5435 /// 5436 /// \param Loc primary location for diagnostic. If two diagnostics are 5437 /// required, one will be at Loc and a new SourceLocation will be created for 5438 /// the other one. 5439 /// 5440 /// \param IsStringLocation if true, Loc points to the format string should be 5441 /// used for the note. Otherwise, Loc points to the argument list and will 5442 /// be used with PDiag. 5443 /// 5444 /// \param StringRange some or all of the string to highlight. This is 5445 /// templated so it can accept either a CharSourceRange or a SourceRange. 5446 /// 5447 /// \param FixIt optional fix it hint for the format string. 5448 template <typename Range> 5449 void CheckFormatHandler::EmitFormatDiagnostic( 5450 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5451 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5452 Range StringRange, ArrayRef<FixItHint> FixIt) { 5453 if (InFunctionCall) { 5454 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5455 D << StringRange; 5456 D << FixIt; 5457 } else { 5458 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5459 << ArgumentExpr->getSourceRange(); 5460 5461 const Sema::SemaDiagnosticBuilder &Note = 5462 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5463 diag::note_format_string_defined); 5464 5465 Note << StringRange; 5466 Note << FixIt; 5467 } 5468 } 5469 5470 //===--- CHECK: Printf format string checking ------------------------------===// 5471 5472 namespace { 5473 class CheckPrintfHandler : public CheckFormatHandler { 5474 public: 5475 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5476 const Expr *origFormatExpr, 5477 const Sema::FormatStringType type, unsigned firstDataArg, 5478 unsigned numDataArgs, bool isObjC, const char *beg, 5479 bool hasVAListArg, ArrayRef<const Expr *> Args, 5480 unsigned formatIdx, bool inFunctionCall, 5481 Sema::VariadicCallType CallType, 5482 llvm::SmallBitVector &CheckedVarArgs, 5483 UncoveredArgHandler &UncoveredArg) 5484 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5485 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5486 inFunctionCall, CallType, CheckedVarArgs, 5487 UncoveredArg) {} 5488 5489 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5490 5491 /// Returns true if '%@' specifiers are allowed in the format string. 5492 bool allowsObjCArg() const { 5493 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5494 FSType == Sema::FST_OSTrace; 5495 } 5496 5497 bool HandleInvalidPrintfConversionSpecifier( 5498 const analyze_printf::PrintfSpecifier &FS, 5499 const char *startSpecifier, 5500 unsigned specifierLen) override; 5501 5502 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5503 const char *startSpecifier, 5504 unsigned specifierLen) override; 5505 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5506 const char *StartSpecifier, 5507 unsigned SpecifierLen, 5508 const Expr *E); 5509 5510 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5511 const char *startSpecifier, unsigned specifierLen); 5512 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5513 const analyze_printf::OptionalAmount &Amt, 5514 unsigned type, 5515 const char *startSpecifier, unsigned specifierLen); 5516 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5517 const analyze_printf::OptionalFlag &flag, 5518 const char *startSpecifier, unsigned specifierLen); 5519 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5520 const analyze_printf::OptionalFlag &ignoredFlag, 5521 const analyze_printf::OptionalFlag &flag, 5522 const char *startSpecifier, unsigned specifierLen); 5523 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5524 const Expr *E); 5525 5526 void HandleEmptyObjCModifierFlag(const char *startFlag, 5527 unsigned flagLen) override; 5528 5529 void HandleInvalidObjCModifierFlag(const char *startFlag, 5530 unsigned flagLen) override; 5531 5532 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5533 const char *flagsEnd, 5534 const char *conversionPosition) 5535 override; 5536 }; 5537 } // end anonymous namespace 5538 5539 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5540 const analyze_printf::PrintfSpecifier &FS, 5541 const char *startSpecifier, 5542 unsigned specifierLen) { 5543 const analyze_printf::PrintfConversionSpecifier &CS = 5544 FS.getConversionSpecifier(); 5545 5546 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5547 getLocationOfByte(CS.getStart()), 5548 startSpecifier, specifierLen, 5549 CS.getStart(), CS.getLength()); 5550 } 5551 5552 bool CheckPrintfHandler::HandleAmount( 5553 const analyze_format_string::OptionalAmount &Amt, 5554 unsigned k, const char *startSpecifier, 5555 unsigned specifierLen) { 5556 if (Amt.hasDataArgument()) { 5557 if (!HasVAListArg) { 5558 unsigned argIndex = Amt.getArgIndex(); 5559 if (argIndex >= NumDataArgs) { 5560 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5561 << k, 5562 getLocationOfByte(Amt.getStart()), 5563 /*IsStringLocation*/true, 5564 getSpecifierRange(startSpecifier, specifierLen)); 5565 // Don't do any more checking. We will just emit 5566 // spurious errors. 5567 return false; 5568 } 5569 5570 // Type check the data argument. It should be an 'int'. 5571 // Although not in conformance with C99, we also allow the argument to be 5572 // an 'unsigned int' as that is a reasonably safe case. GCC also 5573 // doesn't emit a warning for that case. 5574 CoveredArgs.set(argIndex); 5575 const Expr *Arg = getDataArg(argIndex); 5576 if (!Arg) 5577 return false; 5578 5579 QualType T = Arg->getType(); 5580 5581 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5582 assert(AT.isValid()); 5583 5584 if (!AT.matchesType(S.Context, T)) { 5585 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5586 << k << AT.getRepresentativeTypeName(S.Context) 5587 << T << Arg->getSourceRange(), 5588 getLocationOfByte(Amt.getStart()), 5589 /*IsStringLocation*/true, 5590 getSpecifierRange(startSpecifier, specifierLen)); 5591 // Don't do any more checking. We will just emit 5592 // spurious errors. 5593 return false; 5594 } 5595 } 5596 } 5597 return true; 5598 } 5599 5600 void CheckPrintfHandler::HandleInvalidAmount( 5601 const analyze_printf::PrintfSpecifier &FS, 5602 const analyze_printf::OptionalAmount &Amt, 5603 unsigned type, 5604 const char *startSpecifier, 5605 unsigned specifierLen) { 5606 const analyze_printf::PrintfConversionSpecifier &CS = 5607 FS.getConversionSpecifier(); 5608 5609 FixItHint fixit = 5610 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5611 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5612 Amt.getConstantLength())) 5613 : FixItHint(); 5614 5615 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5616 << type << CS.toString(), 5617 getLocationOfByte(Amt.getStart()), 5618 /*IsStringLocation*/true, 5619 getSpecifierRange(startSpecifier, specifierLen), 5620 fixit); 5621 } 5622 5623 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5624 const analyze_printf::OptionalFlag &flag, 5625 const char *startSpecifier, 5626 unsigned specifierLen) { 5627 // Warn about pointless flag with a fixit removal. 5628 const analyze_printf::PrintfConversionSpecifier &CS = 5629 FS.getConversionSpecifier(); 5630 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5631 << flag.toString() << CS.toString(), 5632 getLocationOfByte(flag.getPosition()), 5633 /*IsStringLocation*/true, 5634 getSpecifierRange(startSpecifier, specifierLen), 5635 FixItHint::CreateRemoval( 5636 getSpecifierRange(flag.getPosition(), 1))); 5637 } 5638 5639 void CheckPrintfHandler::HandleIgnoredFlag( 5640 const analyze_printf::PrintfSpecifier &FS, 5641 const analyze_printf::OptionalFlag &ignoredFlag, 5642 const analyze_printf::OptionalFlag &flag, 5643 const char *startSpecifier, 5644 unsigned specifierLen) { 5645 // Warn about ignored flag with a fixit removal. 5646 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5647 << ignoredFlag.toString() << flag.toString(), 5648 getLocationOfByte(ignoredFlag.getPosition()), 5649 /*IsStringLocation*/true, 5650 getSpecifierRange(startSpecifier, specifierLen), 5651 FixItHint::CreateRemoval( 5652 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5653 } 5654 5655 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5656 // bool IsStringLocation, Range StringRange, 5657 // ArrayRef<FixItHint> Fixit = None); 5658 5659 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5660 unsigned flagLen) { 5661 // Warn about an empty flag. 5662 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5663 getLocationOfByte(startFlag), 5664 /*IsStringLocation*/true, 5665 getSpecifierRange(startFlag, flagLen)); 5666 } 5667 5668 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5669 unsigned flagLen) { 5670 // Warn about an invalid flag. 5671 auto Range = getSpecifierRange(startFlag, flagLen); 5672 StringRef flag(startFlag, flagLen); 5673 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5674 getLocationOfByte(startFlag), 5675 /*IsStringLocation*/true, 5676 Range, FixItHint::CreateRemoval(Range)); 5677 } 5678 5679 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5680 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5681 // Warn about using '[...]' without a '@' conversion. 5682 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5683 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5684 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5685 getLocationOfByte(conversionPosition), 5686 /*IsStringLocation*/true, 5687 Range, FixItHint::CreateRemoval(Range)); 5688 } 5689 5690 // Determines if the specified is a C++ class or struct containing 5691 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5692 // "c_str()"). 5693 template<typename MemberKind> 5694 static llvm::SmallPtrSet<MemberKind*, 1> 5695 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5696 const RecordType *RT = Ty->getAs<RecordType>(); 5697 llvm::SmallPtrSet<MemberKind*, 1> Results; 5698 5699 if (!RT) 5700 return Results; 5701 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5702 if (!RD || !RD->getDefinition()) 5703 return Results; 5704 5705 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5706 Sema::LookupMemberName); 5707 R.suppressDiagnostics(); 5708 5709 // We just need to include all members of the right kind turned up by the 5710 // filter, at this point. 5711 if (S.LookupQualifiedName(R, RT->getDecl())) 5712 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5713 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5714 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5715 Results.insert(FK); 5716 } 5717 return Results; 5718 } 5719 5720 /// Check if we could call '.c_str()' on an object. 5721 /// 5722 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5723 /// allow the call, or if it would be ambiguous). 5724 bool Sema::hasCStrMethod(const Expr *E) { 5725 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5726 MethodSet Results = 5727 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5728 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5729 MI != ME; ++MI) 5730 if ((*MI)->getMinRequiredArguments() == 0) 5731 return true; 5732 return false; 5733 } 5734 5735 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5736 // better diagnostic if so. AT is assumed to be valid. 5737 // Returns true when a c_str() conversion method is found. 5738 bool CheckPrintfHandler::checkForCStrMembers( 5739 const analyze_printf::ArgType &AT, const Expr *E) { 5740 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5741 5742 MethodSet Results = 5743 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5744 5745 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5746 MI != ME; ++MI) { 5747 const CXXMethodDecl *Method = *MI; 5748 if (Method->getMinRequiredArguments() == 0 && 5749 AT.matchesType(S.Context, Method->getReturnType())) { 5750 // FIXME: Suggest parens if the expression needs them. 5751 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5752 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5753 << "c_str()" 5754 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5755 return true; 5756 } 5757 } 5758 5759 return false; 5760 } 5761 5762 bool 5763 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5764 &FS, 5765 const char *startSpecifier, 5766 unsigned specifierLen) { 5767 using namespace analyze_format_string; 5768 using namespace analyze_printf; 5769 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5770 5771 if (FS.consumesDataArgument()) { 5772 if (atFirstArg) { 5773 atFirstArg = false; 5774 usesPositionalArgs = FS.usesPositionalArg(); 5775 } 5776 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5777 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5778 startSpecifier, specifierLen); 5779 return false; 5780 } 5781 } 5782 5783 // First check if the field width, precision, and conversion specifier 5784 // have matching data arguments. 5785 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5786 startSpecifier, specifierLen)) { 5787 return false; 5788 } 5789 5790 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5791 startSpecifier, specifierLen)) { 5792 return false; 5793 } 5794 5795 if (!CS.consumesDataArgument()) { 5796 // FIXME: Technically specifying a precision or field width here 5797 // makes no sense. Worth issuing a warning at some point. 5798 return true; 5799 } 5800 5801 // Consume the argument. 5802 unsigned argIndex = FS.getArgIndex(); 5803 if (argIndex < NumDataArgs) { 5804 // The check to see if the argIndex is valid will come later. 5805 // We set the bit here because we may exit early from this 5806 // function if we encounter some other error. 5807 CoveredArgs.set(argIndex); 5808 } 5809 5810 // FreeBSD kernel extensions. 5811 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5812 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5813 // We need at least two arguments. 5814 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5815 return false; 5816 5817 // Claim the second argument. 5818 CoveredArgs.set(argIndex + 1); 5819 5820 // Type check the first argument (int for %b, pointer for %D) 5821 const Expr *Ex = getDataArg(argIndex); 5822 const analyze_printf::ArgType &AT = 5823 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5824 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5825 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5826 EmitFormatDiagnostic( 5827 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5828 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5829 << false << Ex->getSourceRange(), 5830 Ex->getLocStart(), /*IsStringLocation*/false, 5831 getSpecifierRange(startSpecifier, specifierLen)); 5832 5833 // Type check the second argument (char * for both %b and %D) 5834 Ex = getDataArg(argIndex + 1); 5835 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5836 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5837 EmitFormatDiagnostic( 5838 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5839 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5840 << false << Ex->getSourceRange(), 5841 Ex->getLocStart(), /*IsStringLocation*/false, 5842 getSpecifierRange(startSpecifier, specifierLen)); 5843 5844 return true; 5845 } 5846 5847 // Check for using an Objective-C specific conversion specifier 5848 // in a non-ObjC literal. 5849 if (!allowsObjCArg() && CS.isObjCArg()) { 5850 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5851 specifierLen); 5852 } 5853 5854 // %P can only be used with os_log. 5855 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 5856 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5857 specifierLen); 5858 } 5859 5860 // %n is not allowed with os_log. 5861 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 5862 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 5863 getLocationOfByte(CS.getStart()), 5864 /*IsStringLocation*/ false, 5865 getSpecifierRange(startSpecifier, specifierLen)); 5866 5867 return true; 5868 } 5869 5870 // Only scalars are allowed for os_trace. 5871 if (FSType == Sema::FST_OSTrace && 5872 (CS.getKind() == ConversionSpecifier::PArg || 5873 CS.getKind() == ConversionSpecifier::sArg || 5874 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 5875 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5876 specifierLen); 5877 } 5878 5879 // Check for use of public/private annotation outside of os_log(). 5880 if (FSType != Sema::FST_OSLog) { 5881 if (FS.isPublic().isSet()) { 5882 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5883 << "public", 5884 getLocationOfByte(FS.isPublic().getPosition()), 5885 /*IsStringLocation*/ false, 5886 getSpecifierRange(startSpecifier, specifierLen)); 5887 } 5888 if (FS.isPrivate().isSet()) { 5889 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5890 << "private", 5891 getLocationOfByte(FS.isPrivate().getPosition()), 5892 /*IsStringLocation*/ false, 5893 getSpecifierRange(startSpecifier, specifierLen)); 5894 } 5895 } 5896 5897 // Check for invalid use of field width 5898 if (!FS.hasValidFieldWidth()) { 5899 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 5900 startSpecifier, specifierLen); 5901 } 5902 5903 // Check for invalid use of precision 5904 if (!FS.hasValidPrecision()) { 5905 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 5906 startSpecifier, specifierLen); 5907 } 5908 5909 // Precision is mandatory for %P specifier. 5910 if (CS.getKind() == ConversionSpecifier::PArg && 5911 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 5912 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 5913 getLocationOfByte(startSpecifier), 5914 /*IsStringLocation*/ false, 5915 getSpecifierRange(startSpecifier, specifierLen)); 5916 } 5917 5918 // Check each flag does not conflict with any other component. 5919 if (!FS.hasValidThousandsGroupingPrefix()) 5920 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 5921 if (!FS.hasValidLeadingZeros()) 5922 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 5923 if (!FS.hasValidPlusPrefix()) 5924 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 5925 if (!FS.hasValidSpacePrefix()) 5926 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 5927 if (!FS.hasValidAlternativeForm()) 5928 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 5929 if (!FS.hasValidLeftJustified()) 5930 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 5931 5932 // Check that flags are not ignored by another flag 5933 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 5934 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 5935 startSpecifier, specifierLen); 5936 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 5937 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 5938 startSpecifier, specifierLen); 5939 5940 // Check the length modifier is valid with the given conversion specifier. 5941 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5942 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5943 diag::warn_format_nonsensical_length); 5944 else if (!FS.hasStandardLengthModifier()) 5945 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5946 else if (!FS.hasStandardLengthConversionCombination()) 5947 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5948 diag::warn_format_non_standard_conversion_spec); 5949 5950 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5951 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5952 5953 // The remaining checks depend on the data arguments. 5954 if (HasVAListArg) 5955 return true; 5956 5957 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5958 return false; 5959 5960 const Expr *Arg = getDataArg(argIndex); 5961 if (!Arg) 5962 return true; 5963 5964 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 5965 } 5966 5967 static bool requiresParensToAddCast(const Expr *E) { 5968 // FIXME: We should have a general way to reason about operator 5969 // precedence and whether parens are actually needed here. 5970 // Take care of a few common cases where they aren't. 5971 const Expr *Inside = E->IgnoreImpCasts(); 5972 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 5973 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 5974 5975 switch (Inside->getStmtClass()) { 5976 case Stmt::ArraySubscriptExprClass: 5977 case Stmt::CallExprClass: 5978 case Stmt::CharacterLiteralClass: 5979 case Stmt::CXXBoolLiteralExprClass: 5980 case Stmt::DeclRefExprClass: 5981 case Stmt::FloatingLiteralClass: 5982 case Stmt::IntegerLiteralClass: 5983 case Stmt::MemberExprClass: 5984 case Stmt::ObjCArrayLiteralClass: 5985 case Stmt::ObjCBoolLiteralExprClass: 5986 case Stmt::ObjCBoxedExprClass: 5987 case Stmt::ObjCDictionaryLiteralClass: 5988 case Stmt::ObjCEncodeExprClass: 5989 case Stmt::ObjCIvarRefExprClass: 5990 case Stmt::ObjCMessageExprClass: 5991 case Stmt::ObjCPropertyRefExprClass: 5992 case Stmt::ObjCStringLiteralClass: 5993 case Stmt::ObjCSubscriptRefExprClass: 5994 case Stmt::ParenExprClass: 5995 case Stmt::StringLiteralClass: 5996 case Stmt::UnaryOperatorClass: 5997 return false; 5998 default: 5999 return true; 6000 } 6001 } 6002 6003 static std::pair<QualType, StringRef> 6004 shouldNotPrintDirectly(const ASTContext &Context, 6005 QualType IntendedTy, 6006 const Expr *E) { 6007 // Use a 'while' to peel off layers of typedefs. 6008 QualType TyTy = IntendedTy; 6009 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6010 StringRef Name = UserTy->getDecl()->getName(); 6011 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6012 .Case("CFIndex", Context.LongTy) 6013 .Case("NSInteger", Context.LongTy) 6014 .Case("NSUInteger", Context.UnsignedLongTy) 6015 .Case("SInt32", Context.IntTy) 6016 .Case("UInt32", Context.UnsignedIntTy) 6017 .Default(QualType()); 6018 6019 if (!CastTy.isNull()) 6020 return std::make_pair(CastTy, Name); 6021 6022 TyTy = UserTy->desugar(); 6023 } 6024 6025 // Strip parens if necessary. 6026 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6027 return shouldNotPrintDirectly(Context, 6028 PE->getSubExpr()->getType(), 6029 PE->getSubExpr()); 6030 6031 // If this is a conditional expression, then its result type is constructed 6032 // via usual arithmetic conversions and thus there might be no necessary 6033 // typedef sugar there. Recurse to operands to check for NSInteger & 6034 // Co. usage condition. 6035 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6036 QualType TrueTy, FalseTy; 6037 StringRef TrueName, FalseName; 6038 6039 std::tie(TrueTy, TrueName) = 6040 shouldNotPrintDirectly(Context, 6041 CO->getTrueExpr()->getType(), 6042 CO->getTrueExpr()); 6043 std::tie(FalseTy, FalseName) = 6044 shouldNotPrintDirectly(Context, 6045 CO->getFalseExpr()->getType(), 6046 CO->getFalseExpr()); 6047 6048 if (TrueTy == FalseTy) 6049 return std::make_pair(TrueTy, TrueName); 6050 else if (TrueTy.isNull()) 6051 return std::make_pair(FalseTy, FalseName); 6052 else if (FalseTy.isNull()) 6053 return std::make_pair(TrueTy, TrueName); 6054 } 6055 6056 return std::make_pair(QualType(), StringRef()); 6057 } 6058 6059 bool 6060 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6061 const char *StartSpecifier, 6062 unsigned SpecifierLen, 6063 const Expr *E) { 6064 using namespace analyze_format_string; 6065 using namespace analyze_printf; 6066 // Now type check the data expression that matches the 6067 // format specifier. 6068 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6069 if (!AT.isValid()) 6070 return true; 6071 6072 QualType ExprTy = E->getType(); 6073 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6074 ExprTy = TET->getUnderlyingExpr()->getType(); 6075 } 6076 6077 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6078 6079 if (match == analyze_printf::ArgType::Match) { 6080 return true; 6081 } 6082 6083 // Look through argument promotions for our error message's reported type. 6084 // This includes the integral and floating promotions, but excludes array 6085 // and function pointer decay; seeing that an argument intended to be a 6086 // string has type 'char [6]' is probably more confusing than 'char *'. 6087 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6088 if (ICE->getCastKind() == CK_IntegralCast || 6089 ICE->getCastKind() == CK_FloatingCast) { 6090 E = ICE->getSubExpr(); 6091 ExprTy = E->getType(); 6092 6093 // Check if we didn't match because of an implicit cast from a 'char' 6094 // or 'short' to an 'int'. This is done because printf is a varargs 6095 // function. 6096 if (ICE->getType() == S.Context.IntTy || 6097 ICE->getType() == S.Context.UnsignedIntTy) { 6098 // All further checking is done on the subexpression. 6099 if (AT.matchesType(S.Context, ExprTy)) 6100 return true; 6101 } 6102 } 6103 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6104 // Special case for 'a', which has type 'int' in C. 6105 // Note, however, that we do /not/ want to treat multibyte constants like 6106 // 'MooV' as characters! This form is deprecated but still exists. 6107 if (ExprTy == S.Context.IntTy) 6108 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6109 ExprTy = S.Context.CharTy; 6110 } 6111 6112 // Look through enums to their underlying type. 6113 bool IsEnum = false; 6114 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6115 ExprTy = EnumTy->getDecl()->getIntegerType(); 6116 IsEnum = true; 6117 } 6118 6119 // %C in an Objective-C context prints a unichar, not a wchar_t. 6120 // If the argument is an integer of some kind, believe the %C and suggest 6121 // a cast instead of changing the conversion specifier. 6122 QualType IntendedTy = ExprTy; 6123 if (isObjCContext() && 6124 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6125 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6126 !ExprTy->isCharType()) { 6127 // 'unichar' is defined as a typedef of unsigned short, but we should 6128 // prefer using the typedef if it is visible. 6129 IntendedTy = S.Context.UnsignedShortTy; 6130 6131 // While we are here, check if the value is an IntegerLiteral that happens 6132 // to be within the valid range. 6133 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6134 const llvm::APInt &V = IL->getValue(); 6135 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6136 return true; 6137 } 6138 6139 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6140 Sema::LookupOrdinaryName); 6141 if (S.LookupName(Result, S.getCurScope())) { 6142 NamedDecl *ND = Result.getFoundDecl(); 6143 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6144 if (TD->getUnderlyingType() == IntendedTy) 6145 IntendedTy = S.Context.getTypedefType(TD); 6146 } 6147 } 6148 } 6149 6150 // Special-case some of Darwin's platform-independence types by suggesting 6151 // casts to primitive types that are known to be large enough. 6152 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6153 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6154 QualType CastTy; 6155 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6156 if (!CastTy.isNull()) { 6157 IntendedTy = CastTy; 6158 ShouldNotPrintDirectly = true; 6159 } 6160 } 6161 6162 // We may be able to offer a FixItHint if it is a supported type. 6163 PrintfSpecifier fixedFS = FS; 6164 bool success = 6165 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6166 6167 if (success) { 6168 // Get the fix string from the fixed format specifier 6169 SmallString<16> buf; 6170 llvm::raw_svector_ostream os(buf); 6171 fixedFS.toString(os); 6172 6173 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6174 6175 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6176 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6177 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6178 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6179 } 6180 // In this case, the specifier is wrong and should be changed to match 6181 // the argument. 6182 EmitFormatDiagnostic(S.PDiag(diag) 6183 << AT.getRepresentativeTypeName(S.Context) 6184 << IntendedTy << IsEnum << E->getSourceRange(), 6185 E->getLocStart(), 6186 /*IsStringLocation*/ false, SpecRange, 6187 FixItHint::CreateReplacement(SpecRange, os.str())); 6188 } else { 6189 // The canonical type for formatting this value is different from the 6190 // actual type of the expression. (This occurs, for example, with Darwin's 6191 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6192 // should be printed as 'long' for 64-bit compatibility.) 6193 // Rather than emitting a normal format/argument mismatch, we want to 6194 // add a cast to the recommended type (and correct the format string 6195 // if necessary). 6196 SmallString<16> CastBuf; 6197 llvm::raw_svector_ostream CastFix(CastBuf); 6198 CastFix << "("; 6199 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6200 CastFix << ")"; 6201 6202 SmallVector<FixItHint,4> Hints; 6203 if (!AT.matchesType(S.Context, IntendedTy)) 6204 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6205 6206 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6207 // If there's already a cast present, just replace it. 6208 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6209 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6210 6211 } else if (!requiresParensToAddCast(E)) { 6212 // If the expression has high enough precedence, 6213 // just write the C-style cast. 6214 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6215 CastFix.str())); 6216 } else { 6217 // Otherwise, add parens around the expression as well as the cast. 6218 CastFix << "("; 6219 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6220 CastFix.str())); 6221 6222 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6223 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6224 } 6225 6226 if (ShouldNotPrintDirectly) { 6227 // The expression has a type that should not be printed directly. 6228 // We extract the name from the typedef because we don't want to show 6229 // the underlying type in the diagnostic. 6230 StringRef Name; 6231 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6232 Name = TypedefTy->getDecl()->getName(); 6233 else 6234 Name = CastTyName; 6235 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6236 << Name << IntendedTy << IsEnum 6237 << E->getSourceRange(), 6238 E->getLocStart(), /*IsStringLocation=*/false, 6239 SpecRange, Hints); 6240 } else { 6241 // In this case, the expression could be printed using a different 6242 // specifier, but we've decided that the specifier is probably correct 6243 // and we should cast instead. Just use the normal warning message. 6244 EmitFormatDiagnostic( 6245 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6246 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6247 << E->getSourceRange(), 6248 E->getLocStart(), /*IsStringLocation*/false, 6249 SpecRange, Hints); 6250 } 6251 } 6252 } else { 6253 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6254 SpecifierLen); 6255 // Since the warning for passing non-POD types to variadic functions 6256 // was deferred until now, we emit a warning for non-POD 6257 // arguments here. 6258 switch (S.isValidVarArgType(ExprTy)) { 6259 case Sema::VAK_Valid: 6260 case Sema::VAK_ValidInCXX11: { 6261 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6262 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6263 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6264 } 6265 6266 EmitFormatDiagnostic( 6267 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6268 << IsEnum << CSR << E->getSourceRange(), 6269 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6270 break; 6271 } 6272 case Sema::VAK_Undefined: 6273 case Sema::VAK_MSVCUndefined: 6274 EmitFormatDiagnostic( 6275 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6276 << S.getLangOpts().CPlusPlus11 6277 << ExprTy 6278 << CallType 6279 << AT.getRepresentativeTypeName(S.Context) 6280 << CSR 6281 << E->getSourceRange(), 6282 E->getLocStart(), /*IsStringLocation*/false, CSR); 6283 checkForCStrMembers(AT, E); 6284 break; 6285 6286 case Sema::VAK_Invalid: 6287 if (ExprTy->isObjCObjectType()) 6288 EmitFormatDiagnostic( 6289 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6290 << S.getLangOpts().CPlusPlus11 6291 << ExprTy 6292 << CallType 6293 << AT.getRepresentativeTypeName(S.Context) 6294 << CSR 6295 << E->getSourceRange(), 6296 E->getLocStart(), /*IsStringLocation*/false, CSR); 6297 else 6298 // FIXME: If this is an initializer list, suggest removing the braces 6299 // or inserting a cast to the target type. 6300 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6301 << isa<InitListExpr>(E) << ExprTy << CallType 6302 << AT.getRepresentativeTypeName(S.Context) 6303 << E->getSourceRange(); 6304 break; 6305 } 6306 6307 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6308 "format string specifier index out of range"); 6309 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6310 } 6311 6312 return true; 6313 } 6314 6315 //===--- CHECK: Scanf format string checking ------------------------------===// 6316 6317 namespace { 6318 class CheckScanfHandler : public CheckFormatHandler { 6319 public: 6320 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6321 const Expr *origFormatExpr, Sema::FormatStringType type, 6322 unsigned firstDataArg, unsigned numDataArgs, 6323 const char *beg, bool hasVAListArg, 6324 ArrayRef<const Expr *> Args, unsigned formatIdx, 6325 bool inFunctionCall, Sema::VariadicCallType CallType, 6326 llvm::SmallBitVector &CheckedVarArgs, 6327 UncoveredArgHandler &UncoveredArg) 6328 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6329 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6330 inFunctionCall, CallType, CheckedVarArgs, 6331 UncoveredArg) {} 6332 6333 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6334 const char *startSpecifier, 6335 unsigned specifierLen) override; 6336 6337 bool HandleInvalidScanfConversionSpecifier( 6338 const analyze_scanf::ScanfSpecifier &FS, 6339 const char *startSpecifier, 6340 unsigned specifierLen) override; 6341 6342 void HandleIncompleteScanList(const char *start, const char *end) override; 6343 }; 6344 } // end anonymous namespace 6345 6346 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6347 const char *end) { 6348 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6349 getLocationOfByte(end), /*IsStringLocation*/true, 6350 getSpecifierRange(start, end - start)); 6351 } 6352 6353 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6354 const analyze_scanf::ScanfSpecifier &FS, 6355 const char *startSpecifier, 6356 unsigned specifierLen) { 6357 6358 const analyze_scanf::ScanfConversionSpecifier &CS = 6359 FS.getConversionSpecifier(); 6360 6361 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6362 getLocationOfByte(CS.getStart()), 6363 startSpecifier, specifierLen, 6364 CS.getStart(), CS.getLength()); 6365 } 6366 6367 bool CheckScanfHandler::HandleScanfSpecifier( 6368 const analyze_scanf::ScanfSpecifier &FS, 6369 const char *startSpecifier, 6370 unsigned specifierLen) { 6371 using namespace analyze_scanf; 6372 using namespace analyze_format_string; 6373 6374 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6375 6376 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6377 // be used to decide if we are using positional arguments consistently. 6378 if (FS.consumesDataArgument()) { 6379 if (atFirstArg) { 6380 atFirstArg = false; 6381 usesPositionalArgs = FS.usesPositionalArg(); 6382 } 6383 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6384 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6385 startSpecifier, specifierLen); 6386 return false; 6387 } 6388 } 6389 6390 // Check if the field with is non-zero. 6391 const OptionalAmount &Amt = FS.getFieldWidth(); 6392 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6393 if (Amt.getConstantAmount() == 0) { 6394 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6395 Amt.getConstantLength()); 6396 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6397 getLocationOfByte(Amt.getStart()), 6398 /*IsStringLocation*/true, R, 6399 FixItHint::CreateRemoval(R)); 6400 } 6401 } 6402 6403 if (!FS.consumesDataArgument()) { 6404 // FIXME: Technically specifying a precision or field width here 6405 // makes no sense. Worth issuing a warning at some point. 6406 return true; 6407 } 6408 6409 // Consume the argument. 6410 unsigned argIndex = FS.getArgIndex(); 6411 if (argIndex < NumDataArgs) { 6412 // The check to see if the argIndex is valid will come later. 6413 // We set the bit here because we may exit early from this 6414 // function if we encounter some other error. 6415 CoveredArgs.set(argIndex); 6416 } 6417 6418 // Check the length modifier is valid with the given conversion specifier. 6419 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6420 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6421 diag::warn_format_nonsensical_length); 6422 else if (!FS.hasStandardLengthModifier()) 6423 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6424 else if (!FS.hasStandardLengthConversionCombination()) 6425 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6426 diag::warn_format_non_standard_conversion_spec); 6427 6428 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6429 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6430 6431 // The remaining checks depend on the data arguments. 6432 if (HasVAListArg) 6433 return true; 6434 6435 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6436 return false; 6437 6438 // Check that the argument type matches the format specifier. 6439 const Expr *Ex = getDataArg(argIndex); 6440 if (!Ex) 6441 return true; 6442 6443 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6444 6445 if (!AT.isValid()) { 6446 return true; 6447 } 6448 6449 analyze_format_string::ArgType::MatchKind match = 6450 AT.matchesType(S.Context, Ex->getType()); 6451 if (match == analyze_format_string::ArgType::Match) { 6452 return true; 6453 } 6454 6455 ScanfSpecifier fixedFS = FS; 6456 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6457 S.getLangOpts(), S.Context); 6458 6459 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6460 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6461 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6462 } 6463 6464 if (success) { 6465 // Get the fix string from the fixed format specifier. 6466 SmallString<128> buf; 6467 llvm::raw_svector_ostream os(buf); 6468 fixedFS.toString(os); 6469 6470 EmitFormatDiagnostic( 6471 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6472 << Ex->getType() << false << Ex->getSourceRange(), 6473 Ex->getLocStart(), 6474 /*IsStringLocation*/ false, 6475 getSpecifierRange(startSpecifier, specifierLen), 6476 FixItHint::CreateReplacement( 6477 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6478 } else { 6479 EmitFormatDiagnostic(S.PDiag(diag) 6480 << AT.getRepresentativeTypeName(S.Context) 6481 << Ex->getType() << false << Ex->getSourceRange(), 6482 Ex->getLocStart(), 6483 /*IsStringLocation*/ false, 6484 getSpecifierRange(startSpecifier, specifierLen)); 6485 } 6486 6487 return true; 6488 } 6489 6490 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6491 const Expr *OrigFormatExpr, 6492 ArrayRef<const Expr *> Args, 6493 bool HasVAListArg, unsigned format_idx, 6494 unsigned firstDataArg, 6495 Sema::FormatStringType Type, 6496 bool inFunctionCall, 6497 Sema::VariadicCallType CallType, 6498 llvm::SmallBitVector &CheckedVarArgs, 6499 UncoveredArgHandler &UncoveredArg) { 6500 // CHECK: is the format string a wide literal? 6501 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6502 CheckFormatHandler::EmitFormatDiagnostic( 6503 S, inFunctionCall, Args[format_idx], 6504 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6505 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6506 return; 6507 } 6508 6509 // Str - The format string. NOTE: this is NOT null-terminated! 6510 StringRef StrRef = FExpr->getString(); 6511 const char *Str = StrRef.data(); 6512 // Account for cases where the string literal is truncated in a declaration. 6513 const ConstantArrayType *T = 6514 S.Context.getAsConstantArrayType(FExpr->getType()); 6515 assert(T && "String literal not of constant array type!"); 6516 size_t TypeSize = T->getSize().getZExtValue(); 6517 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6518 const unsigned numDataArgs = Args.size() - firstDataArg; 6519 6520 // Emit a warning if the string literal is truncated and does not contain an 6521 // embedded null character. 6522 if (TypeSize <= StrRef.size() && 6523 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6524 CheckFormatHandler::EmitFormatDiagnostic( 6525 S, inFunctionCall, Args[format_idx], 6526 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6527 FExpr->getLocStart(), 6528 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6529 return; 6530 } 6531 6532 // CHECK: empty format string? 6533 if (StrLen == 0 && numDataArgs > 0) { 6534 CheckFormatHandler::EmitFormatDiagnostic( 6535 S, inFunctionCall, Args[format_idx], 6536 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6537 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6538 return; 6539 } 6540 6541 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6542 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6543 Type == Sema::FST_OSTrace) { 6544 CheckPrintfHandler H( 6545 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6546 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6547 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6548 CheckedVarArgs, UncoveredArg); 6549 6550 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6551 S.getLangOpts(), 6552 S.Context.getTargetInfo(), 6553 Type == Sema::FST_FreeBSDKPrintf)) 6554 H.DoneProcessing(); 6555 } else if (Type == Sema::FST_Scanf) { 6556 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6557 numDataArgs, Str, HasVAListArg, Args, format_idx, 6558 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6559 6560 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6561 S.getLangOpts(), 6562 S.Context.getTargetInfo())) 6563 H.DoneProcessing(); 6564 } // TODO: handle other formats 6565 } 6566 6567 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6568 // Str - The format string. NOTE: this is NOT null-terminated! 6569 StringRef StrRef = FExpr->getString(); 6570 const char *Str = StrRef.data(); 6571 // Account for cases where the string literal is truncated in a declaration. 6572 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6573 assert(T && "String literal not of constant array type!"); 6574 size_t TypeSize = T->getSize().getZExtValue(); 6575 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6576 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6577 getLangOpts(), 6578 Context.getTargetInfo()); 6579 } 6580 6581 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6582 6583 // Returns the related absolute value function that is larger, of 0 if one 6584 // does not exist. 6585 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6586 switch (AbsFunction) { 6587 default: 6588 return 0; 6589 6590 case Builtin::BI__builtin_abs: 6591 return Builtin::BI__builtin_labs; 6592 case Builtin::BI__builtin_labs: 6593 return Builtin::BI__builtin_llabs; 6594 case Builtin::BI__builtin_llabs: 6595 return 0; 6596 6597 case Builtin::BI__builtin_fabsf: 6598 return Builtin::BI__builtin_fabs; 6599 case Builtin::BI__builtin_fabs: 6600 return Builtin::BI__builtin_fabsl; 6601 case Builtin::BI__builtin_fabsl: 6602 return 0; 6603 6604 case Builtin::BI__builtin_cabsf: 6605 return Builtin::BI__builtin_cabs; 6606 case Builtin::BI__builtin_cabs: 6607 return Builtin::BI__builtin_cabsl; 6608 case Builtin::BI__builtin_cabsl: 6609 return 0; 6610 6611 case Builtin::BIabs: 6612 return Builtin::BIlabs; 6613 case Builtin::BIlabs: 6614 return Builtin::BIllabs; 6615 case Builtin::BIllabs: 6616 return 0; 6617 6618 case Builtin::BIfabsf: 6619 return Builtin::BIfabs; 6620 case Builtin::BIfabs: 6621 return Builtin::BIfabsl; 6622 case Builtin::BIfabsl: 6623 return 0; 6624 6625 case Builtin::BIcabsf: 6626 return Builtin::BIcabs; 6627 case Builtin::BIcabs: 6628 return Builtin::BIcabsl; 6629 case Builtin::BIcabsl: 6630 return 0; 6631 } 6632 } 6633 6634 // Returns the argument type of the absolute value function. 6635 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6636 unsigned AbsType) { 6637 if (AbsType == 0) 6638 return QualType(); 6639 6640 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6641 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6642 if (Error != ASTContext::GE_None) 6643 return QualType(); 6644 6645 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6646 if (!FT) 6647 return QualType(); 6648 6649 if (FT->getNumParams() != 1) 6650 return QualType(); 6651 6652 return FT->getParamType(0); 6653 } 6654 6655 // Returns the best absolute value function, or zero, based on type and 6656 // current absolute value function. 6657 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6658 unsigned AbsFunctionKind) { 6659 unsigned BestKind = 0; 6660 uint64_t ArgSize = Context.getTypeSize(ArgType); 6661 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6662 Kind = getLargerAbsoluteValueFunction(Kind)) { 6663 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6664 if (Context.getTypeSize(ParamType) >= ArgSize) { 6665 if (BestKind == 0) 6666 BestKind = Kind; 6667 else if (Context.hasSameType(ParamType, ArgType)) { 6668 BestKind = Kind; 6669 break; 6670 } 6671 } 6672 } 6673 return BestKind; 6674 } 6675 6676 enum AbsoluteValueKind { 6677 AVK_Integer, 6678 AVK_Floating, 6679 AVK_Complex 6680 }; 6681 6682 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6683 if (T->isIntegralOrEnumerationType()) 6684 return AVK_Integer; 6685 if (T->isRealFloatingType()) 6686 return AVK_Floating; 6687 if (T->isAnyComplexType()) 6688 return AVK_Complex; 6689 6690 llvm_unreachable("Type not integer, floating, or complex"); 6691 } 6692 6693 // Changes the absolute value function to a different type. Preserves whether 6694 // the function is a builtin. 6695 static unsigned changeAbsFunction(unsigned AbsKind, 6696 AbsoluteValueKind ValueKind) { 6697 switch (ValueKind) { 6698 case AVK_Integer: 6699 switch (AbsKind) { 6700 default: 6701 return 0; 6702 case Builtin::BI__builtin_fabsf: 6703 case Builtin::BI__builtin_fabs: 6704 case Builtin::BI__builtin_fabsl: 6705 case Builtin::BI__builtin_cabsf: 6706 case Builtin::BI__builtin_cabs: 6707 case Builtin::BI__builtin_cabsl: 6708 return Builtin::BI__builtin_abs; 6709 case Builtin::BIfabsf: 6710 case Builtin::BIfabs: 6711 case Builtin::BIfabsl: 6712 case Builtin::BIcabsf: 6713 case Builtin::BIcabs: 6714 case Builtin::BIcabsl: 6715 return Builtin::BIabs; 6716 } 6717 case AVK_Floating: 6718 switch (AbsKind) { 6719 default: 6720 return 0; 6721 case Builtin::BI__builtin_abs: 6722 case Builtin::BI__builtin_labs: 6723 case Builtin::BI__builtin_llabs: 6724 case Builtin::BI__builtin_cabsf: 6725 case Builtin::BI__builtin_cabs: 6726 case Builtin::BI__builtin_cabsl: 6727 return Builtin::BI__builtin_fabsf; 6728 case Builtin::BIabs: 6729 case Builtin::BIlabs: 6730 case Builtin::BIllabs: 6731 case Builtin::BIcabsf: 6732 case Builtin::BIcabs: 6733 case Builtin::BIcabsl: 6734 return Builtin::BIfabsf; 6735 } 6736 case AVK_Complex: 6737 switch (AbsKind) { 6738 default: 6739 return 0; 6740 case Builtin::BI__builtin_abs: 6741 case Builtin::BI__builtin_labs: 6742 case Builtin::BI__builtin_llabs: 6743 case Builtin::BI__builtin_fabsf: 6744 case Builtin::BI__builtin_fabs: 6745 case Builtin::BI__builtin_fabsl: 6746 return Builtin::BI__builtin_cabsf; 6747 case Builtin::BIabs: 6748 case Builtin::BIlabs: 6749 case Builtin::BIllabs: 6750 case Builtin::BIfabsf: 6751 case Builtin::BIfabs: 6752 case Builtin::BIfabsl: 6753 return Builtin::BIcabsf; 6754 } 6755 } 6756 llvm_unreachable("Unable to convert function"); 6757 } 6758 6759 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6760 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6761 if (!FnInfo) 6762 return 0; 6763 6764 switch (FDecl->getBuiltinID()) { 6765 default: 6766 return 0; 6767 case Builtin::BI__builtin_abs: 6768 case Builtin::BI__builtin_fabs: 6769 case Builtin::BI__builtin_fabsf: 6770 case Builtin::BI__builtin_fabsl: 6771 case Builtin::BI__builtin_labs: 6772 case Builtin::BI__builtin_llabs: 6773 case Builtin::BI__builtin_cabs: 6774 case Builtin::BI__builtin_cabsf: 6775 case Builtin::BI__builtin_cabsl: 6776 case Builtin::BIabs: 6777 case Builtin::BIlabs: 6778 case Builtin::BIllabs: 6779 case Builtin::BIfabs: 6780 case Builtin::BIfabsf: 6781 case Builtin::BIfabsl: 6782 case Builtin::BIcabs: 6783 case Builtin::BIcabsf: 6784 case Builtin::BIcabsl: 6785 return FDecl->getBuiltinID(); 6786 } 6787 llvm_unreachable("Unknown Builtin type"); 6788 } 6789 6790 // If the replacement is valid, emit a note with replacement function. 6791 // Additionally, suggest including the proper header if not already included. 6792 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6793 unsigned AbsKind, QualType ArgType) { 6794 bool EmitHeaderHint = true; 6795 const char *HeaderName = nullptr; 6796 const char *FunctionName = nullptr; 6797 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6798 FunctionName = "std::abs"; 6799 if (ArgType->isIntegralOrEnumerationType()) { 6800 HeaderName = "cstdlib"; 6801 } else if (ArgType->isRealFloatingType()) { 6802 HeaderName = "cmath"; 6803 } else { 6804 llvm_unreachable("Invalid Type"); 6805 } 6806 6807 // Lookup all std::abs 6808 if (NamespaceDecl *Std = S.getStdNamespace()) { 6809 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6810 R.suppressDiagnostics(); 6811 S.LookupQualifiedName(R, Std); 6812 6813 for (const auto *I : R) { 6814 const FunctionDecl *FDecl = nullptr; 6815 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6816 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6817 } else { 6818 FDecl = dyn_cast<FunctionDecl>(I); 6819 } 6820 if (!FDecl) 6821 continue; 6822 6823 // Found std::abs(), check that they are the right ones. 6824 if (FDecl->getNumParams() != 1) 6825 continue; 6826 6827 // Check that the parameter type can handle the argument. 6828 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6829 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6830 S.Context.getTypeSize(ArgType) <= 6831 S.Context.getTypeSize(ParamType)) { 6832 // Found a function, don't need the header hint. 6833 EmitHeaderHint = false; 6834 break; 6835 } 6836 } 6837 } 6838 } else { 6839 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6840 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6841 6842 if (HeaderName) { 6843 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6844 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6845 R.suppressDiagnostics(); 6846 S.LookupName(R, S.getCurScope()); 6847 6848 if (R.isSingleResult()) { 6849 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6850 if (FD && FD->getBuiltinID() == AbsKind) { 6851 EmitHeaderHint = false; 6852 } else { 6853 return; 6854 } 6855 } else if (!R.empty()) { 6856 return; 6857 } 6858 } 6859 } 6860 6861 S.Diag(Loc, diag::note_replace_abs_function) 6862 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 6863 6864 if (!HeaderName) 6865 return; 6866 6867 if (!EmitHeaderHint) 6868 return; 6869 6870 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 6871 << FunctionName; 6872 } 6873 6874 template <std::size_t StrLen> 6875 static bool IsStdFunction(const FunctionDecl *FDecl, 6876 const char (&Str)[StrLen]) { 6877 if (!FDecl) 6878 return false; 6879 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 6880 return false; 6881 if (!FDecl->isInStdNamespace()) 6882 return false; 6883 6884 return true; 6885 } 6886 6887 // Warn when using the wrong abs() function. 6888 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 6889 const FunctionDecl *FDecl) { 6890 if (Call->getNumArgs() != 1) 6891 return; 6892 6893 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 6894 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 6895 if (AbsKind == 0 && !IsStdAbs) 6896 return; 6897 6898 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6899 QualType ParamType = Call->getArg(0)->getType(); 6900 6901 // Unsigned types cannot be negative. Suggest removing the absolute value 6902 // function call. 6903 if (ArgType->isUnsignedIntegerType()) { 6904 const char *FunctionName = 6905 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 6906 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 6907 Diag(Call->getExprLoc(), diag::note_remove_abs) 6908 << FunctionName 6909 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 6910 return; 6911 } 6912 6913 // Taking the absolute value of a pointer is very suspicious, they probably 6914 // wanted to index into an array, dereference a pointer, call a function, etc. 6915 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 6916 unsigned DiagType = 0; 6917 if (ArgType->isFunctionType()) 6918 DiagType = 1; 6919 else if (ArgType->isArrayType()) 6920 DiagType = 2; 6921 6922 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 6923 return; 6924 } 6925 6926 // std::abs has overloads which prevent most of the absolute value problems 6927 // from occurring. 6928 if (IsStdAbs) 6929 return; 6930 6931 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 6932 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 6933 6934 // The argument and parameter are the same kind. Check if they are the right 6935 // size. 6936 if (ArgValueKind == ParamValueKind) { 6937 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 6938 return; 6939 6940 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 6941 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 6942 << FDecl << ArgType << ParamType; 6943 6944 if (NewAbsKind == 0) 6945 return; 6946 6947 emitReplacement(*this, Call->getExprLoc(), 6948 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6949 return; 6950 } 6951 6952 // ArgValueKind != ParamValueKind 6953 // The wrong type of absolute value function was used. Attempt to find the 6954 // proper one. 6955 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 6956 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 6957 if (NewAbsKind == 0) 6958 return; 6959 6960 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 6961 << FDecl << ParamValueKind << ArgValueKind; 6962 6963 emitReplacement(*this, Call->getExprLoc(), 6964 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6965 } 6966 6967 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 6968 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 6969 const FunctionDecl *FDecl) { 6970 if (!Call || !FDecl) return; 6971 6972 // Ignore template specializations and macros. 6973 if (inTemplateInstantiation()) return; 6974 if (Call->getExprLoc().isMacroID()) return; 6975 6976 // Only care about the one template argument, two function parameter std::max 6977 if (Call->getNumArgs() != 2) return; 6978 if (!IsStdFunction(FDecl, "max")) return; 6979 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 6980 if (!ArgList) return; 6981 if (ArgList->size() != 1) return; 6982 6983 // Check that template type argument is unsigned integer. 6984 const auto& TA = ArgList->get(0); 6985 if (TA.getKind() != TemplateArgument::Type) return; 6986 QualType ArgType = TA.getAsType(); 6987 if (!ArgType->isUnsignedIntegerType()) return; 6988 6989 // See if either argument is a literal zero. 6990 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 6991 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 6992 if (!MTE) return false; 6993 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 6994 if (!Num) return false; 6995 if (Num->getValue() != 0) return false; 6996 return true; 6997 }; 6998 6999 const Expr *FirstArg = Call->getArg(0); 7000 const Expr *SecondArg = Call->getArg(1); 7001 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7002 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7003 7004 // Only warn when exactly one argument is zero. 7005 if (IsFirstArgZero == IsSecondArgZero) return; 7006 7007 SourceRange FirstRange = FirstArg->getSourceRange(); 7008 SourceRange SecondRange = SecondArg->getSourceRange(); 7009 7010 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7011 7012 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7013 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7014 7015 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7016 SourceRange RemovalRange; 7017 if (IsFirstArgZero) { 7018 RemovalRange = SourceRange(FirstRange.getBegin(), 7019 SecondRange.getBegin().getLocWithOffset(-1)); 7020 } else { 7021 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7022 SecondRange.getEnd()); 7023 } 7024 7025 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7026 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7027 << FixItHint::CreateRemoval(RemovalRange); 7028 } 7029 7030 //===--- CHECK: Standard memory functions ---------------------------------===// 7031 7032 /// \brief Takes the expression passed to the size_t parameter of functions 7033 /// such as memcmp, strncat, etc and warns if it's a comparison. 7034 /// 7035 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7036 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7037 IdentifierInfo *FnName, 7038 SourceLocation FnLoc, 7039 SourceLocation RParenLoc) { 7040 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7041 if (!Size) 7042 return false; 7043 7044 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 7045 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 7046 return false; 7047 7048 SourceRange SizeRange = Size->getSourceRange(); 7049 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7050 << SizeRange << FnName; 7051 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7052 << FnName << FixItHint::CreateInsertion( 7053 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7054 << FixItHint::CreateRemoval(RParenLoc); 7055 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7056 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7057 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7058 ")"); 7059 7060 return true; 7061 } 7062 7063 /// \brief Determine whether the given type is or contains a dynamic class type 7064 /// (e.g., whether it has a vtable). 7065 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7066 bool &IsContained) { 7067 // Look through array types while ignoring qualifiers. 7068 const Type *Ty = T->getBaseElementTypeUnsafe(); 7069 IsContained = false; 7070 7071 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7072 RD = RD ? RD->getDefinition() : nullptr; 7073 if (!RD || RD->isInvalidDecl()) 7074 return nullptr; 7075 7076 if (RD->isDynamicClass()) 7077 return RD; 7078 7079 // Check all the fields. If any bases were dynamic, the class is dynamic. 7080 // It's impossible for a class to transitively contain itself by value, so 7081 // infinite recursion is impossible. 7082 for (auto *FD : RD->fields()) { 7083 bool SubContained; 7084 if (const CXXRecordDecl *ContainedRD = 7085 getContainedDynamicClass(FD->getType(), SubContained)) { 7086 IsContained = true; 7087 return ContainedRD; 7088 } 7089 } 7090 7091 return nullptr; 7092 } 7093 7094 /// \brief If E is a sizeof expression, returns its argument expression, 7095 /// otherwise returns NULL. 7096 static const Expr *getSizeOfExprArg(const Expr *E) { 7097 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7098 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7099 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 7100 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7101 7102 return nullptr; 7103 } 7104 7105 /// \brief If E is a sizeof expression, returns its argument type. 7106 static QualType getSizeOfArgType(const Expr *E) { 7107 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7108 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7109 if (SizeOf->getKind() == clang::UETT_SizeOf) 7110 return SizeOf->getTypeOfArgument(); 7111 7112 return QualType(); 7113 } 7114 7115 /// \brief Check for dangerous or invalid arguments to memset(). 7116 /// 7117 /// This issues warnings on known problematic, dangerous or unspecified 7118 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7119 /// function calls. 7120 /// 7121 /// \param Call The call expression to diagnose. 7122 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7123 unsigned BId, 7124 IdentifierInfo *FnName) { 7125 assert(BId != 0); 7126 7127 // It is possible to have a non-standard definition of memset. Validate 7128 // we have enough arguments, and if not, abort further checking. 7129 unsigned ExpectedNumArgs = 7130 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7131 if (Call->getNumArgs() < ExpectedNumArgs) 7132 return; 7133 7134 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7135 BId == Builtin::BIstrndup ? 1 : 2); 7136 unsigned LenArg = 7137 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7138 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7139 7140 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7141 Call->getLocStart(), Call->getRParenLoc())) 7142 return; 7143 7144 // We have special checking when the length is a sizeof expression. 7145 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7146 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7147 llvm::FoldingSetNodeID SizeOfArgID; 7148 7149 // Although widely used, 'bzero' is not a standard function. Be more strict 7150 // with the argument types before allowing diagnostics and only allow the 7151 // form bzero(ptr, sizeof(...)). 7152 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7153 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7154 return; 7155 7156 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7157 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7158 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7159 7160 QualType DestTy = Dest->getType(); 7161 QualType PointeeTy; 7162 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7163 PointeeTy = DestPtrTy->getPointeeType(); 7164 7165 // Never warn about void type pointers. This can be used to suppress 7166 // false positives. 7167 if (PointeeTy->isVoidType()) 7168 continue; 7169 7170 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7171 // actually comparing the expressions for equality. Because computing the 7172 // expression IDs can be expensive, we only do this if the diagnostic is 7173 // enabled. 7174 if (SizeOfArg && 7175 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7176 SizeOfArg->getExprLoc())) { 7177 // We only compute IDs for expressions if the warning is enabled, and 7178 // cache the sizeof arg's ID. 7179 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7180 SizeOfArg->Profile(SizeOfArgID, Context, true); 7181 llvm::FoldingSetNodeID DestID; 7182 Dest->Profile(DestID, Context, true); 7183 if (DestID == SizeOfArgID) { 7184 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7185 // over sizeof(src) as well. 7186 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7187 StringRef ReadableName = FnName->getName(); 7188 7189 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7190 if (UnaryOp->getOpcode() == UO_AddrOf) 7191 ActionIdx = 1; // If its an address-of operator, just remove it. 7192 if (!PointeeTy->isIncompleteType() && 7193 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7194 ActionIdx = 2; // If the pointee's size is sizeof(char), 7195 // suggest an explicit length. 7196 7197 // If the function is defined as a builtin macro, do not show macro 7198 // expansion. 7199 SourceLocation SL = SizeOfArg->getExprLoc(); 7200 SourceRange DSR = Dest->getSourceRange(); 7201 SourceRange SSR = SizeOfArg->getSourceRange(); 7202 SourceManager &SM = getSourceManager(); 7203 7204 if (SM.isMacroArgExpansion(SL)) { 7205 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7206 SL = SM.getSpellingLoc(SL); 7207 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7208 SM.getSpellingLoc(DSR.getEnd())); 7209 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7210 SM.getSpellingLoc(SSR.getEnd())); 7211 } 7212 7213 DiagRuntimeBehavior(SL, SizeOfArg, 7214 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7215 << ReadableName 7216 << PointeeTy 7217 << DestTy 7218 << DSR 7219 << SSR); 7220 DiagRuntimeBehavior(SL, SizeOfArg, 7221 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7222 << ActionIdx 7223 << SSR); 7224 7225 break; 7226 } 7227 } 7228 7229 // Also check for cases where the sizeof argument is the exact same 7230 // type as the memory argument, and where it points to a user-defined 7231 // record type. 7232 if (SizeOfArgTy != QualType()) { 7233 if (PointeeTy->isRecordType() && 7234 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7235 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7236 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7237 << FnName << SizeOfArgTy << ArgIdx 7238 << PointeeTy << Dest->getSourceRange() 7239 << LenExpr->getSourceRange()); 7240 break; 7241 } 7242 } 7243 } else if (DestTy->isArrayType()) { 7244 PointeeTy = DestTy; 7245 } 7246 7247 if (PointeeTy == QualType()) 7248 continue; 7249 7250 // Always complain about dynamic classes. 7251 bool IsContained; 7252 if (const CXXRecordDecl *ContainedRD = 7253 getContainedDynamicClass(PointeeTy, IsContained)) { 7254 7255 unsigned OperationType = 0; 7256 // "overwritten" if we're warning about the destination for any call 7257 // but memcmp; otherwise a verb appropriate to the call. 7258 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7259 if (BId == Builtin::BImemcpy) 7260 OperationType = 1; 7261 else if(BId == Builtin::BImemmove) 7262 OperationType = 2; 7263 else if (BId == Builtin::BImemcmp) 7264 OperationType = 3; 7265 } 7266 7267 DiagRuntimeBehavior( 7268 Dest->getExprLoc(), Dest, 7269 PDiag(diag::warn_dyn_class_memaccess) 7270 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7271 << FnName << IsContained << ContainedRD << OperationType 7272 << Call->getCallee()->getSourceRange()); 7273 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7274 BId != Builtin::BImemset) 7275 DiagRuntimeBehavior( 7276 Dest->getExprLoc(), Dest, 7277 PDiag(diag::warn_arc_object_memaccess) 7278 << ArgIdx << FnName << PointeeTy 7279 << Call->getCallee()->getSourceRange()); 7280 else 7281 continue; 7282 7283 DiagRuntimeBehavior( 7284 Dest->getExprLoc(), Dest, 7285 PDiag(diag::note_bad_memaccess_silence) 7286 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7287 break; 7288 } 7289 } 7290 7291 // A little helper routine: ignore addition and subtraction of integer literals. 7292 // This intentionally does not ignore all integer constant expressions because 7293 // we don't want to remove sizeof(). 7294 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7295 Ex = Ex->IgnoreParenCasts(); 7296 7297 for (;;) { 7298 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7299 if (!BO || !BO->isAdditiveOp()) 7300 break; 7301 7302 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7303 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7304 7305 if (isa<IntegerLiteral>(RHS)) 7306 Ex = LHS; 7307 else if (isa<IntegerLiteral>(LHS)) 7308 Ex = RHS; 7309 else 7310 break; 7311 } 7312 7313 return Ex; 7314 } 7315 7316 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7317 ASTContext &Context) { 7318 // Only handle constant-sized or VLAs, but not flexible members. 7319 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7320 // Only issue the FIXIT for arrays of size > 1. 7321 if (CAT->getSize().getSExtValue() <= 1) 7322 return false; 7323 } else if (!Ty->isVariableArrayType()) { 7324 return false; 7325 } 7326 return true; 7327 } 7328 7329 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7330 // be the size of the source, instead of the destination. 7331 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7332 IdentifierInfo *FnName) { 7333 7334 // Don't crash if the user has the wrong number of arguments 7335 unsigned NumArgs = Call->getNumArgs(); 7336 if ((NumArgs != 3) && (NumArgs != 4)) 7337 return; 7338 7339 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7340 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7341 const Expr *CompareWithSrc = nullptr; 7342 7343 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7344 Call->getLocStart(), Call->getRParenLoc())) 7345 return; 7346 7347 // Look for 'strlcpy(dst, x, sizeof(x))' 7348 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7349 CompareWithSrc = Ex; 7350 else { 7351 // Look for 'strlcpy(dst, x, strlen(x))' 7352 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7353 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7354 SizeCall->getNumArgs() == 1) 7355 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7356 } 7357 } 7358 7359 if (!CompareWithSrc) 7360 return; 7361 7362 // Determine if the argument to sizeof/strlen is equal to the source 7363 // argument. In principle there's all kinds of things you could do 7364 // here, for instance creating an == expression and evaluating it with 7365 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7366 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7367 if (!SrcArgDRE) 7368 return; 7369 7370 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7371 if (!CompareWithSrcDRE || 7372 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7373 return; 7374 7375 const Expr *OriginalSizeArg = Call->getArg(2); 7376 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7377 << OriginalSizeArg->getSourceRange() << FnName; 7378 7379 // Output a FIXIT hint if the destination is an array (rather than a 7380 // pointer to an array). This could be enhanced to handle some 7381 // pointers if we know the actual size, like if DstArg is 'array+2' 7382 // we could say 'sizeof(array)-2'. 7383 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7384 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7385 return; 7386 7387 SmallString<128> sizeString; 7388 llvm::raw_svector_ostream OS(sizeString); 7389 OS << "sizeof("; 7390 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7391 OS << ")"; 7392 7393 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7394 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7395 OS.str()); 7396 } 7397 7398 /// Check if two expressions refer to the same declaration. 7399 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7400 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7401 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7402 return D1->getDecl() == D2->getDecl(); 7403 return false; 7404 } 7405 7406 static const Expr *getStrlenExprArg(const Expr *E) { 7407 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7408 const FunctionDecl *FD = CE->getDirectCallee(); 7409 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7410 return nullptr; 7411 return CE->getArg(0)->IgnoreParenCasts(); 7412 } 7413 return nullptr; 7414 } 7415 7416 // Warn on anti-patterns as the 'size' argument to strncat. 7417 // The correct size argument should look like following: 7418 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7419 void Sema::CheckStrncatArguments(const CallExpr *CE, 7420 IdentifierInfo *FnName) { 7421 // Don't crash if the user has the wrong number of arguments. 7422 if (CE->getNumArgs() < 3) 7423 return; 7424 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7425 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7426 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7427 7428 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7429 CE->getRParenLoc())) 7430 return; 7431 7432 // Identify common expressions, which are wrongly used as the size argument 7433 // to strncat and may lead to buffer overflows. 7434 unsigned PatternType = 0; 7435 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7436 // - sizeof(dst) 7437 if (referToTheSameDecl(SizeOfArg, DstArg)) 7438 PatternType = 1; 7439 // - sizeof(src) 7440 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7441 PatternType = 2; 7442 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7443 if (BE->getOpcode() == BO_Sub) { 7444 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7445 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7446 // - sizeof(dst) - strlen(dst) 7447 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7448 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7449 PatternType = 1; 7450 // - sizeof(src) - (anything) 7451 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7452 PatternType = 2; 7453 } 7454 } 7455 7456 if (PatternType == 0) 7457 return; 7458 7459 // Generate the diagnostic. 7460 SourceLocation SL = LenArg->getLocStart(); 7461 SourceRange SR = LenArg->getSourceRange(); 7462 SourceManager &SM = getSourceManager(); 7463 7464 // If the function is defined as a builtin macro, do not show macro expansion. 7465 if (SM.isMacroArgExpansion(SL)) { 7466 SL = SM.getSpellingLoc(SL); 7467 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7468 SM.getSpellingLoc(SR.getEnd())); 7469 } 7470 7471 // Check if the destination is an array (rather than a pointer to an array). 7472 QualType DstTy = DstArg->getType(); 7473 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7474 Context); 7475 if (!isKnownSizeArray) { 7476 if (PatternType == 1) 7477 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7478 else 7479 Diag(SL, diag::warn_strncat_src_size) << SR; 7480 return; 7481 } 7482 7483 if (PatternType == 1) 7484 Diag(SL, diag::warn_strncat_large_size) << SR; 7485 else 7486 Diag(SL, diag::warn_strncat_src_size) << SR; 7487 7488 SmallString<128> sizeString; 7489 llvm::raw_svector_ostream OS(sizeString); 7490 OS << "sizeof("; 7491 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7492 OS << ") - "; 7493 OS << "strlen("; 7494 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7495 OS << ") - 1"; 7496 7497 Diag(SL, diag::note_strncat_wrong_size) 7498 << FixItHint::CreateReplacement(SR, OS.str()); 7499 } 7500 7501 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7502 7503 static const Expr *EvalVal(const Expr *E, 7504 SmallVectorImpl<const DeclRefExpr *> &refVars, 7505 const Decl *ParentDecl); 7506 static const Expr *EvalAddr(const Expr *E, 7507 SmallVectorImpl<const DeclRefExpr *> &refVars, 7508 const Decl *ParentDecl); 7509 7510 /// CheckReturnStackAddr - Check if a return statement returns the address 7511 /// of a stack variable. 7512 static void 7513 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7514 SourceLocation ReturnLoc) { 7515 7516 const Expr *stackE = nullptr; 7517 SmallVector<const DeclRefExpr *, 8> refVars; 7518 7519 // Perform checking for returned stack addresses, local blocks, 7520 // label addresses or references to temporaries. 7521 if (lhsType->isPointerType() || 7522 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7523 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7524 } else if (lhsType->isReferenceType()) { 7525 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7526 } 7527 7528 if (!stackE) 7529 return; // Nothing suspicious was found. 7530 7531 // Parameters are initialized in the calling scope, so taking the address 7532 // of a parameter reference doesn't need a warning. 7533 for (auto *DRE : refVars) 7534 if (isa<ParmVarDecl>(DRE->getDecl())) 7535 return; 7536 7537 SourceLocation diagLoc; 7538 SourceRange diagRange; 7539 if (refVars.empty()) { 7540 diagLoc = stackE->getLocStart(); 7541 diagRange = stackE->getSourceRange(); 7542 } else { 7543 // We followed through a reference variable. 'stackE' contains the 7544 // problematic expression but we will warn at the return statement pointing 7545 // at the reference variable. We will later display the "trail" of 7546 // reference variables using notes. 7547 diagLoc = refVars[0]->getLocStart(); 7548 diagRange = refVars[0]->getSourceRange(); 7549 } 7550 7551 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7552 // address of local var 7553 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7554 << DR->getDecl()->getDeclName() << diagRange; 7555 } else if (isa<BlockExpr>(stackE)) { // local block. 7556 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7557 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7558 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7559 } else { // local temporary. 7560 // If there is an LValue->RValue conversion, then the value of the 7561 // reference type is used, not the reference. 7562 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7563 if (ICE->getCastKind() == CK_LValueToRValue) { 7564 return; 7565 } 7566 } 7567 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7568 << lhsType->isReferenceType() << diagRange; 7569 } 7570 7571 // Display the "trail" of reference variables that we followed until we 7572 // found the problematic expression using notes. 7573 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7574 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7575 // If this var binds to another reference var, show the range of the next 7576 // var, otherwise the var binds to the problematic expression, in which case 7577 // show the range of the expression. 7578 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7579 : stackE->getSourceRange(); 7580 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7581 << VD->getDeclName() << range; 7582 } 7583 } 7584 7585 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7586 /// check if the expression in a return statement evaluates to an address 7587 /// to a location on the stack, a local block, an address of a label, or a 7588 /// reference to local temporary. The recursion is used to traverse the 7589 /// AST of the return expression, with recursion backtracking when we 7590 /// encounter a subexpression that (1) clearly does not lead to one of the 7591 /// above problematic expressions (2) is something we cannot determine leads to 7592 /// a problematic expression based on such local checking. 7593 /// 7594 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7595 /// the expression that they point to. Such variables are added to the 7596 /// 'refVars' vector so that we know what the reference variable "trail" was. 7597 /// 7598 /// EvalAddr processes expressions that are pointers that are used as 7599 /// references (and not L-values). EvalVal handles all other values. 7600 /// At the base case of the recursion is a check for the above problematic 7601 /// expressions. 7602 /// 7603 /// This implementation handles: 7604 /// 7605 /// * pointer-to-pointer casts 7606 /// * implicit conversions from array references to pointers 7607 /// * taking the address of fields 7608 /// * arbitrary interplay between "&" and "*" operators 7609 /// * pointer arithmetic from an address of a stack variable 7610 /// * taking the address of an array element where the array is on the stack 7611 static const Expr *EvalAddr(const Expr *E, 7612 SmallVectorImpl<const DeclRefExpr *> &refVars, 7613 const Decl *ParentDecl) { 7614 if (E->isTypeDependent()) 7615 return nullptr; 7616 7617 // We should only be called for evaluating pointer expressions. 7618 assert((E->getType()->isAnyPointerType() || 7619 E->getType()->isBlockPointerType() || 7620 E->getType()->isObjCQualifiedIdType()) && 7621 "EvalAddr only works on pointers"); 7622 7623 E = E->IgnoreParens(); 7624 7625 // Our "symbolic interpreter" is just a dispatch off the currently 7626 // viewed AST node. We then recursively traverse the AST by calling 7627 // EvalAddr and EvalVal appropriately. 7628 switch (E->getStmtClass()) { 7629 case Stmt::DeclRefExprClass: { 7630 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7631 7632 // If we leave the immediate function, the lifetime isn't about to end. 7633 if (DR->refersToEnclosingVariableOrCapture()) 7634 return nullptr; 7635 7636 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7637 // If this is a reference variable, follow through to the expression that 7638 // it points to. 7639 if (V->hasLocalStorage() && 7640 V->getType()->isReferenceType() && V->hasInit()) { 7641 // Add the reference variable to the "trail". 7642 refVars.push_back(DR); 7643 return EvalAddr(V->getInit(), refVars, ParentDecl); 7644 } 7645 7646 return nullptr; 7647 } 7648 7649 case Stmt::UnaryOperatorClass: { 7650 // The only unary operator that make sense to handle here 7651 // is AddrOf. All others don't make sense as pointers. 7652 const UnaryOperator *U = cast<UnaryOperator>(E); 7653 7654 if (U->getOpcode() == UO_AddrOf) 7655 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7656 return nullptr; 7657 } 7658 7659 case Stmt::BinaryOperatorClass: { 7660 // Handle pointer arithmetic. All other binary operators are not valid 7661 // in this context. 7662 const BinaryOperator *B = cast<BinaryOperator>(E); 7663 BinaryOperatorKind op = B->getOpcode(); 7664 7665 if (op != BO_Add && op != BO_Sub) 7666 return nullptr; 7667 7668 const Expr *Base = B->getLHS(); 7669 7670 // Determine which argument is the real pointer base. It could be 7671 // the RHS argument instead of the LHS. 7672 if (!Base->getType()->isPointerType()) 7673 Base = B->getRHS(); 7674 7675 assert(Base->getType()->isPointerType()); 7676 return EvalAddr(Base, refVars, ParentDecl); 7677 } 7678 7679 // For conditional operators we need to see if either the LHS or RHS are 7680 // valid DeclRefExpr*s. If one of them is valid, we return it. 7681 case Stmt::ConditionalOperatorClass: { 7682 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7683 7684 // Handle the GNU extension for missing LHS. 7685 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7686 if (const Expr *LHSExpr = C->getLHS()) { 7687 // In C++, we can have a throw-expression, which has 'void' type. 7688 if (!LHSExpr->getType()->isVoidType()) 7689 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7690 return LHS; 7691 } 7692 7693 // In C++, we can have a throw-expression, which has 'void' type. 7694 if (C->getRHS()->getType()->isVoidType()) 7695 return nullptr; 7696 7697 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7698 } 7699 7700 case Stmt::BlockExprClass: 7701 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7702 return E; // local block. 7703 return nullptr; 7704 7705 case Stmt::AddrLabelExprClass: 7706 return E; // address of label. 7707 7708 case Stmt::ExprWithCleanupsClass: 7709 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7710 ParentDecl); 7711 7712 // For casts, we need to handle conversions from arrays to 7713 // pointer values, and pointer-to-pointer conversions. 7714 case Stmt::ImplicitCastExprClass: 7715 case Stmt::CStyleCastExprClass: 7716 case Stmt::CXXFunctionalCastExprClass: 7717 case Stmt::ObjCBridgedCastExprClass: 7718 case Stmt::CXXStaticCastExprClass: 7719 case Stmt::CXXDynamicCastExprClass: 7720 case Stmt::CXXConstCastExprClass: 7721 case Stmt::CXXReinterpretCastExprClass: { 7722 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7723 switch (cast<CastExpr>(E)->getCastKind()) { 7724 case CK_LValueToRValue: 7725 case CK_NoOp: 7726 case CK_BaseToDerived: 7727 case CK_DerivedToBase: 7728 case CK_UncheckedDerivedToBase: 7729 case CK_Dynamic: 7730 case CK_CPointerToObjCPointerCast: 7731 case CK_BlockPointerToObjCPointerCast: 7732 case CK_AnyPointerToBlockPointerCast: 7733 return EvalAddr(SubExpr, refVars, ParentDecl); 7734 7735 case CK_ArrayToPointerDecay: 7736 return EvalVal(SubExpr, refVars, ParentDecl); 7737 7738 case CK_BitCast: 7739 if (SubExpr->getType()->isAnyPointerType() || 7740 SubExpr->getType()->isBlockPointerType() || 7741 SubExpr->getType()->isObjCQualifiedIdType()) 7742 return EvalAddr(SubExpr, refVars, ParentDecl); 7743 else 7744 return nullptr; 7745 7746 default: 7747 return nullptr; 7748 } 7749 } 7750 7751 case Stmt::MaterializeTemporaryExprClass: 7752 if (const Expr *Result = 7753 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7754 refVars, ParentDecl)) 7755 return Result; 7756 return E; 7757 7758 // Everything else: we simply don't reason about them. 7759 default: 7760 return nullptr; 7761 } 7762 } 7763 7764 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7765 /// See the comments for EvalAddr for more details. 7766 static const Expr *EvalVal(const Expr *E, 7767 SmallVectorImpl<const DeclRefExpr *> &refVars, 7768 const Decl *ParentDecl) { 7769 do { 7770 // We should only be called for evaluating non-pointer expressions, or 7771 // expressions with a pointer type that are not used as references but 7772 // instead 7773 // are l-values (e.g., DeclRefExpr with a pointer type). 7774 7775 // Our "symbolic interpreter" is just a dispatch off the currently 7776 // viewed AST node. We then recursively traverse the AST by calling 7777 // EvalAddr and EvalVal appropriately. 7778 7779 E = E->IgnoreParens(); 7780 switch (E->getStmtClass()) { 7781 case Stmt::ImplicitCastExprClass: { 7782 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7783 if (IE->getValueKind() == VK_LValue) { 7784 E = IE->getSubExpr(); 7785 continue; 7786 } 7787 return nullptr; 7788 } 7789 7790 case Stmt::ExprWithCleanupsClass: 7791 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7792 ParentDecl); 7793 7794 case Stmt::DeclRefExprClass: { 7795 // When we hit a DeclRefExpr we are looking at code that refers to a 7796 // variable's name. If it's not a reference variable we check if it has 7797 // local storage within the function, and if so, return the expression. 7798 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7799 7800 // If we leave the immediate function, the lifetime isn't about to end. 7801 if (DR->refersToEnclosingVariableOrCapture()) 7802 return nullptr; 7803 7804 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7805 // Check if it refers to itself, e.g. "int& i = i;". 7806 if (V == ParentDecl) 7807 return DR; 7808 7809 if (V->hasLocalStorage()) { 7810 if (!V->getType()->isReferenceType()) 7811 return DR; 7812 7813 // Reference variable, follow through to the expression that 7814 // it points to. 7815 if (V->hasInit()) { 7816 // Add the reference variable to the "trail". 7817 refVars.push_back(DR); 7818 return EvalVal(V->getInit(), refVars, V); 7819 } 7820 } 7821 } 7822 7823 return nullptr; 7824 } 7825 7826 case Stmt::UnaryOperatorClass: { 7827 // The only unary operator that make sense to handle here 7828 // is Deref. All others don't resolve to a "name." This includes 7829 // handling all sorts of rvalues passed to a unary operator. 7830 const UnaryOperator *U = cast<UnaryOperator>(E); 7831 7832 if (U->getOpcode() == UO_Deref) 7833 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7834 7835 return nullptr; 7836 } 7837 7838 case Stmt::ArraySubscriptExprClass: { 7839 // Array subscripts are potential references to data on the stack. We 7840 // retrieve the DeclRefExpr* for the array variable if it indeed 7841 // has local storage. 7842 const auto *ASE = cast<ArraySubscriptExpr>(E); 7843 if (ASE->isTypeDependent()) 7844 return nullptr; 7845 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7846 } 7847 7848 case Stmt::OMPArraySectionExprClass: { 7849 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7850 ParentDecl); 7851 } 7852 7853 case Stmt::ConditionalOperatorClass: { 7854 // For conditional operators we need to see if either the LHS or RHS are 7855 // non-NULL Expr's. If one is non-NULL, we return it. 7856 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7857 7858 // Handle the GNU extension for missing LHS. 7859 if (const Expr *LHSExpr = C->getLHS()) { 7860 // In C++, we can have a throw-expression, which has 'void' type. 7861 if (!LHSExpr->getType()->isVoidType()) 7862 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 7863 return LHS; 7864 } 7865 7866 // In C++, we can have a throw-expression, which has 'void' type. 7867 if (C->getRHS()->getType()->isVoidType()) 7868 return nullptr; 7869 7870 return EvalVal(C->getRHS(), refVars, ParentDecl); 7871 } 7872 7873 // Accesses to members are potential references to data on the stack. 7874 case Stmt::MemberExprClass: { 7875 const MemberExpr *M = cast<MemberExpr>(E); 7876 7877 // Check for indirect access. We only want direct field accesses. 7878 if (M->isArrow()) 7879 return nullptr; 7880 7881 // Check whether the member type is itself a reference, in which case 7882 // we're not going to refer to the member, but to what the member refers 7883 // to. 7884 if (M->getMemberDecl()->getType()->isReferenceType()) 7885 return nullptr; 7886 7887 return EvalVal(M->getBase(), refVars, ParentDecl); 7888 } 7889 7890 case Stmt::MaterializeTemporaryExprClass: 7891 if (const Expr *Result = 7892 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7893 refVars, ParentDecl)) 7894 return Result; 7895 return E; 7896 7897 default: 7898 // Check that we don't return or take the address of a reference to a 7899 // temporary. This is only useful in C++. 7900 if (!E->isTypeDependent() && E->isRValue()) 7901 return E; 7902 7903 // Everything else: we simply don't reason about them. 7904 return nullptr; 7905 } 7906 } while (true); 7907 } 7908 7909 void 7910 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 7911 SourceLocation ReturnLoc, 7912 bool isObjCMethod, 7913 const AttrVec *Attrs, 7914 const FunctionDecl *FD) { 7915 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 7916 7917 // Check if the return value is null but should not be. 7918 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 7919 (!isObjCMethod && isNonNullType(Context, lhsType))) && 7920 CheckNonNullExpr(*this, RetValExp)) 7921 Diag(ReturnLoc, diag::warn_null_ret) 7922 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 7923 7924 // C++11 [basic.stc.dynamic.allocation]p4: 7925 // If an allocation function declared with a non-throwing 7926 // exception-specification fails to allocate storage, it shall return 7927 // a null pointer. Any other allocation function that fails to allocate 7928 // storage shall indicate failure only by throwing an exception [...] 7929 if (FD) { 7930 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 7931 if (Op == OO_New || Op == OO_Array_New) { 7932 const FunctionProtoType *Proto 7933 = FD->getType()->castAs<FunctionProtoType>(); 7934 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 7935 CheckNonNullExpr(*this, RetValExp)) 7936 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 7937 << FD << getLangOpts().CPlusPlus11; 7938 } 7939 } 7940 } 7941 7942 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 7943 7944 /// Check for comparisons of floating point operands using != and ==. 7945 /// Issue a warning if these are no self-comparisons, as they are not likely 7946 /// to do what the programmer intended. 7947 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 7948 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 7949 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 7950 7951 // Special case: check for x == x (which is OK). 7952 // Do not emit warnings for such cases. 7953 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 7954 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 7955 if (DRL->getDecl() == DRR->getDecl()) 7956 return; 7957 7958 // Special case: check for comparisons against literals that can be exactly 7959 // represented by APFloat. In such cases, do not emit a warning. This 7960 // is a heuristic: often comparison against such literals are used to 7961 // detect if a value in a variable has not changed. This clearly can 7962 // lead to false negatives. 7963 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 7964 if (FLL->isExact()) 7965 return; 7966 } else 7967 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 7968 if (FLR->isExact()) 7969 return; 7970 7971 // Check for comparisons with builtin types. 7972 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 7973 if (CL->getBuiltinCallee()) 7974 return; 7975 7976 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 7977 if (CR->getBuiltinCallee()) 7978 return; 7979 7980 // Emit the diagnostic. 7981 Diag(Loc, diag::warn_floatingpoint_eq) 7982 << LHS->getSourceRange() << RHS->getSourceRange(); 7983 } 7984 7985 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 7986 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 7987 7988 namespace { 7989 7990 /// Structure recording the 'active' range of an integer-valued 7991 /// expression. 7992 struct IntRange { 7993 /// The number of bits active in the int. 7994 unsigned Width; 7995 7996 /// True if the int is known not to have negative values. 7997 bool NonNegative; 7998 7999 IntRange(unsigned Width, bool NonNegative) 8000 : Width(Width), NonNegative(NonNegative) 8001 {} 8002 8003 /// Returns the range of the bool type. 8004 static IntRange forBoolType() { 8005 return IntRange(1, true); 8006 } 8007 8008 /// Returns the range of an opaque value of the given integral type. 8009 static IntRange forValueOfType(ASTContext &C, QualType T) { 8010 return forValueOfCanonicalType(C, 8011 T->getCanonicalTypeInternal().getTypePtr()); 8012 } 8013 8014 /// Returns the range of an opaque value of a canonical integral type. 8015 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8016 assert(T->isCanonicalUnqualified()); 8017 8018 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8019 T = VT->getElementType().getTypePtr(); 8020 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8021 T = CT->getElementType().getTypePtr(); 8022 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8023 T = AT->getValueType().getTypePtr(); 8024 8025 // For enum types, use the known bit width of the enumerators. 8026 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8027 EnumDecl *Enum = ET->getDecl(); 8028 if (!Enum->isCompleteDefinition()) 8029 return IntRange(C.getIntWidth(QualType(T, 0)), false); 8030 8031 unsigned NumPositive = Enum->getNumPositiveBits(); 8032 unsigned NumNegative = Enum->getNumNegativeBits(); 8033 8034 if (NumNegative == 0) 8035 return IntRange(NumPositive, true/*NonNegative*/); 8036 else 8037 return IntRange(std::max(NumPositive + 1, NumNegative), 8038 false/*NonNegative*/); 8039 } 8040 8041 const BuiltinType *BT = cast<BuiltinType>(T); 8042 assert(BT->isInteger()); 8043 8044 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8045 } 8046 8047 /// Returns the "target" range of a canonical integral type, i.e. 8048 /// the range of values expressible in the type. 8049 /// 8050 /// This matches forValueOfCanonicalType except that enums have the 8051 /// full range of their type, not the range of their enumerators. 8052 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8053 assert(T->isCanonicalUnqualified()); 8054 8055 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8056 T = VT->getElementType().getTypePtr(); 8057 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8058 T = CT->getElementType().getTypePtr(); 8059 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8060 T = AT->getValueType().getTypePtr(); 8061 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8062 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8063 8064 const BuiltinType *BT = cast<BuiltinType>(T); 8065 assert(BT->isInteger()); 8066 8067 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8068 } 8069 8070 /// Returns the supremum of two ranges: i.e. their conservative merge. 8071 static IntRange join(IntRange L, IntRange R) { 8072 return IntRange(std::max(L.Width, R.Width), 8073 L.NonNegative && R.NonNegative); 8074 } 8075 8076 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8077 static IntRange meet(IntRange L, IntRange R) { 8078 return IntRange(std::min(L.Width, R.Width), 8079 L.NonNegative || R.NonNegative); 8080 } 8081 }; 8082 8083 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 8084 if (value.isSigned() && value.isNegative()) 8085 return IntRange(value.getMinSignedBits(), false); 8086 8087 if (value.getBitWidth() > MaxWidth) 8088 value = value.trunc(MaxWidth); 8089 8090 // isNonNegative() just checks the sign bit without considering 8091 // signedness. 8092 return IntRange(value.getActiveBits(), true); 8093 } 8094 8095 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8096 unsigned MaxWidth) { 8097 if (result.isInt()) 8098 return GetValueRange(C, result.getInt(), MaxWidth); 8099 8100 if (result.isVector()) { 8101 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8102 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8103 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8104 R = IntRange::join(R, El); 8105 } 8106 return R; 8107 } 8108 8109 if (result.isComplexInt()) { 8110 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8111 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8112 return IntRange::join(R, I); 8113 } 8114 8115 // This can happen with lossless casts to intptr_t of "based" lvalues. 8116 // Assume it might use arbitrary bits. 8117 // FIXME: The only reason we need to pass the type in here is to get 8118 // the sign right on this one case. It would be nice if APValue 8119 // preserved this. 8120 assert(result.isLValue() || result.isAddrLabelDiff()); 8121 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8122 } 8123 8124 QualType GetExprType(const Expr *E) { 8125 QualType Ty = E->getType(); 8126 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8127 Ty = AtomicRHS->getValueType(); 8128 return Ty; 8129 } 8130 8131 /// Pseudo-evaluate the given integer expression, estimating the 8132 /// range of values it might take. 8133 /// 8134 /// \param MaxWidth - the width to which the value will be truncated 8135 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8136 E = E->IgnoreParens(); 8137 8138 // Try a full evaluation first. 8139 Expr::EvalResult result; 8140 if (E->EvaluateAsRValue(result, C)) 8141 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8142 8143 // I think we only want to look through implicit casts here; if the 8144 // user has an explicit widening cast, we should treat the value as 8145 // being of the new, wider type. 8146 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8147 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8148 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8149 8150 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8151 8152 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8153 CE->getCastKind() == CK_BooleanToSignedIntegral; 8154 8155 // Assume that non-integer casts can span the full range of the type. 8156 if (!isIntegerCast) 8157 return OutputTypeRange; 8158 8159 IntRange SubRange 8160 = GetExprRange(C, CE->getSubExpr(), 8161 std::min(MaxWidth, OutputTypeRange.Width)); 8162 8163 // Bail out if the subexpr's range is as wide as the cast type. 8164 if (SubRange.Width >= OutputTypeRange.Width) 8165 return OutputTypeRange; 8166 8167 // Otherwise, we take the smaller width, and we're non-negative if 8168 // either the output type or the subexpr is. 8169 return IntRange(SubRange.Width, 8170 SubRange.NonNegative || OutputTypeRange.NonNegative); 8171 } 8172 8173 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8174 // If we can fold the condition, just take that operand. 8175 bool CondResult; 8176 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8177 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8178 : CO->getFalseExpr(), 8179 MaxWidth); 8180 8181 // Otherwise, conservatively merge. 8182 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8183 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8184 return IntRange::join(L, R); 8185 } 8186 8187 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8188 switch (BO->getOpcode()) { 8189 8190 // Boolean-valued operations are single-bit and positive. 8191 case BO_LAnd: 8192 case BO_LOr: 8193 case BO_LT: 8194 case BO_GT: 8195 case BO_LE: 8196 case BO_GE: 8197 case BO_EQ: 8198 case BO_NE: 8199 return IntRange::forBoolType(); 8200 8201 // The type of the assignments is the type of the LHS, so the RHS 8202 // is not necessarily the same type. 8203 case BO_MulAssign: 8204 case BO_DivAssign: 8205 case BO_RemAssign: 8206 case BO_AddAssign: 8207 case BO_SubAssign: 8208 case BO_XorAssign: 8209 case BO_OrAssign: 8210 // TODO: bitfields? 8211 return IntRange::forValueOfType(C, GetExprType(E)); 8212 8213 // Simple assignments just pass through the RHS, which will have 8214 // been coerced to the LHS type. 8215 case BO_Assign: 8216 // TODO: bitfields? 8217 return GetExprRange(C, BO->getRHS(), MaxWidth); 8218 8219 // Operations with opaque sources are black-listed. 8220 case BO_PtrMemD: 8221 case BO_PtrMemI: 8222 return IntRange::forValueOfType(C, GetExprType(E)); 8223 8224 // Bitwise-and uses the *infinum* of the two source ranges. 8225 case BO_And: 8226 case BO_AndAssign: 8227 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8228 GetExprRange(C, BO->getRHS(), MaxWidth)); 8229 8230 // Left shift gets black-listed based on a judgement call. 8231 case BO_Shl: 8232 // ...except that we want to treat '1 << (blah)' as logically 8233 // positive. It's an important idiom. 8234 if (IntegerLiteral *I 8235 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8236 if (I->getValue() == 1) { 8237 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8238 return IntRange(R.Width, /*NonNegative*/ true); 8239 } 8240 } 8241 // fallthrough 8242 8243 case BO_ShlAssign: 8244 return IntRange::forValueOfType(C, GetExprType(E)); 8245 8246 // Right shift by a constant can narrow its left argument. 8247 case BO_Shr: 8248 case BO_ShrAssign: { 8249 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8250 8251 // If the shift amount is a positive constant, drop the width by 8252 // that much. 8253 llvm::APSInt shift; 8254 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8255 shift.isNonNegative()) { 8256 unsigned zext = shift.getZExtValue(); 8257 if (zext >= L.Width) 8258 L.Width = (L.NonNegative ? 0 : 1); 8259 else 8260 L.Width -= zext; 8261 } 8262 8263 return L; 8264 } 8265 8266 // Comma acts as its right operand. 8267 case BO_Comma: 8268 return GetExprRange(C, BO->getRHS(), MaxWidth); 8269 8270 // Black-list pointer subtractions. 8271 case BO_Sub: 8272 if (BO->getLHS()->getType()->isPointerType()) 8273 return IntRange::forValueOfType(C, GetExprType(E)); 8274 break; 8275 8276 // The width of a division result is mostly determined by the size 8277 // of the LHS. 8278 case BO_Div: { 8279 // Don't 'pre-truncate' the operands. 8280 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8281 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8282 8283 // If the divisor is constant, use that. 8284 llvm::APSInt divisor; 8285 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8286 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8287 if (log2 >= L.Width) 8288 L.Width = (L.NonNegative ? 0 : 1); 8289 else 8290 L.Width = std::min(L.Width - log2, MaxWidth); 8291 return L; 8292 } 8293 8294 // Otherwise, just use the LHS's width. 8295 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8296 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8297 } 8298 8299 // The result of a remainder can't be larger than the result of 8300 // either side. 8301 case BO_Rem: { 8302 // Don't 'pre-truncate' the operands. 8303 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8304 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8305 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8306 8307 IntRange meet = IntRange::meet(L, R); 8308 meet.Width = std::min(meet.Width, MaxWidth); 8309 return meet; 8310 } 8311 8312 // The default behavior is okay for these. 8313 case BO_Mul: 8314 case BO_Add: 8315 case BO_Xor: 8316 case BO_Or: 8317 break; 8318 } 8319 8320 // The default case is to treat the operation as if it were closed 8321 // on the narrowest type that encompasses both operands. 8322 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8323 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8324 return IntRange::join(L, R); 8325 } 8326 8327 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8328 switch (UO->getOpcode()) { 8329 // Boolean-valued operations are white-listed. 8330 case UO_LNot: 8331 return IntRange::forBoolType(); 8332 8333 // Operations with opaque sources are black-listed. 8334 case UO_Deref: 8335 case UO_AddrOf: // should be impossible 8336 return IntRange::forValueOfType(C, GetExprType(E)); 8337 8338 default: 8339 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8340 } 8341 } 8342 8343 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8344 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8345 8346 if (const auto *BitField = E->getSourceBitField()) 8347 return IntRange(BitField->getBitWidthValue(C), 8348 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8349 8350 return IntRange::forValueOfType(C, GetExprType(E)); 8351 } 8352 8353 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8354 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8355 } 8356 8357 /// Checks whether the given value, which currently has the given 8358 /// source semantics, has the same value when coerced through the 8359 /// target semantics. 8360 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8361 const llvm::fltSemantics &Src, 8362 const llvm::fltSemantics &Tgt) { 8363 llvm::APFloat truncated = value; 8364 8365 bool ignored; 8366 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8367 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8368 8369 return truncated.bitwiseIsEqual(value); 8370 } 8371 8372 /// Checks whether the given value, which currently has the given 8373 /// source semantics, has the same value when coerced through the 8374 /// target semantics. 8375 /// 8376 /// The value might be a vector of floats (or a complex number). 8377 bool IsSameFloatAfterCast(const APValue &value, 8378 const llvm::fltSemantics &Src, 8379 const llvm::fltSemantics &Tgt) { 8380 if (value.isFloat()) 8381 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8382 8383 if (value.isVector()) { 8384 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8385 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8386 return false; 8387 return true; 8388 } 8389 8390 assert(value.isComplexFloat()); 8391 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8392 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8393 } 8394 8395 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8396 8397 bool IsZero(Sema &S, Expr *E) { 8398 // Suppress cases where we are comparing against an enum constant. 8399 if (const DeclRefExpr *DR = 8400 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8401 if (isa<EnumConstantDecl>(DR->getDecl())) 8402 return false; 8403 8404 // Suppress cases where the '0' value is expanded from a macro. 8405 if (E->getLocStart().isMacroID()) 8406 return false; 8407 8408 llvm::APSInt Value; 8409 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 8410 } 8411 8412 bool HasEnumType(Expr *E) { 8413 // Strip off implicit integral promotions. 8414 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8415 if (ICE->getCastKind() != CK_IntegralCast && 8416 ICE->getCastKind() != CK_NoOp) 8417 break; 8418 E = ICE->getSubExpr(); 8419 } 8420 8421 return E->getType()->isEnumeralType(); 8422 } 8423 8424 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 8425 // Disable warning in template instantiations. 8426 if (S.inTemplateInstantiation()) 8427 return; 8428 8429 BinaryOperatorKind op = E->getOpcode(); 8430 if (E->isValueDependent()) 8431 return; 8432 8433 if (op == BO_LT && IsZero(S, E->getRHS())) { 8434 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8435 << "< 0" << "false" << HasEnumType(E->getLHS()) 8436 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8437 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 8438 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8439 << ">= 0" << "true" << HasEnumType(E->getLHS()) 8440 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8441 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 8442 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8443 << "0 >" << "false" << HasEnumType(E->getRHS()) 8444 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8445 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 8446 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8447 << "0 <=" << "true" << HasEnumType(E->getRHS()) 8448 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8449 } 8450 } 8451 8452 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8453 Expr *Other, const llvm::APSInt &Value, 8454 bool RhsConstant) { 8455 // Disable warning in template instantiations. 8456 if (S.inTemplateInstantiation()) 8457 return; 8458 8459 // TODO: Investigate using GetExprRange() to get tighter bounds 8460 // on the bit ranges. 8461 QualType OtherT = Other->getType(); 8462 if (const auto *AT = OtherT->getAs<AtomicType>()) 8463 OtherT = AT->getValueType(); 8464 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8465 unsigned OtherWidth = OtherRange.Width; 8466 8467 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8468 8469 // 0 values are handled later by CheckTrivialUnsignedComparison(). 8470 if ((Value == 0) && (!OtherIsBooleanType)) 8471 return; 8472 8473 BinaryOperatorKind op = E->getOpcode(); 8474 bool IsTrue = true; 8475 8476 // Used for diagnostic printout. 8477 enum { 8478 LiteralConstant = 0, 8479 CXXBoolLiteralTrue, 8480 CXXBoolLiteralFalse 8481 } LiteralOrBoolConstant = LiteralConstant; 8482 8483 if (!OtherIsBooleanType) { 8484 QualType ConstantT = Constant->getType(); 8485 QualType CommonT = E->getLHS()->getType(); 8486 8487 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8488 return; 8489 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8490 "comparison with non-integer type"); 8491 8492 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8493 bool CommonSigned = CommonT->isSignedIntegerType(); 8494 8495 bool EqualityOnly = false; 8496 8497 if (CommonSigned) { 8498 // The common type is signed, therefore no signed to unsigned conversion. 8499 if (!OtherRange.NonNegative) { 8500 // Check that the constant is representable in type OtherT. 8501 if (ConstantSigned) { 8502 if (OtherWidth >= Value.getMinSignedBits()) 8503 return; 8504 } else { // !ConstantSigned 8505 if (OtherWidth >= Value.getActiveBits() + 1) 8506 return; 8507 } 8508 } else { // !OtherSigned 8509 // Check that the constant is representable in type OtherT. 8510 // Negative values are out of range. 8511 if (ConstantSigned) { 8512 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8513 return; 8514 } else { // !ConstantSigned 8515 if (OtherWidth >= Value.getActiveBits()) 8516 return; 8517 } 8518 } 8519 } else { // !CommonSigned 8520 if (OtherRange.NonNegative) { 8521 if (OtherWidth >= Value.getActiveBits()) 8522 return; 8523 } else { // OtherSigned 8524 assert(!ConstantSigned && 8525 "Two signed types converted to unsigned types."); 8526 // Check to see if the constant is representable in OtherT. 8527 if (OtherWidth > Value.getActiveBits()) 8528 return; 8529 // Check to see if the constant is equivalent to a negative value 8530 // cast to CommonT. 8531 if (S.Context.getIntWidth(ConstantT) == 8532 S.Context.getIntWidth(CommonT) && 8533 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8534 return; 8535 // The constant value rests between values that OtherT can represent 8536 // after conversion. Relational comparison still works, but equality 8537 // comparisons will be tautological. 8538 EqualityOnly = true; 8539 } 8540 } 8541 8542 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8543 8544 if (op == BO_EQ || op == BO_NE) { 8545 IsTrue = op == BO_NE; 8546 } else if (EqualityOnly) { 8547 return; 8548 } else if (RhsConstant) { 8549 if (op == BO_GT || op == BO_GE) 8550 IsTrue = !PositiveConstant; 8551 else // op == BO_LT || op == BO_LE 8552 IsTrue = PositiveConstant; 8553 } else { 8554 if (op == BO_LT || op == BO_LE) 8555 IsTrue = !PositiveConstant; 8556 else // op == BO_GT || op == BO_GE 8557 IsTrue = PositiveConstant; 8558 } 8559 } else { 8560 // Other isKnownToHaveBooleanValue 8561 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8562 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8563 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8564 8565 static const struct LinkedConditions { 8566 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8567 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8568 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8569 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8570 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8571 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8572 8573 } TruthTable = { 8574 // Constant on LHS. | Constant on RHS. | 8575 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8576 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8577 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8578 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8579 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8580 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8581 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8582 }; 8583 8584 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8585 8586 enum ConstantValue ConstVal = Zero; 8587 if (Value.isUnsigned() || Value.isNonNegative()) { 8588 if (Value == 0) { 8589 LiteralOrBoolConstant = 8590 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8591 ConstVal = Zero; 8592 } else if (Value == 1) { 8593 LiteralOrBoolConstant = 8594 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8595 ConstVal = One; 8596 } else { 8597 LiteralOrBoolConstant = LiteralConstant; 8598 ConstVal = GT_One; 8599 } 8600 } else { 8601 ConstVal = LT_Zero; 8602 } 8603 8604 CompareBoolWithConstantResult CmpRes; 8605 8606 switch (op) { 8607 case BO_LT: 8608 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8609 break; 8610 case BO_GT: 8611 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8612 break; 8613 case BO_LE: 8614 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8615 break; 8616 case BO_GE: 8617 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8618 break; 8619 case BO_EQ: 8620 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8621 break; 8622 case BO_NE: 8623 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8624 break; 8625 default: 8626 CmpRes = Unkwn; 8627 break; 8628 } 8629 8630 if (CmpRes == AFals) { 8631 IsTrue = false; 8632 } else if (CmpRes == ATrue) { 8633 IsTrue = true; 8634 } else { 8635 return; 8636 } 8637 } 8638 8639 // If this is a comparison to an enum constant, include that 8640 // constant in the diagnostic. 8641 const EnumConstantDecl *ED = nullptr; 8642 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8643 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8644 8645 SmallString<64> PrettySourceValue; 8646 llvm::raw_svector_ostream OS(PrettySourceValue); 8647 if (ED) 8648 OS << '\'' << *ED << "' (" << Value << ")"; 8649 else 8650 OS << Value; 8651 8652 S.DiagRuntimeBehavior( 8653 E->getOperatorLoc(), E, 8654 S.PDiag(diag::warn_out_of_range_compare) 8655 << OS.str() << LiteralOrBoolConstant 8656 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8657 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8658 } 8659 8660 /// Analyze the operands of the given comparison. Implements the 8661 /// fallback case from AnalyzeComparison. 8662 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8663 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8664 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8665 } 8666 8667 /// \brief Implements -Wsign-compare. 8668 /// 8669 /// \param E the binary operator to check for warnings 8670 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8671 // The type the comparison is being performed in. 8672 QualType T = E->getLHS()->getType(); 8673 8674 // Only analyze comparison operators where both sides have been converted to 8675 // the same type. 8676 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8677 return AnalyzeImpConvsInComparison(S, E); 8678 8679 // Don't analyze value-dependent comparisons directly. 8680 if (E->isValueDependent()) 8681 return AnalyzeImpConvsInComparison(S, E); 8682 8683 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8684 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8685 8686 bool IsComparisonConstant = false; 8687 8688 // Check whether an integer constant comparison results in a value 8689 // of 'true' or 'false'. 8690 if (T->isIntegralType(S.Context)) { 8691 llvm::APSInt RHSValue; 8692 bool IsRHSIntegralLiteral = 8693 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8694 llvm::APSInt LHSValue; 8695 bool IsLHSIntegralLiteral = 8696 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8697 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8698 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8699 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8700 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8701 else 8702 IsComparisonConstant = 8703 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8704 } else if (!T->hasUnsignedIntegerRepresentation()) 8705 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8706 8707 // We don't do anything special if this isn't an unsigned integral 8708 // comparison: we're only interested in integral comparisons, and 8709 // signed comparisons only happen in cases we don't care to warn about. 8710 // 8711 // We also don't care about value-dependent expressions or expressions 8712 // whose result is a constant. 8713 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 8714 return AnalyzeImpConvsInComparison(S, E); 8715 8716 // Check to see if one of the (unmodified) operands is of different 8717 // signedness. 8718 Expr *signedOperand, *unsignedOperand; 8719 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8720 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8721 "unsigned comparison between two signed integer expressions?"); 8722 signedOperand = LHS; 8723 unsignedOperand = RHS; 8724 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8725 signedOperand = RHS; 8726 unsignedOperand = LHS; 8727 } else { 8728 CheckTrivialUnsignedComparison(S, E); 8729 return AnalyzeImpConvsInComparison(S, E); 8730 } 8731 8732 // Otherwise, calculate the effective range of the signed operand. 8733 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8734 8735 // Go ahead and analyze implicit conversions in the operands. Note 8736 // that we skip the implicit conversions on both sides. 8737 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8738 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8739 8740 // If the signed range is non-negative, -Wsign-compare won't fire, 8741 // but we should still check for comparisons which are always true 8742 // or false. 8743 if (signedRange.NonNegative) 8744 return CheckTrivialUnsignedComparison(S, E); 8745 8746 // For (in)equality comparisons, if the unsigned operand is a 8747 // constant which cannot collide with a overflowed signed operand, 8748 // then reinterpreting the signed operand as unsigned will not 8749 // change the result of the comparison. 8750 if (E->isEqualityOp()) { 8751 unsigned comparisonWidth = S.Context.getIntWidth(T); 8752 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8753 8754 // We should never be unable to prove that the unsigned operand is 8755 // non-negative. 8756 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8757 8758 if (unsignedRange.Width < comparisonWidth) 8759 return; 8760 } 8761 8762 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8763 S.PDiag(diag::warn_mixed_sign_comparison) 8764 << LHS->getType() << RHS->getType() 8765 << LHS->getSourceRange() << RHS->getSourceRange()); 8766 } 8767 8768 /// Analyzes an attempt to assign the given value to a bitfield. 8769 /// 8770 /// Returns true if there was something fishy about the attempt. 8771 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8772 SourceLocation InitLoc) { 8773 assert(Bitfield->isBitField()); 8774 if (Bitfield->isInvalidDecl()) 8775 return false; 8776 8777 // White-list bool bitfields. 8778 QualType BitfieldType = Bitfield->getType(); 8779 if (BitfieldType->isBooleanType()) 8780 return false; 8781 8782 if (BitfieldType->isEnumeralType()) { 8783 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 8784 // If the underlying enum type was not explicitly specified as an unsigned 8785 // type and the enum contain only positive values, MSVC++ will cause an 8786 // inconsistency by storing this as a signed type. 8787 if (S.getLangOpts().CPlusPlus11 && 8788 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 8789 BitfieldEnumDecl->getNumPositiveBits() > 0 && 8790 BitfieldEnumDecl->getNumNegativeBits() == 0) { 8791 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 8792 << BitfieldEnumDecl->getNameAsString(); 8793 } 8794 } 8795 8796 if (Bitfield->getType()->isBooleanType()) 8797 return false; 8798 8799 // Ignore value- or type-dependent expressions. 8800 if (Bitfield->getBitWidth()->isValueDependent() || 8801 Bitfield->getBitWidth()->isTypeDependent() || 8802 Init->isValueDependent() || 8803 Init->isTypeDependent()) 8804 return false; 8805 8806 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8807 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8808 8809 llvm::APSInt Value; 8810 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 8811 Expr::SE_AllowSideEffects)) { 8812 // The RHS is not constant. If the RHS has an enum type, make sure the 8813 // bitfield is wide enough to hold all the values of the enum without 8814 // truncation. 8815 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 8816 EnumDecl *ED = EnumTy->getDecl(); 8817 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 8818 8819 // Enum types are implicitly signed on Windows, so check if there are any 8820 // negative enumerators to see if the enum was intended to be signed or 8821 // not. 8822 bool SignedEnum = ED->getNumNegativeBits() > 0; 8823 8824 // Check for surprising sign changes when assigning enum values to a 8825 // bitfield of different signedness. If the bitfield is signed and we 8826 // have exactly the right number of bits to store this unsigned enum, 8827 // suggest changing the enum to an unsigned type. This typically happens 8828 // on Windows where unfixed enums always use an underlying type of 'int'. 8829 unsigned DiagID = 0; 8830 if (SignedEnum && !SignedBitfield) { 8831 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 8832 } else if (SignedBitfield && !SignedEnum && 8833 ED->getNumPositiveBits() == FieldWidth) { 8834 DiagID = diag::warn_signed_bitfield_enum_conversion; 8835 } 8836 8837 if (DiagID) { 8838 S.Diag(InitLoc, DiagID) << Bitfield << ED; 8839 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 8840 SourceRange TypeRange = 8841 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 8842 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 8843 << SignedEnum << TypeRange; 8844 } 8845 8846 // Compute the required bitwidth. If the enum has negative values, we need 8847 // one more bit than the normal number of positive bits to represent the 8848 // sign bit. 8849 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 8850 ED->getNumNegativeBits()) 8851 : ED->getNumPositiveBits(); 8852 8853 // Check the bitwidth. 8854 if (BitsNeeded > FieldWidth) { 8855 Expr *WidthExpr = Bitfield->getBitWidth(); 8856 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 8857 << Bitfield << ED; 8858 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 8859 << BitsNeeded << ED << WidthExpr->getSourceRange(); 8860 } 8861 } 8862 8863 return false; 8864 } 8865 8866 unsigned OriginalWidth = Value.getBitWidth(); 8867 8868 if (!Value.isSigned() || Value.isNegative()) 8869 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 8870 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 8871 OriginalWidth = Value.getMinSignedBits(); 8872 8873 if (OriginalWidth <= FieldWidth) 8874 return false; 8875 8876 // Compute the value which the bitfield will contain. 8877 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 8878 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 8879 8880 // Check whether the stored value is equal to the original value. 8881 TruncatedValue = TruncatedValue.extend(OriginalWidth); 8882 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 8883 return false; 8884 8885 // Special-case bitfields of width 1: booleans are naturally 0/1, and 8886 // therefore don't strictly fit into a signed bitfield of width 1. 8887 if (FieldWidth == 1 && Value == 1) 8888 return false; 8889 8890 std::string PrettyValue = Value.toString(10); 8891 std::string PrettyTrunc = TruncatedValue.toString(10); 8892 8893 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 8894 << PrettyValue << PrettyTrunc << OriginalInit->getType() 8895 << Init->getSourceRange(); 8896 8897 return true; 8898 } 8899 8900 /// Analyze the given simple or compound assignment for warning-worthy 8901 /// operations. 8902 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 8903 // Just recurse on the LHS. 8904 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8905 8906 // We want to recurse on the RHS as normal unless we're assigning to 8907 // a bitfield. 8908 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 8909 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 8910 E->getOperatorLoc())) { 8911 // Recurse, ignoring any implicit conversions on the RHS. 8912 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 8913 E->getOperatorLoc()); 8914 } 8915 } 8916 8917 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8918 } 8919 8920 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8921 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 8922 SourceLocation CContext, unsigned diag, 8923 bool pruneControlFlow = false) { 8924 if (pruneControlFlow) { 8925 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8926 S.PDiag(diag) 8927 << SourceType << T << E->getSourceRange() 8928 << SourceRange(CContext)); 8929 return; 8930 } 8931 S.Diag(E->getExprLoc(), diag) 8932 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 8933 } 8934 8935 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8936 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 8937 unsigned diag, bool pruneControlFlow = false) { 8938 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 8939 } 8940 8941 8942 /// Diagnose an implicit cast from a floating point value to an integer value. 8943 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 8944 8945 SourceLocation CContext) { 8946 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 8947 const bool PruneWarnings = S.inTemplateInstantiation(); 8948 8949 Expr *InnerE = E->IgnoreParenImpCasts(); 8950 // We also want to warn on, e.g., "int i = -1.234" 8951 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 8952 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 8953 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 8954 8955 const bool IsLiteral = 8956 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 8957 8958 llvm::APFloat Value(0.0); 8959 bool IsConstant = 8960 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 8961 if (!IsConstant) { 8962 return DiagnoseImpCast(S, E, T, CContext, 8963 diag::warn_impcast_float_integer, PruneWarnings); 8964 } 8965 8966 bool isExact = false; 8967 8968 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 8969 T->hasUnsignedIntegerRepresentation()); 8970 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 8971 &isExact) == llvm::APFloat::opOK && 8972 isExact) { 8973 if (IsLiteral) return; 8974 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 8975 PruneWarnings); 8976 } 8977 8978 unsigned DiagID = 0; 8979 if (IsLiteral) { 8980 // Warn on floating point literal to integer. 8981 DiagID = diag::warn_impcast_literal_float_to_integer; 8982 } else if (IntegerValue == 0) { 8983 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 8984 return DiagnoseImpCast(S, E, T, CContext, 8985 diag::warn_impcast_float_integer, PruneWarnings); 8986 } 8987 // Warn on non-zero to zero conversion. 8988 DiagID = diag::warn_impcast_float_to_integer_zero; 8989 } else { 8990 if (IntegerValue.isUnsigned()) { 8991 if (!IntegerValue.isMaxValue()) { 8992 return DiagnoseImpCast(S, E, T, CContext, 8993 diag::warn_impcast_float_integer, PruneWarnings); 8994 } 8995 } else { // IntegerValue.isSigned() 8996 if (!IntegerValue.isMaxSignedValue() && 8997 !IntegerValue.isMinSignedValue()) { 8998 return DiagnoseImpCast(S, E, T, CContext, 8999 diag::warn_impcast_float_integer, PruneWarnings); 9000 } 9001 } 9002 // Warn on evaluatable floating point expression to integer conversion. 9003 DiagID = diag::warn_impcast_float_to_integer; 9004 } 9005 9006 // FIXME: Force the precision of the source value down so we don't print 9007 // digits which are usually useless (we don't really care here if we 9008 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9009 // would automatically print the shortest representation, but it's a bit 9010 // tricky to implement. 9011 SmallString<16> PrettySourceValue; 9012 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9013 precision = (precision * 59 + 195) / 196; 9014 Value.toString(PrettySourceValue, precision); 9015 9016 SmallString<16> PrettyTargetValue; 9017 if (IsBool) 9018 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9019 else 9020 IntegerValue.toString(PrettyTargetValue); 9021 9022 if (PruneWarnings) { 9023 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9024 S.PDiag(DiagID) 9025 << E->getType() << T.getUnqualifiedType() 9026 << PrettySourceValue << PrettyTargetValue 9027 << E->getSourceRange() << SourceRange(CContext)); 9028 } else { 9029 S.Diag(E->getExprLoc(), DiagID) 9030 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9031 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9032 } 9033 } 9034 9035 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 9036 if (!Range.Width) return "0"; 9037 9038 llvm::APSInt ValueInRange = Value; 9039 ValueInRange.setIsSigned(!Range.NonNegative); 9040 ValueInRange = ValueInRange.trunc(Range.Width); 9041 return ValueInRange.toString(10); 9042 } 9043 9044 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9045 if (!isa<ImplicitCastExpr>(Ex)) 9046 return false; 9047 9048 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9049 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9050 const Type *Source = 9051 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9052 if (Target->isDependentType()) 9053 return false; 9054 9055 const BuiltinType *FloatCandidateBT = 9056 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9057 const Type *BoolCandidateType = ToBool ? Target : Source; 9058 9059 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9060 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9061 } 9062 9063 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9064 SourceLocation CC) { 9065 unsigned NumArgs = TheCall->getNumArgs(); 9066 for (unsigned i = 0; i < NumArgs; ++i) { 9067 Expr *CurrA = TheCall->getArg(i); 9068 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9069 continue; 9070 9071 bool IsSwapped = ((i > 0) && 9072 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9073 IsSwapped |= ((i < (NumArgs - 1)) && 9074 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9075 if (IsSwapped) { 9076 // Warn on this floating-point to bool conversion. 9077 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9078 CurrA->getType(), CC, 9079 diag::warn_impcast_floating_point_to_bool); 9080 } 9081 } 9082 } 9083 9084 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 9085 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9086 E->getExprLoc())) 9087 return; 9088 9089 // Don't warn on functions which have return type nullptr_t. 9090 if (isa<CallExpr>(E)) 9091 return; 9092 9093 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9094 const Expr::NullPointerConstantKind NullKind = 9095 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9096 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9097 return; 9098 9099 // Return if target type is a safe conversion. 9100 if (T->isAnyPointerType() || T->isBlockPointerType() || 9101 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9102 return; 9103 9104 SourceLocation Loc = E->getSourceRange().getBegin(); 9105 9106 // Venture through the macro stacks to get to the source of macro arguments. 9107 // The new location is a better location than the complete location that was 9108 // passed in. 9109 while (S.SourceMgr.isMacroArgExpansion(Loc)) 9110 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 9111 9112 while (S.SourceMgr.isMacroArgExpansion(CC)) 9113 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 9114 9115 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9116 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9117 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9118 Loc, S.SourceMgr, S.getLangOpts()); 9119 if (MacroName == "NULL") 9120 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 9121 } 9122 9123 // Only warn if the null and context location are in the same macro expansion. 9124 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9125 return; 9126 9127 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9128 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 9129 << FixItHint::CreateReplacement(Loc, 9130 S.getFixItZeroLiteralForType(T, Loc)); 9131 } 9132 9133 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9134 ObjCArrayLiteral *ArrayLiteral); 9135 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9136 ObjCDictionaryLiteral *DictionaryLiteral); 9137 9138 /// Check a single element within a collection literal against the 9139 /// target element type. 9140 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 9141 Expr *Element, unsigned ElementKind) { 9142 // Skip a bitcast to 'id' or qualified 'id'. 9143 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9144 if (ICE->getCastKind() == CK_BitCast && 9145 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9146 Element = ICE->getSubExpr(); 9147 } 9148 9149 QualType ElementType = Element->getType(); 9150 ExprResult ElementResult(Element); 9151 if (ElementType->getAs<ObjCObjectPointerType>() && 9152 S.CheckSingleAssignmentConstraints(TargetElementType, 9153 ElementResult, 9154 false, false) 9155 != Sema::Compatible) { 9156 S.Diag(Element->getLocStart(), 9157 diag::warn_objc_collection_literal_element) 9158 << ElementType << ElementKind << TargetElementType 9159 << Element->getSourceRange(); 9160 } 9161 9162 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9163 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9164 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9165 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9166 } 9167 9168 /// Check an Objective-C array literal being converted to the given 9169 /// target type. 9170 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9171 ObjCArrayLiteral *ArrayLiteral) { 9172 if (!S.NSArrayDecl) 9173 return; 9174 9175 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9176 if (!TargetObjCPtr) 9177 return; 9178 9179 if (TargetObjCPtr->isUnspecialized() || 9180 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9181 != S.NSArrayDecl->getCanonicalDecl()) 9182 return; 9183 9184 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9185 if (TypeArgs.size() != 1) 9186 return; 9187 9188 QualType TargetElementType = TypeArgs[0]; 9189 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9190 checkObjCCollectionLiteralElement(S, TargetElementType, 9191 ArrayLiteral->getElement(I), 9192 0); 9193 } 9194 } 9195 9196 /// Check an Objective-C dictionary literal being converted to the given 9197 /// target type. 9198 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9199 ObjCDictionaryLiteral *DictionaryLiteral) { 9200 if (!S.NSDictionaryDecl) 9201 return; 9202 9203 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9204 if (!TargetObjCPtr) 9205 return; 9206 9207 if (TargetObjCPtr->isUnspecialized() || 9208 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9209 != S.NSDictionaryDecl->getCanonicalDecl()) 9210 return; 9211 9212 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9213 if (TypeArgs.size() != 2) 9214 return; 9215 9216 QualType TargetKeyType = TypeArgs[0]; 9217 QualType TargetObjectType = TypeArgs[1]; 9218 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9219 auto Element = DictionaryLiteral->getKeyValueElement(I); 9220 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9221 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9222 } 9223 } 9224 9225 // Helper function to filter out cases for constant width constant conversion. 9226 // Don't warn on char array initialization or for non-decimal values. 9227 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9228 SourceLocation CC) { 9229 // If initializing from a constant, and the constant starts with '0', 9230 // then it is a binary, octal, or hexadecimal. Allow these constants 9231 // to fill all the bits, even if there is a sign change. 9232 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9233 const char FirstLiteralCharacter = 9234 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9235 if (FirstLiteralCharacter == '0') 9236 return false; 9237 } 9238 9239 // If the CC location points to a '{', and the type is char, then assume 9240 // assume it is an array initialization. 9241 if (CC.isValid() && T->isCharType()) { 9242 const char FirstContextCharacter = 9243 S.getSourceManager().getCharacterData(CC)[0]; 9244 if (FirstContextCharacter == '{') 9245 return false; 9246 } 9247 9248 return true; 9249 } 9250 9251 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 9252 SourceLocation CC, bool *ICContext = nullptr) { 9253 if (E->isTypeDependent() || E->isValueDependent()) return; 9254 9255 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9256 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9257 if (Source == Target) return; 9258 if (Target->isDependentType()) return; 9259 9260 // If the conversion context location is invalid don't complain. We also 9261 // don't want to emit a warning if the issue occurs from the expansion of 9262 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9263 // delay this check as long as possible. Once we detect we are in that 9264 // scenario, we just return. 9265 if (CC.isInvalid()) 9266 return; 9267 9268 // Diagnose implicit casts to bool. 9269 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9270 if (isa<StringLiteral>(E)) 9271 // Warn on string literal to bool. Checks for string literals in logical 9272 // and expressions, for instance, assert(0 && "error here"), are 9273 // prevented by a check in AnalyzeImplicitConversions(). 9274 return DiagnoseImpCast(S, E, T, CC, 9275 diag::warn_impcast_string_literal_to_bool); 9276 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9277 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9278 // This covers the literal expressions that evaluate to Objective-C 9279 // objects. 9280 return DiagnoseImpCast(S, E, T, CC, 9281 diag::warn_impcast_objective_c_literal_to_bool); 9282 } 9283 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9284 // Warn on pointer to bool conversion that is always true. 9285 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9286 SourceRange(CC)); 9287 } 9288 } 9289 9290 // Check implicit casts from Objective-C collection literals to specialized 9291 // collection types, e.g., NSArray<NSString *> *. 9292 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9293 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9294 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9295 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9296 9297 // Strip vector types. 9298 if (isa<VectorType>(Source)) { 9299 if (!isa<VectorType>(Target)) { 9300 if (S.SourceMgr.isInSystemMacro(CC)) 9301 return; 9302 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9303 } 9304 9305 // If the vector cast is cast between two vectors of the same size, it is 9306 // a bitcast, not a conversion. 9307 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9308 return; 9309 9310 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9311 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9312 } 9313 if (auto VecTy = dyn_cast<VectorType>(Target)) 9314 Target = VecTy->getElementType().getTypePtr(); 9315 9316 // Strip complex types. 9317 if (isa<ComplexType>(Source)) { 9318 if (!isa<ComplexType>(Target)) { 9319 if (S.SourceMgr.isInSystemMacro(CC)) 9320 return; 9321 9322 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 9323 } 9324 9325 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9326 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9327 } 9328 9329 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9330 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9331 9332 // If the source is floating point... 9333 if (SourceBT && SourceBT->isFloatingPoint()) { 9334 // ...and the target is floating point... 9335 if (TargetBT && TargetBT->isFloatingPoint()) { 9336 // ...then warn if we're dropping FP rank. 9337 9338 // Builtin FP kinds are ordered by increasing FP rank. 9339 if (SourceBT->getKind() > TargetBT->getKind()) { 9340 // Don't warn about float constants that are precisely 9341 // representable in the target type. 9342 Expr::EvalResult result; 9343 if (E->EvaluateAsRValue(result, S.Context)) { 9344 // Value might be a float, a float vector, or a float complex. 9345 if (IsSameFloatAfterCast(result.Val, 9346 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9347 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9348 return; 9349 } 9350 9351 if (S.SourceMgr.isInSystemMacro(CC)) 9352 return; 9353 9354 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9355 } 9356 // ... or possibly if we're increasing rank, too 9357 else if (TargetBT->getKind() > SourceBT->getKind()) { 9358 if (S.SourceMgr.isInSystemMacro(CC)) 9359 return; 9360 9361 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9362 } 9363 return; 9364 } 9365 9366 // If the target is integral, always warn. 9367 if (TargetBT && TargetBT->isInteger()) { 9368 if (S.SourceMgr.isInSystemMacro(CC)) 9369 return; 9370 9371 DiagnoseFloatingImpCast(S, E, T, CC); 9372 } 9373 9374 // Detect the case where a call result is converted from floating-point to 9375 // to bool, and the final argument to the call is converted from bool, to 9376 // discover this typo: 9377 // 9378 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9379 // 9380 // FIXME: This is an incredibly special case; is there some more general 9381 // way to detect this class of misplaced-parentheses bug? 9382 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9383 // Check last argument of function call to see if it is an 9384 // implicit cast from a type matching the type the result 9385 // is being cast to. 9386 CallExpr *CEx = cast<CallExpr>(E); 9387 if (unsigned NumArgs = CEx->getNumArgs()) { 9388 Expr *LastA = CEx->getArg(NumArgs - 1); 9389 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9390 if (isa<ImplicitCastExpr>(LastA) && 9391 InnerE->getType()->isBooleanType()) { 9392 // Warn on this floating-point to bool conversion 9393 DiagnoseImpCast(S, E, T, CC, 9394 diag::warn_impcast_floating_point_to_bool); 9395 } 9396 } 9397 } 9398 return; 9399 } 9400 9401 DiagnoseNullConversion(S, E, T, CC); 9402 9403 S.DiscardMisalignedMemberAddress(Target, E); 9404 9405 if (!Source->isIntegerType() || !Target->isIntegerType()) 9406 return; 9407 9408 // TODO: remove this early return once the false positives for constant->bool 9409 // in templates, macros, etc, are reduced or removed. 9410 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9411 return; 9412 9413 IntRange SourceRange = GetExprRange(S.Context, E); 9414 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9415 9416 if (SourceRange.Width > TargetRange.Width) { 9417 // If the source is a constant, use a default-on diagnostic. 9418 // TODO: this should happen for bitfield stores, too. 9419 llvm::APSInt Value(32); 9420 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9421 if (S.SourceMgr.isInSystemMacro(CC)) 9422 return; 9423 9424 std::string PrettySourceValue = Value.toString(10); 9425 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9426 9427 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9428 S.PDiag(diag::warn_impcast_integer_precision_constant) 9429 << PrettySourceValue << PrettyTargetValue 9430 << E->getType() << T << E->getSourceRange() 9431 << clang::SourceRange(CC)); 9432 return; 9433 } 9434 9435 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9436 if (S.SourceMgr.isInSystemMacro(CC)) 9437 return; 9438 9439 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9440 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9441 /* pruneControlFlow */ true); 9442 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9443 } 9444 9445 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9446 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9447 // Warn when doing a signed to signed conversion, warn if the positive 9448 // source value is exactly the width of the target type, which will 9449 // cause a negative value to be stored. 9450 9451 llvm::APSInt Value; 9452 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9453 !S.SourceMgr.isInSystemMacro(CC)) { 9454 if (isSameWidthConstantConversion(S, E, T, CC)) { 9455 std::string PrettySourceValue = Value.toString(10); 9456 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9457 9458 S.DiagRuntimeBehavior( 9459 E->getExprLoc(), E, 9460 S.PDiag(diag::warn_impcast_integer_precision_constant) 9461 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9462 << E->getSourceRange() << clang::SourceRange(CC)); 9463 return; 9464 } 9465 } 9466 9467 // Fall through for non-constants to give a sign conversion warning. 9468 } 9469 9470 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9471 (!TargetRange.NonNegative && SourceRange.NonNegative && 9472 SourceRange.Width == TargetRange.Width)) { 9473 if (S.SourceMgr.isInSystemMacro(CC)) 9474 return; 9475 9476 unsigned DiagID = diag::warn_impcast_integer_sign; 9477 9478 // Traditionally, gcc has warned about this under -Wsign-compare. 9479 // We also want to warn about it in -Wconversion. 9480 // So if -Wconversion is off, use a completely identical diagnostic 9481 // in the sign-compare group. 9482 // The conditional-checking code will 9483 if (ICContext) { 9484 DiagID = diag::warn_impcast_integer_sign_conditional; 9485 *ICContext = true; 9486 } 9487 9488 return DiagnoseImpCast(S, E, T, CC, DiagID); 9489 } 9490 9491 // Diagnose conversions between different enumeration types. 9492 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9493 // type, to give us better diagnostics. 9494 QualType SourceType = E->getType(); 9495 if (!S.getLangOpts().CPlusPlus) { 9496 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9497 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9498 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9499 SourceType = S.Context.getTypeDeclType(Enum); 9500 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9501 } 9502 } 9503 9504 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9505 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9506 if (SourceEnum->getDecl()->hasNameForLinkage() && 9507 TargetEnum->getDecl()->hasNameForLinkage() && 9508 SourceEnum != TargetEnum) { 9509 if (S.SourceMgr.isInSystemMacro(CC)) 9510 return; 9511 9512 return DiagnoseImpCast(S, E, SourceType, T, CC, 9513 diag::warn_impcast_different_enum_types); 9514 } 9515 } 9516 9517 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9518 SourceLocation CC, QualType T); 9519 9520 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9521 SourceLocation CC, bool &ICContext) { 9522 E = E->IgnoreParenImpCasts(); 9523 9524 if (isa<ConditionalOperator>(E)) 9525 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9526 9527 AnalyzeImplicitConversions(S, E, CC); 9528 if (E->getType() != T) 9529 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9530 } 9531 9532 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9533 SourceLocation CC, QualType T) { 9534 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9535 9536 bool Suspicious = false; 9537 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9538 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9539 9540 // If -Wconversion would have warned about either of the candidates 9541 // for a signedness conversion to the context type... 9542 if (!Suspicious) return; 9543 9544 // ...but it's currently ignored... 9545 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9546 return; 9547 9548 // ...then check whether it would have warned about either of the 9549 // candidates for a signedness conversion to the condition type. 9550 if (E->getType() == T) return; 9551 9552 Suspicious = false; 9553 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9554 E->getType(), CC, &Suspicious); 9555 if (!Suspicious) 9556 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9557 E->getType(), CC, &Suspicious); 9558 } 9559 9560 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9561 /// Input argument E is a logical expression. 9562 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9563 if (S.getLangOpts().Bool) 9564 return; 9565 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9566 } 9567 9568 /// AnalyzeImplicitConversions - Find and report any interesting 9569 /// implicit conversions in the given expression. There are a couple 9570 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9571 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9572 QualType T = OrigE->getType(); 9573 Expr *E = OrigE->IgnoreParenImpCasts(); 9574 9575 if (E->isTypeDependent() || E->isValueDependent()) 9576 return; 9577 9578 // For conditional operators, we analyze the arguments as if they 9579 // were being fed directly into the output. 9580 if (isa<ConditionalOperator>(E)) { 9581 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9582 CheckConditionalOperator(S, CO, CC, T); 9583 return; 9584 } 9585 9586 // Check implicit argument conversions for function calls. 9587 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9588 CheckImplicitArgumentConversions(S, Call, CC); 9589 9590 // Go ahead and check any implicit conversions we might have skipped. 9591 // The non-canonical typecheck is just an optimization; 9592 // CheckImplicitConversion will filter out dead implicit conversions. 9593 if (E->getType() != T) 9594 CheckImplicitConversion(S, E, T, CC); 9595 9596 // Now continue drilling into this expression. 9597 9598 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9599 // The bound subexpressions in a PseudoObjectExpr are not reachable 9600 // as transitive children. 9601 // FIXME: Use a more uniform representation for this. 9602 for (auto *SE : POE->semantics()) 9603 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9604 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9605 } 9606 9607 // Skip past explicit casts. 9608 if (isa<ExplicitCastExpr>(E)) { 9609 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9610 return AnalyzeImplicitConversions(S, E, CC); 9611 } 9612 9613 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9614 // Do a somewhat different check with comparison operators. 9615 if (BO->isComparisonOp()) 9616 return AnalyzeComparison(S, BO); 9617 9618 // And with simple assignments. 9619 if (BO->getOpcode() == BO_Assign) 9620 return AnalyzeAssignment(S, BO); 9621 } 9622 9623 // These break the otherwise-useful invariant below. Fortunately, 9624 // we don't really need to recurse into them, because any internal 9625 // expressions should have been analyzed already when they were 9626 // built into statements. 9627 if (isa<StmtExpr>(E)) return; 9628 9629 // Don't descend into unevaluated contexts. 9630 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9631 9632 // Now just recurse over the expression's children. 9633 CC = E->getExprLoc(); 9634 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9635 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9636 for (Stmt *SubStmt : E->children()) { 9637 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9638 if (!ChildExpr) 9639 continue; 9640 9641 if (IsLogicalAndOperator && 9642 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9643 // Ignore checking string literals that are in logical and operators. 9644 // This is a common pattern for asserts. 9645 continue; 9646 AnalyzeImplicitConversions(S, ChildExpr, CC); 9647 } 9648 9649 if (BO && BO->isLogicalOp()) { 9650 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9651 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9652 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9653 9654 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9655 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9656 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9657 } 9658 9659 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9660 if (U->getOpcode() == UO_LNot) 9661 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9662 } 9663 9664 } // end anonymous namespace 9665 9666 /// Diagnose integer type and any valid implicit convertion to it. 9667 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 9668 // Taking into account implicit conversions, 9669 // allow any integer. 9670 if (!E->getType()->isIntegerType()) { 9671 S.Diag(E->getLocStart(), 9672 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9673 return true; 9674 } 9675 // Potentially emit standard warnings for implicit conversions if enabled 9676 // using -Wconversion. 9677 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 9678 return false; 9679 } 9680 9681 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9682 // Returns true when emitting a warning about taking the address of a reference. 9683 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9684 const PartialDiagnostic &PD) { 9685 E = E->IgnoreParenImpCasts(); 9686 9687 const FunctionDecl *FD = nullptr; 9688 9689 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9690 if (!DRE->getDecl()->getType()->isReferenceType()) 9691 return false; 9692 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9693 if (!M->getMemberDecl()->getType()->isReferenceType()) 9694 return false; 9695 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9696 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9697 return false; 9698 FD = Call->getDirectCallee(); 9699 } else { 9700 return false; 9701 } 9702 9703 SemaRef.Diag(E->getExprLoc(), PD); 9704 9705 // If possible, point to location of function. 9706 if (FD) { 9707 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9708 } 9709 9710 return true; 9711 } 9712 9713 // Returns true if the SourceLocation is expanded from any macro body. 9714 // Returns false if the SourceLocation is invalid, is from not in a macro 9715 // expansion, or is from expanded from a top-level macro argument. 9716 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9717 if (Loc.isInvalid()) 9718 return false; 9719 9720 while (Loc.isMacroID()) { 9721 if (SM.isMacroBodyExpansion(Loc)) 9722 return true; 9723 Loc = SM.getImmediateMacroCallerLoc(Loc); 9724 } 9725 9726 return false; 9727 } 9728 9729 /// \brief Diagnose pointers that are always non-null. 9730 /// \param E the expression containing the pointer 9731 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9732 /// compared to a null pointer 9733 /// \param IsEqual True when the comparison is equal to a null pointer 9734 /// \param Range Extra SourceRange to highlight in the diagnostic 9735 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9736 Expr::NullPointerConstantKind NullKind, 9737 bool IsEqual, SourceRange Range) { 9738 if (!E) 9739 return; 9740 9741 // Don't warn inside macros. 9742 if (E->getExprLoc().isMacroID()) { 9743 const SourceManager &SM = getSourceManager(); 9744 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9745 IsInAnyMacroBody(SM, Range.getBegin())) 9746 return; 9747 } 9748 E = E->IgnoreImpCasts(); 9749 9750 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9751 9752 if (isa<CXXThisExpr>(E)) { 9753 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9754 : diag::warn_this_bool_conversion; 9755 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9756 return; 9757 } 9758 9759 bool IsAddressOf = false; 9760 9761 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9762 if (UO->getOpcode() != UO_AddrOf) 9763 return; 9764 IsAddressOf = true; 9765 E = UO->getSubExpr(); 9766 } 9767 9768 if (IsAddressOf) { 9769 unsigned DiagID = IsCompare 9770 ? diag::warn_address_of_reference_null_compare 9771 : diag::warn_address_of_reference_bool_conversion; 9772 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 9773 << IsEqual; 9774 if (CheckForReference(*this, E, PD)) { 9775 return; 9776 } 9777 } 9778 9779 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 9780 bool IsParam = isa<NonNullAttr>(NonnullAttr); 9781 std::string Str; 9782 llvm::raw_string_ostream S(Str); 9783 E->printPretty(S, nullptr, getPrintingPolicy()); 9784 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 9785 : diag::warn_cast_nonnull_to_bool; 9786 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 9787 << E->getSourceRange() << Range << IsEqual; 9788 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 9789 }; 9790 9791 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 9792 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 9793 if (auto *Callee = Call->getDirectCallee()) { 9794 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 9795 ComplainAboutNonnullParamOrCall(A); 9796 return; 9797 } 9798 } 9799 } 9800 9801 // Expect to find a single Decl. Skip anything more complicated. 9802 ValueDecl *D = nullptr; 9803 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 9804 D = R->getDecl(); 9805 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9806 D = M->getMemberDecl(); 9807 } 9808 9809 // Weak Decls can be null. 9810 if (!D || D->isWeak()) 9811 return; 9812 9813 // Check for parameter decl with nonnull attribute 9814 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 9815 if (getCurFunction() && 9816 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 9817 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 9818 ComplainAboutNonnullParamOrCall(A); 9819 return; 9820 } 9821 9822 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 9823 auto ParamIter = llvm::find(FD->parameters(), PV); 9824 assert(ParamIter != FD->param_end()); 9825 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 9826 9827 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 9828 if (!NonNull->args_size()) { 9829 ComplainAboutNonnullParamOrCall(NonNull); 9830 return; 9831 } 9832 9833 for (unsigned ArgNo : NonNull->args()) { 9834 if (ArgNo == ParamNo) { 9835 ComplainAboutNonnullParamOrCall(NonNull); 9836 return; 9837 } 9838 } 9839 } 9840 } 9841 } 9842 } 9843 9844 QualType T = D->getType(); 9845 const bool IsArray = T->isArrayType(); 9846 const bool IsFunction = T->isFunctionType(); 9847 9848 // Address of function is used to silence the function warning. 9849 if (IsAddressOf && IsFunction) { 9850 return; 9851 } 9852 9853 // Found nothing. 9854 if (!IsAddressOf && !IsFunction && !IsArray) 9855 return; 9856 9857 // Pretty print the expression for the diagnostic. 9858 std::string Str; 9859 llvm::raw_string_ostream S(Str); 9860 E->printPretty(S, nullptr, getPrintingPolicy()); 9861 9862 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 9863 : diag::warn_impcast_pointer_to_bool; 9864 enum { 9865 AddressOf, 9866 FunctionPointer, 9867 ArrayPointer 9868 } DiagType; 9869 if (IsAddressOf) 9870 DiagType = AddressOf; 9871 else if (IsFunction) 9872 DiagType = FunctionPointer; 9873 else if (IsArray) 9874 DiagType = ArrayPointer; 9875 else 9876 llvm_unreachable("Could not determine diagnostic."); 9877 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 9878 << Range << IsEqual; 9879 9880 if (!IsFunction) 9881 return; 9882 9883 // Suggest '&' to silence the function warning. 9884 Diag(E->getExprLoc(), diag::note_function_warning_silence) 9885 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 9886 9887 // Check to see if '()' fixit should be emitted. 9888 QualType ReturnType; 9889 UnresolvedSet<4> NonTemplateOverloads; 9890 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 9891 if (ReturnType.isNull()) 9892 return; 9893 9894 if (IsCompare) { 9895 // There are two cases here. If there is null constant, the only suggest 9896 // for a pointer return type. If the null is 0, then suggest if the return 9897 // type is a pointer or an integer type. 9898 if (!ReturnType->isPointerType()) { 9899 if (NullKind == Expr::NPCK_ZeroExpression || 9900 NullKind == Expr::NPCK_ZeroLiteral) { 9901 if (!ReturnType->isIntegerType()) 9902 return; 9903 } else { 9904 return; 9905 } 9906 } 9907 } else { // !IsCompare 9908 // For function to bool, only suggest if the function pointer has bool 9909 // return type. 9910 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 9911 return; 9912 } 9913 Diag(E->getExprLoc(), diag::note_function_to_function_call) 9914 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 9915 } 9916 9917 /// Diagnoses "dangerous" implicit conversions within the given 9918 /// expression (which is a full expression). Implements -Wconversion 9919 /// and -Wsign-compare. 9920 /// 9921 /// \param CC the "context" location of the implicit conversion, i.e. 9922 /// the most location of the syntactic entity requiring the implicit 9923 /// conversion 9924 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 9925 // Don't diagnose in unevaluated contexts. 9926 if (isUnevaluatedContext()) 9927 return; 9928 9929 // Don't diagnose for value- or type-dependent expressions. 9930 if (E->isTypeDependent() || E->isValueDependent()) 9931 return; 9932 9933 // Check for array bounds violations in cases where the check isn't triggered 9934 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 9935 // ArraySubscriptExpr is on the RHS of a variable initialization. 9936 CheckArrayAccess(E); 9937 9938 // This is not the right CC for (e.g.) a variable initialization. 9939 AnalyzeImplicitConversions(*this, E, CC); 9940 } 9941 9942 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9943 /// Input argument E is a logical expression. 9944 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 9945 ::CheckBoolLikeConversion(*this, E, CC); 9946 } 9947 9948 /// Diagnose when expression is an integer constant expression and its evaluation 9949 /// results in integer overflow 9950 void Sema::CheckForIntOverflow (Expr *E) { 9951 // Use a work list to deal with nested struct initializers. 9952 SmallVector<Expr *, 2> Exprs(1, E); 9953 9954 do { 9955 Expr *E = Exprs.pop_back_val(); 9956 9957 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 9958 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 9959 continue; 9960 } 9961 9962 if (auto InitList = dyn_cast<InitListExpr>(E)) 9963 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 9964 9965 if (isa<ObjCBoxedExpr>(E)) 9966 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 9967 } while (!Exprs.empty()); 9968 } 9969 9970 namespace { 9971 /// \brief Visitor for expressions which looks for unsequenced operations on the 9972 /// same object. 9973 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 9974 typedef EvaluatedExprVisitor<SequenceChecker> Base; 9975 9976 /// \brief A tree of sequenced regions within an expression. Two regions are 9977 /// unsequenced if one is an ancestor or a descendent of the other. When we 9978 /// finish processing an expression with sequencing, such as a comma 9979 /// expression, we fold its tree nodes into its parent, since they are 9980 /// unsequenced with respect to nodes we will visit later. 9981 class SequenceTree { 9982 struct Value { 9983 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 9984 unsigned Parent : 31; 9985 unsigned Merged : 1; 9986 }; 9987 SmallVector<Value, 8> Values; 9988 9989 public: 9990 /// \brief A region within an expression which may be sequenced with respect 9991 /// to some other region. 9992 class Seq { 9993 explicit Seq(unsigned N) : Index(N) {} 9994 unsigned Index; 9995 friend class SequenceTree; 9996 public: 9997 Seq() : Index(0) {} 9998 }; 9999 10000 SequenceTree() { Values.push_back(Value(0)); } 10001 Seq root() const { return Seq(0); } 10002 10003 /// \brief Create a new sequence of operations, which is an unsequenced 10004 /// subset of \p Parent. This sequence of operations is sequenced with 10005 /// respect to other children of \p Parent. 10006 Seq allocate(Seq Parent) { 10007 Values.push_back(Value(Parent.Index)); 10008 return Seq(Values.size() - 1); 10009 } 10010 10011 /// \brief Merge a sequence of operations into its parent. 10012 void merge(Seq S) { 10013 Values[S.Index].Merged = true; 10014 } 10015 10016 /// \brief Determine whether two operations are unsequenced. This operation 10017 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10018 /// should have been merged into its parent as appropriate. 10019 bool isUnsequenced(Seq Cur, Seq Old) { 10020 unsigned C = representative(Cur.Index); 10021 unsigned Target = representative(Old.Index); 10022 while (C >= Target) { 10023 if (C == Target) 10024 return true; 10025 C = Values[C].Parent; 10026 } 10027 return false; 10028 } 10029 10030 private: 10031 /// \brief Pick a representative for a sequence. 10032 unsigned representative(unsigned K) { 10033 if (Values[K].Merged) 10034 // Perform path compression as we go. 10035 return Values[K].Parent = representative(Values[K].Parent); 10036 return K; 10037 } 10038 }; 10039 10040 /// An object for which we can track unsequenced uses. 10041 typedef NamedDecl *Object; 10042 10043 /// Different flavors of object usage which we track. We only track the 10044 /// least-sequenced usage of each kind. 10045 enum UsageKind { 10046 /// A read of an object. Multiple unsequenced reads are OK. 10047 UK_Use, 10048 /// A modification of an object which is sequenced before the value 10049 /// computation of the expression, such as ++n in C++. 10050 UK_ModAsValue, 10051 /// A modification of an object which is not sequenced before the value 10052 /// computation of the expression, such as n++. 10053 UK_ModAsSideEffect, 10054 10055 UK_Count = UK_ModAsSideEffect + 1 10056 }; 10057 10058 struct Usage { 10059 Usage() : Use(nullptr), Seq() {} 10060 Expr *Use; 10061 SequenceTree::Seq Seq; 10062 }; 10063 10064 struct UsageInfo { 10065 UsageInfo() : Diagnosed(false) {} 10066 Usage Uses[UK_Count]; 10067 /// Have we issued a diagnostic for this variable already? 10068 bool Diagnosed; 10069 }; 10070 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 10071 10072 Sema &SemaRef; 10073 /// Sequenced regions within the expression. 10074 SequenceTree Tree; 10075 /// Declaration modifications and references which we have seen. 10076 UsageInfoMap UsageMap; 10077 /// The region we are currently within. 10078 SequenceTree::Seq Region; 10079 /// Filled in with declarations which were modified as a side-effect 10080 /// (that is, post-increment operations). 10081 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 10082 /// Expressions to check later. We defer checking these to reduce 10083 /// stack usage. 10084 SmallVectorImpl<Expr *> &WorkList; 10085 10086 /// RAII object wrapping the visitation of a sequenced subexpression of an 10087 /// expression. At the end of this process, the side-effects of the evaluation 10088 /// become sequenced with respect to the value computation of the result, so 10089 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10090 /// UK_ModAsValue. 10091 struct SequencedSubexpression { 10092 SequencedSubexpression(SequenceChecker &Self) 10093 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 10094 Self.ModAsSideEffect = &ModAsSideEffect; 10095 } 10096 ~SequencedSubexpression() { 10097 for (auto &M : llvm::reverse(ModAsSideEffect)) { 10098 UsageInfo &U = Self.UsageMap[M.first]; 10099 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 10100 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 10101 SideEffectUsage = M.second; 10102 } 10103 Self.ModAsSideEffect = OldModAsSideEffect; 10104 } 10105 10106 SequenceChecker &Self; 10107 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 10108 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 10109 }; 10110 10111 /// RAII object wrapping the visitation of a subexpression which we might 10112 /// choose to evaluate as a constant. If any subexpression is evaluated and 10113 /// found to be non-constant, this allows us to suppress the evaluation of 10114 /// the outer expression. 10115 class EvaluationTracker { 10116 public: 10117 EvaluationTracker(SequenceChecker &Self) 10118 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 10119 Self.EvalTracker = this; 10120 } 10121 ~EvaluationTracker() { 10122 Self.EvalTracker = Prev; 10123 if (Prev) 10124 Prev->EvalOK &= EvalOK; 10125 } 10126 10127 bool evaluate(const Expr *E, bool &Result) { 10128 if (!EvalOK || E->isValueDependent()) 10129 return false; 10130 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 10131 return EvalOK; 10132 } 10133 10134 private: 10135 SequenceChecker &Self; 10136 EvaluationTracker *Prev; 10137 bool EvalOK; 10138 } *EvalTracker; 10139 10140 /// \brief Find the object which is produced by the specified expression, 10141 /// if any. 10142 Object getObject(Expr *E, bool Mod) const { 10143 E = E->IgnoreParenCasts(); 10144 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10145 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 10146 return getObject(UO->getSubExpr(), Mod); 10147 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10148 if (BO->getOpcode() == BO_Comma) 10149 return getObject(BO->getRHS(), Mod); 10150 if (Mod && BO->isAssignmentOp()) 10151 return getObject(BO->getLHS(), Mod); 10152 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10153 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 10154 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 10155 return ME->getMemberDecl(); 10156 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10157 // FIXME: If this is a reference, map through to its value. 10158 return DRE->getDecl(); 10159 return nullptr; 10160 } 10161 10162 /// \brief Note that an object was modified or used by an expression. 10163 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 10164 Usage &U = UI.Uses[UK]; 10165 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 10166 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 10167 ModAsSideEffect->push_back(std::make_pair(O, U)); 10168 U.Use = Ref; 10169 U.Seq = Region; 10170 } 10171 } 10172 /// \brief Check whether a modification or use conflicts with a prior usage. 10173 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 10174 bool IsModMod) { 10175 if (UI.Diagnosed) 10176 return; 10177 10178 const Usage &U = UI.Uses[OtherKind]; 10179 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 10180 return; 10181 10182 Expr *Mod = U.Use; 10183 Expr *ModOrUse = Ref; 10184 if (OtherKind == UK_Use) 10185 std::swap(Mod, ModOrUse); 10186 10187 SemaRef.Diag(Mod->getExprLoc(), 10188 IsModMod ? diag::warn_unsequenced_mod_mod 10189 : diag::warn_unsequenced_mod_use) 10190 << O << SourceRange(ModOrUse->getExprLoc()); 10191 UI.Diagnosed = true; 10192 } 10193 10194 void notePreUse(Object O, Expr *Use) { 10195 UsageInfo &U = UsageMap[O]; 10196 // Uses conflict with other modifications. 10197 checkUsage(O, U, Use, UK_ModAsValue, false); 10198 } 10199 void notePostUse(Object O, Expr *Use) { 10200 UsageInfo &U = UsageMap[O]; 10201 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 10202 addUsage(U, O, Use, UK_Use); 10203 } 10204 10205 void notePreMod(Object O, Expr *Mod) { 10206 UsageInfo &U = UsageMap[O]; 10207 // Modifications conflict with other modifications and with uses. 10208 checkUsage(O, U, Mod, UK_ModAsValue, true); 10209 checkUsage(O, U, Mod, UK_Use, false); 10210 } 10211 void notePostMod(Object O, Expr *Use, UsageKind UK) { 10212 UsageInfo &U = UsageMap[O]; 10213 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 10214 addUsage(U, O, Use, UK); 10215 } 10216 10217 public: 10218 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 10219 : Base(S.Context), SemaRef(S), Region(Tree.root()), 10220 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 10221 Visit(E); 10222 } 10223 10224 void VisitStmt(Stmt *S) { 10225 // Skip all statements which aren't expressions for now. 10226 } 10227 10228 void VisitExpr(Expr *E) { 10229 // By default, just recurse to evaluated subexpressions. 10230 Base::VisitStmt(E); 10231 } 10232 10233 void VisitCastExpr(CastExpr *E) { 10234 Object O = Object(); 10235 if (E->getCastKind() == CK_LValueToRValue) 10236 O = getObject(E->getSubExpr(), false); 10237 10238 if (O) 10239 notePreUse(O, E); 10240 VisitExpr(E); 10241 if (O) 10242 notePostUse(O, E); 10243 } 10244 10245 void VisitBinComma(BinaryOperator *BO) { 10246 // C++11 [expr.comma]p1: 10247 // Every value computation and side effect associated with the left 10248 // expression is sequenced before every value computation and side 10249 // effect associated with the right expression. 10250 SequenceTree::Seq LHS = Tree.allocate(Region); 10251 SequenceTree::Seq RHS = Tree.allocate(Region); 10252 SequenceTree::Seq OldRegion = Region; 10253 10254 { 10255 SequencedSubexpression SeqLHS(*this); 10256 Region = LHS; 10257 Visit(BO->getLHS()); 10258 } 10259 10260 Region = RHS; 10261 Visit(BO->getRHS()); 10262 10263 Region = OldRegion; 10264 10265 // Forget that LHS and RHS are sequenced. They are both unsequenced 10266 // with respect to other stuff. 10267 Tree.merge(LHS); 10268 Tree.merge(RHS); 10269 } 10270 10271 void VisitBinAssign(BinaryOperator *BO) { 10272 // The modification is sequenced after the value computation of the LHS 10273 // and RHS, so check it before inspecting the operands and update the 10274 // map afterwards. 10275 Object O = getObject(BO->getLHS(), true); 10276 if (!O) 10277 return VisitExpr(BO); 10278 10279 notePreMod(O, BO); 10280 10281 // C++11 [expr.ass]p7: 10282 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 10283 // only once. 10284 // 10285 // Therefore, for a compound assignment operator, O is considered used 10286 // everywhere except within the evaluation of E1 itself. 10287 if (isa<CompoundAssignOperator>(BO)) 10288 notePreUse(O, BO); 10289 10290 Visit(BO->getLHS()); 10291 10292 if (isa<CompoundAssignOperator>(BO)) 10293 notePostUse(O, BO); 10294 10295 Visit(BO->getRHS()); 10296 10297 // C++11 [expr.ass]p1: 10298 // the assignment is sequenced [...] before the value computation of the 10299 // assignment expression. 10300 // C11 6.5.16/3 has no such rule. 10301 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10302 : UK_ModAsSideEffect); 10303 } 10304 10305 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 10306 VisitBinAssign(CAO); 10307 } 10308 10309 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10310 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10311 void VisitUnaryPreIncDec(UnaryOperator *UO) { 10312 Object O = getObject(UO->getSubExpr(), true); 10313 if (!O) 10314 return VisitExpr(UO); 10315 10316 notePreMod(O, UO); 10317 Visit(UO->getSubExpr()); 10318 // C++11 [expr.pre.incr]p1: 10319 // the expression ++x is equivalent to x+=1 10320 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10321 : UK_ModAsSideEffect); 10322 } 10323 10324 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10325 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10326 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10327 Object O = getObject(UO->getSubExpr(), true); 10328 if (!O) 10329 return VisitExpr(UO); 10330 10331 notePreMod(O, UO); 10332 Visit(UO->getSubExpr()); 10333 notePostMod(O, UO, UK_ModAsSideEffect); 10334 } 10335 10336 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10337 void VisitBinLOr(BinaryOperator *BO) { 10338 // The side-effects of the LHS of an '&&' are sequenced before the 10339 // value computation of the RHS, and hence before the value computation 10340 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10341 // as if they were unconditionally sequenced. 10342 EvaluationTracker Eval(*this); 10343 { 10344 SequencedSubexpression Sequenced(*this); 10345 Visit(BO->getLHS()); 10346 } 10347 10348 bool Result; 10349 if (Eval.evaluate(BO->getLHS(), Result)) { 10350 if (!Result) 10351 Visit(BO->getRHS()); 10352 } else { 10353 // Check for unsequenced operations in the RHS, treating it as an 10354 // entirely separate evaluation. 10355 // 10356 // FIXME: If there are operations in the RHS which are unsequenced 10357 // with respect to operations outside the RHS, and those operations 10358 // are unconditionally evaluated, diagnose them. 10359 WorkList.push_back(BO->getRHS()); 10360 } 10361 } 10362 void VisitBinLAnd(BinaryOperator *BO) { 10363 EvaluationTracker Eval(*this); 10364 { 10365 SequencedSubexpression Sequenced(*this); 10366 Visit(BO->getLHS()); 10367 } 10368 10369 bool Result; 10370 if (Eval.evaluate(BO->getLHS(), Result)) { 10371 if (Result) 10372 Visit(BO->getRHS()); 10373 } else { 10374 WorkList.push_back(BO->getRHS()); 10375 } 10376 } 10377 10378 // Only visit the condition, unless we can be sure which subexpression will 10379 // be chosen. 10380 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10381 EvaluationTracker Eval(*this); 10382 { 10383 SequencedSubexpression Sequenced(*this); 10384 Visit(CO->getCond()); 10385 } 10386 10387 bool Result; 10388 if (Eval.evaluate(CO->getCond(), Result)) 10389 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10390 else { 10391 WorkList.push_back(CO->getTrueExpr()); 10392 WorkList.push_back(CO->getFalseExpr()); 10393 } 10394 } 10395 10396 void VisitCallExpr(CallExpr *CE) { 10397 // C++11 [intro.execution]p15: 10398 // When calling a function [...], every value computation and side effect 10399 // associated with any argument expression, or with the postfix expression 10400 // designating the called function, is sequenced before execution of every 10401 // expression or statement in the body of the function [and thus before 10402 // the value computation of its result]. 10403 SequencedSubexpression Sequenced(*this); 10404 Base::VisitCallExpr(CE); 10405 10406 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10407 } 10408 10409 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10410 // This is a call, so all subexpressions are sequenced before the result. 10411 SequencedSubexpression Sequenced(*this); 10412 10413 if (!CCE->isListInitialization()) 10414 return VisitExpr(CCE); 10415 10416 // In C++11, list initializations are sequenced. 10417 SmallVector<SequenceTree::Seq, 32> Elts; 10418 SequenceTree::Seq Parent = Region; 10419 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10420 E = CCE->arg_end(); 10421 I != E; ++I) { 10422 Region = Tree.allocate(Parent); 10423 Elts.push_back(Region); 10424 Visit(*I); 10425 } 10426 10427 // Forget that the initializers are sequenced. 10428 Region = Parent; 10429 for (unsigned I = 0; I < Elts.size(); ++I) 10430 Tree.merge(Elts[I]); 10431 } 10432 10433 void VisitInitListExpr(InitListExpr *ILE) { 10434 if (!SemaRef.getLangOpts().CPlusPlus11) 10435 return VisitExpr(ILE); 10436 10437 // In C++11, list initializations are sequenced. 10438 SmallVector<SequenceTree::Seq, 32> Elts; 10439 SequenceTree::Seq Parent = Region; 10440 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10441 Expr *E = ILE->getInit(I); 10442 if (!E) continue; 10443 Region = Tree.allocate(Parent); 10444 Elts.push_back(Region); 10445 Visit(E); 10446 } 10447 10448 // Forget that the initializers are sequenced. 10449 Region = Parent; 10450 for (unsigned I = 0; I < Elts.size(); ++I) 10451 Tree.merge(Elts[I]); 10452 } 10453 }; 10454 } // end anonymous namespace 10455 10456 void Sema::CheckUnsequencedOperations(Expr *E) { 10457 SmallVector<Expr *, 8> WorkList; 10458 WorkList.push_back(E); 10459 while (!WorkList.empty()) { 10460 Expr *Item = WorkList.pop_back_val(); 10461 SequenceChecker(*this, Item, WorkList); 10462 } 10463 } 10464 10465 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10466 bool IsConstexpr) { 10467 CheckImplicitConversions(E, CheckLoc); 10468 if (!E->isInstantiationDependent()) 10469 CheckUnsequencedOperations(E); 10470 if (!IsConstexpr && !E->isValueDependent()) 10471 CheckForIntOverflow(E); 10472 DiagnoseMisalignedMembers(); 10473 } 10474 10475 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10476 FieldDecl *BitField, 10477 Expr *Init) { 10478 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10479 } 10480 10481 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10482 SourceLocation Loc) { 10483 if (!PType->isVariablyModifiedType()) 10484 return; 10485 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10486 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10487 return; 10488 } 10489 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10490 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10491 return; 10492 } 10493 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10494 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10495 return; 10496 } 10497 10498 const ArrayType *AT = S.Context.getAsArrayType(PType); 10499 if (!AT) 10500 return; 10501 10502 if (AT->getSizeModifier() != ArrayType::Star) { 10503 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10504 return; 10505 } 10506 10507 S.Diag(Loc, diag::err_array_star_in_function_definition); 10508 } 10509 10510 /// CheckParmsForFunctionDef - Check that the parameters of the given 10511 /// function are appropriate for the definition of a function. This 10512 /// takes care of any checks that cannot be performed on the 10513 /// declaration itself, e.g., that the types of each of the function 10514 /// parameters are complete. 10515 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10516 bool CheckParameterNames) { 10517 bool HasInvalidParm = false; 10518 for (ParmVarDecl *Param : Parameters) { 10519 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10520 // function declarator that is part of a function definition of 10521 // that function shall not have incomplete type. 10522 // 10523 // This is also C++ [dcl.fct]p6. 10524 if (!Param->isInvalidDecl() && 10525 RequireCompleteType(Param->getLocation(), Param->getType(), 10526 diag::err_typecheck_decl_incomplete_type)) { 10527 Param->setInvalidDecl(); 10528 HasInvalidParm = true; 10529 } 10530 10531 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10532 // declaration of each parameter shall include an identifier. 10533 if (CheckParameterNames && 10534 Param->getIdentifier() == nullptr && 10535 !Param->isImplicit() && 10536 !getLangOpts().CPlusPlus) 10537 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10538 10539 // C99 6.7.5.3p12: 10540 // If the function declarator is not part of a definition of that 10541 // function, parameters may have incomplete type and may use the [*] 10542 // notation in their sequences of declarator specifiers to specify 10543 // variable length array types. 10544 QualType PType = Param->getOriginalType(); 10545 // FIXME: This diagnostic should point the '[*]' if source-location 10546 // information is added for it. 10547 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10548 10549 // MSVC destroys objects passed by value in the callee. Therefore a 10550 // function definition which takes such a parameter must be able to call the 10551 // object's destructor. However, we don't perform any direct access check 10552 // on the dtor. 10553 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10554 .getCXXABI() 10555 .areArgsDestroyedLeftToRightInCallee()) { 10556 if (!Param->isInvalidDecl()) { 10557 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10558 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10559 if (!ClassDecl->isInvalidDecl() && 10560 !ClassDecl->hasIrrelevantDestructor() && 10561 !ClassDecl->isDependentContext()) { 10562 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10563 MarkFunctionReferenced(Param->getLocation(), Destructor); 10564 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10565 } 10566 } 10567 } 10568 } 10569 10570 // Parameters with the pass_object_size attribute only need to be marked 10571 // constant at function definitions. Because we lack information about 10572 // whether we're on a declaration or definition when we're instantiating the 10573 // attribute, we need to check for constness here. 10574 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10575 if (!Param->getType().isConstQualified()) 10576 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10577 << Attr->getSpelling() << 1; 10578 } 10579 10580 return HasInvalidParm; 10581 } 10582 10583 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 10584 /// or MemberExpr. 10585 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 10586 ASTContext &Context) { 10587 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 10588 return Context.getDeclAlign(DRE->getDecl()); 10589 10590 if (const auto *ME = dyn_cast<MemberExpr>(E)) 10591 return Context.getDeclAlign(ME->getMemberDecl()); 10592 10593 return TypeAlign; 10594 } 10595 10596 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10597 /// pointer cast increases the alignment requirements. 10598 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10599 // This is actually a lot of work to potentially be doing on every 10600 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10601 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10602 return; 10603 10604 // Ignore dependent types. 10605 if (T->isDependentType() || Op->getType()->isDependentType()) 10606 return; 10607 10608 // Require that the destination be a pointer type. 10609 const PointerType *DestPtr = T->getAs<PointerType>(); 10610 if (!DestPtr) return; 10611 10612 // If the destination has alignment 1, we're done. 10613 QualType DestPointee = DestPtr->getPointeeType(); 10614 if (DestPointee->isIncompleteType()) return; 10615 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10616 if (DestAlign.isOne()) return; 10617 10618 // Require that the source be a pointer type. 10619 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10620 if (!SrcPtr) return; 10621 QualType SrcPointee = SrcPtr->getPointeeType(); 10622 10623 // Whitelist casts from cv void*. We already implicitly 10624 // whitelisted casts to cv void*, since they have alignment 1. 10625 // Also whitelist casts involving incomplete types, which implicitly 10626 // includes 'void'. 10627 if (SrcPointee->isIncompleteType()) return; 10628 10629 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10630 10631 if (auto *CE = dyn_cast<CastExpr>(Op)) { 10632 if (CE->getCastKind() == CK_ArrayToPointerDecay) 10633 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 10634 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 10635 if (UO->getOpcode() == UO_AddrOf) 10636 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 10637 } 10638 10639 if (SrcAlign >= DestAlign) return; 10640 10641 Diag(TRange.getBegin(), diag::warn_cast_align) 10642 << Op->getType() << T 10643 << static_cast<unsigned>(SrcAlign.getQuantity()) 10644 << static_cast<unsigned>(DestAlign.getQuantity()) 10645 << TRange << Op->getSourceRange(); 10646 } 10647 10648 /// \brief Check whether this array fits the idiom of a size-one tail padded 10649 /// array member of a struct. 10650 /// 10651 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10652 /// commonly used to emulate flexible arrays in C89 code. 10653 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10654 const NamedDecl *ND) { 10655 if (Size != 1 || !ND) return false; 10656 10657 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10658 if (!FD) return false; 10659 10660 // Don't consider sizes resulting from macro expansions or template argument 10661 // substitution to form C89 tail-padded arrays. 10662 10663 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10664 while (TInfo) { 10665 TypeLoc TL = TInfo->getTypeLoc(); 10666 // Look through typedefs. 10667 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10668 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10669 TInfo = TDL->getTypeSourceInfo(); 10670 continue; 10671 } 10672 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10673 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10674 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10675 return false; 10676 } 10677 break; 10678 } 10679 10680 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10681 if (!RD) return false; 10682 if (RD->isUnion()) return false; 10683 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10684 if (!CRD->isStandardLayout()) return false; 10685 } 10686 10687 // See if this is the last field decl in the record. 10688 const Decl *D = FD; 10689 while ((D = D->getNextDeclInContext())) 10690 if (isa<FieldDecl>(D)) 10691 return false; 10692 return true; 10693 } 10694 10695 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10696 const ArraySubscriptExpr *ASE, 10697 bool AllowOnePastEnd, bool IndexNegated) { 10698 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10699 if (IndexExpr->isValueDependent()) 10700 return; 10701 10702 const Type *EffectiveType = 10703 BaseExpr->getType()->getPointeeOrArrayElementType(); 10704 BaseExpr = BaseExpr->IgnoreParenCasts(); 10705 const ConstantArrayType *ArrayTy = 10706 Context.getAsConstantArrayType(BaseExpr->getType()); 10707 if (!ArrayTy) 10708 return; 10709 10710 llvm::APSInt index; 10711 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10712 return; 10713 if (IndexNegated) 10714 index = -index; 10715 10716 const NamedDecl *ND = nullptr; 10717 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10718 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10719 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10720 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10721 10722 if (index.isUnsigned() || !index.isNegative()) { 10723 llvm::APInt size = ArrayTy->getSize(); 10724 if (!size.isStrictlyPositive()) 10725 return; 10726 10727 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10728 if (BaseType != EffectiveType) { 10729 // Make sure we're comparing apples to apples when comparing index to size 10730 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10731 uint64_t array_typesize = Context.getTypeSize(BaseType); 10732 // Handle ptrarith_typesize being zero, such as when casting to void* 10733 if (!ptrarith_typesize) ptrarith_typesize = 1; 10734 if (ptrarith_typesize != array_typesize) { 10735 // There's a cast to a different size type involved 10736 uint64_t ratio = array_typesize / ptrarith_typesize; 10737 // TODO: Be smarter about handling cases where array_typesize is not a 10738 // multiple of ptrarith_typesize 10739 if (ptrarith_typesize * ratio == array_typesize) 10740 size *= llvm::APInt(size.getBitWidth(), ratio); 10741 } 10742 } 10743 10744 if (size.getBitWidth() > index.getBitWidth()) 10745 index = index.zext(size.getBitWidth()); 10746 else if (size.getBitWidth() < index.getBitWidth()) 10747 size = size.zext(index.getBitWidth()); 10748 10749 // For array subscripting the index must be less than size, but for pointer 10750 // arithmetic also allow the index (offset) to be equal to size since 10751 // computing the next address after the end of the array is legal and 10752 // commonly done e.g. in C++ iterators and range-based for loops. 10753 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10754 return; 10755 10756 // Also don't warn for arrays of size 1 which are members of some 10757 // structure. These are often used to approximate flexible arrays in C89 10758 // code. 10759 if (IsTailPaddedMemberArray(*this, size, ND)) 10760 return; 10761 10762 // Suppress the warning if the subscript expression (as identified by the 10763 // ']' location) and the index expression are both from macro expansions 10764 // within a system header. 10765 if (ASE) { 10766 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 10767 ASE->getRBracketLoc()); 10768 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 10769 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 10770 IndexExpr->getLocStart()); 10771 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 10772 return; 10773 } 10774 } 10775 10776 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 10777 if (ASE) 10778 DiagID = diag::warn_array_index_exceeds_bounds; 10779 10780 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10781 PDiag(DiagID) << index.toString(10, true) 10782 << size.toString(10, true) 10783 << (unsigned)size.getLimitedValue(~0U) 10784 << IndexExpr->getSourceRange()); 10785 } else { 10786 unsigned DiagID = diag::warn_array_index_precedes_bounds; 10787 if (!ASE) { 10788 DiagID = diag::warn_ptr_arith_precedes_bounds; 10789 if (index.isNegative()) index = -index; 10790 } 10791 10792 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10793 PDiag(DiagID) << index.toString(10, true) 10794 << IndexExpr->getSourceRange()); 10795 } 10796 10797 if (!ND) { 10798 // Try harder to find a NamedDecl to point at in the note. 10799 while (const ArraySubscriptExpr *ASE = 10800 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 10801 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 10802 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10803 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10804 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10805 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10806 } 10807 10808 if (ND) 10809 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 10810 PDiag(diag::note_array_index_out_of_bounds) 10811 << ND->getDeclName()); 10812 } 10813 10814 void Sema::CheckArrayAccess(const Expr *expr) { 10815 int AllowOnePastEnd = 0; 10816 while (expr) { 10817 expr = expr->IgnoreParenImpCasts(); 10818 switch (expr->getStmtClass()) { 10819 case Stmt::ArraySubscriptExprClass: { 10820 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 10821 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 10822 AllowOnePastEnd > 0); 10823 return; 10824 } 10825 case Stmt::OMPArraySectionExprClass: { 10826 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 10827 if (ASE->getLowerBound()) 10828 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 10829 /*ASE=*/nullptr, AllowOnePastEnd > 0); 10830 return; 10831 } 10832 case Stmt::UnaryOperatorClass: { 10833 // Only unwrap the * and & unary operators 10834 const UnaryOperator *UO = cast<UnaryOperator>(expr); 10835 expr = UO->getSubExpr(); 10836 switch (UO->getOpcode()) { 10837 case UO_AddrOf: 10838 AllowOnePastEnd++; 10839 break; 10840 case UO_Deref: 10841 AllowOnePastEnd--; 10842 break; 10843 default: 10844 return; 10845 } 10846 break; 10847 } 10848 case Stmt::ConditionalOperatorClass: { 10849 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 10850 if (const Expr *lhs = cond->getLHS()) 10851 CheckArrayAccess(lhs); 10852 if (const Expr *rhs = cond->getRHS()) 10853 CheckArrayAccess(rhs); 10854 return; 10855 } 10856 case Stmt::CXXOperatorCallExprClass: { 10857 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 10858 for (const auto *Arg : OCE->arguments()) 10859 CheckArrayAccess(Arg); 10860 return; 10861 } 10862 default: 10863 return; 10864 } 10865 } 10866 } 10867 10868 //===--- CHECK: Objective-C retain cycles ----------------------------------// 10869 10870 namespace { 10871 struct RetainCycleOwner { 10872 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 10873 VarDecl *Variable; 10874 SourceRange Range; 10875 SourceLocation Loc; 10876 bool Indirect; 10877 10878 void setLocsFrom(Expr *e) { 10879 Loc = e->getExprLoc(); 10880 Range = e->getSourceRange(); 10881 } 10882 }; 10883 } // end anonymous namespace 10884 10885 /// Consider whether capturing the given variable can possibly lead to 10886 /// a retain cycle. 10887 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 10888 // In ARC, it's captured strongly iff the variable has __strong 10889 // lifetime. In MRR, it's captured strongly if the variable is 10890 // __block and has an appropriate type. 10891 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10892 return false; 10893 10894 owner.Variable = var; 10895 if (ref) 10896 owner.setLocsFrom(ref); 10897 return true; 10898 } 10899 10900 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 10901 while (true) { 10902 e = e->IgnoreParens(); 10903 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 10904 switch (cast->getCastKind()) { 10905 case CK_BitCast: 10906 case CK_LValueBitCast: 10907 case CK_LValueToRValue: 10908 case CK_ARCReclaimReturnedObject: 10909 e = cast->getSubExpr(); 10910 continue; 10911 10912 default: 10913 return false; 10914 } 10915 } 10916 10917 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 10918 ObjCIvarDecl *ivar = ref->getDecl(); 10919 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10920 return false; 10921 10922 // Try to find a retain cycle in the base. 10923 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 10924 return false; 10925 10926 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 10927 owner.Indirect = true; 10928 return true; 10929 } 10930 10931 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 10932 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 10933 if (!var) return false; 10934 return considerVariable(var, ref, owner); 10935 } 10936 10937 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 10938 if (member->isArrow()) return false; 10939 10940 // Don't count this as an indirect ownership. 10941 e = member->getBase(); 10942 continue; 10943 } 10944 10945 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 10946 // Only pay attention to pseudo-objects on property references. 10947 ObjCPropertyRefExpr *pre 10948 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 10949 ->IgnoreParens()); 10950 if (!pre) return false; 10951 if (pre->isImplicitProperty()) return false; 10952 ObjCPropertyDecl *property = pre->getExplicitProperty(); 10953 if (!property->isRetaining() && 10954 !(property->getPropertyIvarDecl() && 10955 property->getPropertyIvarDecl()->getType() 10956 .getObjCLifetime() == Qualifiers::OCL_Strong)) 10957 return false; 10958 10959 owner.Indirect = true; 10960 if (pre->isSuperReceiver()) { 10961 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 10962 if (!owner.Variable) 10963 return false; 10964 owner.Loc = pre->getLocation(); 10965 owner.Range = pre->getSourceRange(); 10966 return true; 10967 } 10968 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 10969 ->getSourceExpr()); 10970 continue; 10971 } 10972 10973 // Array ivars? 10974 10975 return false; 10976 } 10977 } 10978 10979 namespace { 10980 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 10981 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 10982 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 10983 Context(Context), Variable(variable), Capturer(nullptr), 10984 VarWillBeReased(false) {} 10985 ASTContext &Context; 10986 VarDecl *Variable; 10987 Expr *Capturer; 10988 bool VarWillBeReased; 10989 10990 void VisitDeclRefExpr(DeclRefExpr *ref) { 10991 if (ref->getDecl() == Variable && !Capturer) 10992 Capturer = ref; 10993 } 10994 10995 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 10996 if (Capturer) return; 10997 Visit(ref->getBase()); 10998 if (Capturer && ref->isFreeIvar()) 10999 Capturer = ref; 11000 } 11001 11002 void VisitBlockExpr(BlockExpr *block) { 11003 // Look inside nested blocks 11004 if (block->getBlockDecl()->capturesVariable(Variable)) 11005 Visit(block->getBlockDecl()->getBody()); 11006 } 11007 11008 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11009 if (Capturer) return; 11010 if (OVE->getSourceExpr()) 11011 Visit(OVE->getSourceExpr()); 11012 } 11013 void VisitBinaryOperator(BinaryOperator *BinOp) { 11014 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11015 return; 11016 Expr *LHS = BinOp->getLHS(); 11017 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11018 if (DRE->getDecl() != Variable) 11019 return; 11020 if (Expr *RHS = BinOp->getRHS()) { 11021 RHS = RHS->IgnoreParenCasts(); 11022 llvm::APSInt Value; 11023 VarWillBeReased = 11024 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11025 } 11026 } 11027 } 11028 }; 11029 } // end anonymous namespace 11030 11031 /// Check whether the given argument is a block which captures a 11032 /// variable. 11033 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11034 assert(owner.Variable && owner.Loc.isValid()); 11035 11036 e = e->IgnoreParenCasts(); 11037 11038 // Look through [^{...} copy] and Block_copy(^{...}). 11039 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11040 Selector Cmd = ME->getSelector(); 11041 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11042 e = ME->getInstanceReceiver(); 11043 if (!e) 11044 return nullptr; 11045 e = e->IgnoreParenCasts(); 11046 } 11047 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11048 if (CE->getNumArgs() == 1) { 11049 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11050 if (Fn) { 11051 const IdentifierInfo *FnI = Fn->getIdentifier(); 11052 if (FnI && FnI->isStr("_Block_copy")) { 11053 e = CE->getArg(0)->IgnoreParenCasts(); 11054 } 11055 } 11056 } 11057 } 11058 11059 BlockExpr *block = dyn_cast<BlockExpr>(e); 11060 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11061 return nullptr; 11062 11063 FindCaptureVisitor visitor(S.Context, owner.Variable); 11064 visitor.Visit(block->getBlockDecl()->getBody()); 11065 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11066 } 11067 11068 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11069 RetainCycleOwner &owner) { 11070 assert(capturer); 11071 assert(owner.Variable && owner.Loc.isValid()); 11072 11073 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11074 << owner.Variable << capturer->getSourceRange(); 11075 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11076 << owner.Indirect << owner.Range; 11077 } 11078 11079 /// Check for a keyword selector that starts with the word 'add' or 11080 /// 'set'. 11081 static bool isSetterLikeSelector(Selector sel) { 11082 if (sel.isUnarySelector()) return false; 11083 11084 StringRef str = sel.getNameForSlot(0); 11085 while (!str.empty() && str.front() == '_') str = str.substr(1); 11086 if (str.startswith("set")) 11087 str = str.substr(3); 11088 else if (str.startswith("add")) { 11089 // Specially whitelist 'addOperationWithBlock:'. 11090 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 11091 return false; 11092 str = str.substr(3); 11093 } 11094 else 11095 return false; 11096 11097 if (str.empty()) return true; 11098 return !isLowercase(str.front()); 11099 } 11100 11101 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 11102 ObjCMessageExpr *Message) { 11103 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 11104 Message->getReceiverInterface(), 11105 NSAPI::ClassId_NSMutableArray); 11106 if (!IsMutableArray) { 11107 return None; 11108 } 11109 11110 Selector Sel = Message->getSelector(); 11111 11112 Optional<NSAPI::NSArrayMethodKind> MKOpt = 11113 S.NSAPIObj->getNSArrayMethodKind(Sel); 11114 if (!MKOpt) { 11115 return None; 11116 } 11117 11118 NSAPI::NSArrayMethodKind MK = *MKOpt; 11119 11120 switch (MK) { 11121 case NSAPI::NSMutableArr_addObject: 11122 case NSAPI::NSMutableArr_insertObjectAtIndex: 11123 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 11124 return 0; 11125 case NSAPI::NSMutableArr_replaceObjectAtIndex: 11126 return 1; 11127 11128 default: 11129 return None; 11130 } 11131 11132 return None; 11133 } 11134 11135 static 11136 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 11137 ObjCMessageExpr *Message) { 11138 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 11139 Message->getReceiverInterface(), 11140 NSAPI::ClassId_NSMutableDictionary); 11141 if (!IsMutableDictionary) { 11142 return None; 11143 } 11144 11145 Selector Sel = Message->getSelector(); 11146 11147 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 11148 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 11149 if (!MKOpt) { 11150 return None; 11151 } 11152 11153 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 11154 11155 switch (MK) { 11156 case NSAPI::NSMutableDict_setObjectForKey: 11157 case NSAPI::NSMutableDict_setValueForKey: 11158 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 11159 return 0; 11160 11161 default: 11162 return None; 11163 } 11164 11165 return None; 11166 } 11167 11168 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 11169 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 11170 Message->getReceiverInterface(), 11171 NSAPI::ClassId_NSMutableSet); 11172 11173 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 11174 Message->getReceiverInterface(), 11175 NSAPI::ClassId_NSMutableOrderedSet); 11176 if (!IsMutableSet && !IsMutableOrderedSet) { 11177 return None; 11178 } 11179 11180 Selector Sel = Message->getSelector(); 11181 11182 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 11183 if (!MKOpt) { 11184 return None; 11185 } 11186 11187 NSAPI::NSSetMethodKind MK = *MKOpt; 11188 11189 switch (MK) { 11190 case NSAPI::NSMutableSet_addObject: 11191 case NSAPI::NSOrderedSet_setObjectAtIndex: 11192 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 11193 case NSAPI::NSOrderedSet_insertObjectAtIndex: 11194 return 0; 11195 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 11196 return 1; 11197 } 11198 11199 return None; 11200 } 11201 11202 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 11203 if (!Message->isInstanceMessage()) { 11204 return; 11205 } 11206 11207 Optional<int> ArgOpt; 11208 11209 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 11210 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 11211 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 11212 return; 11213 } 11214 11215 int ArgIndex = *ArgOpt; 11216 11217 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 11218 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 11219 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 11220 } 11221 11222 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 11223 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11224 if (ArgRE->isObjCSelfExpr()) { 11225 Diag(Message->getSourceRange().getBegin(), 11226 diag::warn_objc_circular_container) 11227 << ArgRE->getDecl()->getName() << StringRef("super"); 11228 } 11229 } 11230 } else { 11231 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 11232 11233 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 11234 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 11235 } 11236 11237 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 11238 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11239 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 11240 ValueDecl *Decl = ReceiverRE->getDecl(); 11241 Diag(Message->getSourceRange().getBegin(), 11242 diag::warn_objc_circular_container) 11243 << Decl->getName() << Decl->getName(); 11244 if (!ArgRE->isObjCSelfExpr()) { 11245 Diag(Decl->getLocation(), 11246 diag::note_objc_circular_container_declared_here) 11247 << Decl->getName(); 11248 } 11249 } 11250 } 11251 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 11252 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 11253 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 11254 ObjCIvarDecl *Decl = IvarRE->getDecl(); 11255 Diag(Message->getSourceRange().getBegin(), 11256 diag::warn_objc_circular_container) 11257 << Decl->getName() << Decl->getName(); 11258 Diag(Decl->getLocation(), 11259 diag::note_objc_circular_container_declared_here) 11260 << Decl->getName(); 11261 } 11262 } 11263 } 11264 } 11265 } 11266 11267 /// Check a message send to see if it's likely to cause a retain cycle. 11268 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11269 // Only check instance methods whose selector looks like a setter. 11270 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 11271 return; 11272 11273 // Try to find a variable that the receiver is strongly owned by. 11274 RetainCycleOwner owner; 11275 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 11276 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 11277 return; 11278 } else { 11279 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 11280 owner.Variable = getCurMethodDecl()->getSelfDecl(); 11281 owner.Loc = msg->getSuperLoc(); 11282 owner.Range = msg->getSuperLoc(); 11283 } 11284 11285 // Check whether the receiver is captured by any of the arguments. 11286 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 11287 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 11288 return diagnoseRetainCycle(*this, capturer, owner); 11289 } 11290 11291 /// Check a property assign to see if it's likely to cause a retain cycle. 11292 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 11293 RetainCycleOwner owner; 11294 if (!findRetainCycleOwner(*this, receiver, owner)) 11295 return; 11296 11297 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 11298 diagnoseRetainCycle(*this, capturer, owner); 11299 } 11300 11301 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 11302 RetainCycleOwner Owner; 11303 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 11304 return; 11305 11306 // Because we don't have an expression for the variable, we have to set the 11307 // location explicitly here. 11308 Owner.Loc = Var->getLocation(); 11309 Owner.Range = Var->getSourceRange(); 11310 11311 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 11312 diagnoseRetainCycle(*this, Capturer, Owner); 11313 } 11314 11315 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 11316 Expr *RHS, bool isProperty) { 11317 // Check if RHS is an Objective-C object literal, which also can get 11318 // immediately zapped in a weak reference. Note that we explicitly 11319 // allow ObjCStringLiterals, since those are designed to never really die. 11320 RHS = RHS->IgnoreParenImpCasts(); 11321 11322 // This enum needs to match with the 'select' in 11323 // warn_objc_arc_literal_assign (off-by-1). 11324 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 11325 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 11326 return false; 11327 11328 S.Diag(Loc, diag::warn_arc_literal_assign) 11329 << (unsigned) Kind 11330 << (isProperty ? 0 : 1) 11331 << RHS->getSourceRange(); 11332 11333 return true; 11334 } 11335 11336 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 11337 Qualifiers::ObjCLifetime LT, 11338 Expr *RHS, bool isProperty) { 11339 // Strip off any implicit cast added to get to the one ARC-specific. 11340 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11341 if (cast->getCastKind() == CK_ARCConsumeObject) { 11342 S.Diag(Loc, diag::warn_arc_retained_assign) 11343 << (LT == Qualifiers::OCL_ExplicitNone) 11344 << (isProperty ? 0 : 1) 11345 << RHS->getSourceRange(); 11346 return true; 11347 } 11348 RHS = cast->getSubExpr(); 11349 } 11350 11351 if (LT == Qualifiers::OCL_Weak && 11352 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11353 return true; 11354 11355 return false; 11356 } 11357 11358 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11359 QualType LHS, Expr *RHS) { 11360 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11361 11362 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11363 return false; 11364 11365 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11366 return true; 11367 11368 return false; 11369 } 11370 11371 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11372 Expr *LHS, Expr *RHS) { 11373 QualType LHSType; 11374 // PropertyRef on LHS type need be directly obtained from 11375 // its declaration as it has a PseudoType. 11376 ObjCPropertyRefExpr *PRE 11377 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11378 if (PRE && !PRE->isImplicitProperty()) { 11379 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11380 if (PD) 11381 LHSType = PD->getType(); 11382 } 11383 11384 if (LHSType.isNull()) 11385 LHSType = LHS->getType(); 11386 11387 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11388 11389 if (LT == Qualifiers::OCL_Weak) { 11390 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11391 getCurFunction()->markSafeWeakUse(LHS); 11392 } 11393 11394 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11395 return; 11396 11397 // FIXME. Check for other life times. 11398 if (LT != Qualifiers::OCL_None) 11399 return; 11400 11401 if (PRE) { 11402 if (PRE->isImplicitProperty()) 11403 return; 11404 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11405 if (!PD) 11406 return; 11407 11408 unsigned Attributes = PD->getPropertyAttributes(); 11409 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11410 // when 'assign' attribute was not explicitly specified 11411 // by user, ignore it and rely on property type itself 11412 // for lifetime info. 11413 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11414 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11415 LHSType->isObjCRetainableType()) 11416 return; 11417 11418 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11419 if (cast->getCastKind() == CK_ARCConsumeObject) { 11420 Diag(Loc, diag::warn_arc_retained_property_assign) 11421 << RHS->getSourceRange(); 11422 return; 11423 } 11424 RHS = cast->getSubExpr(); 11425 } 11426 } 11427 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11428 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11429 return; 11430 } 11431 } 11432 } 11433 11434 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11435 11436 namespace { 11437 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11438 SourceLocation StmtLoc, 11439 const NullStmt *Body) { 11440 // Do not warn if the body is a macro that expands to nothing, e.g: 11441 // 11442 // #define CALL(x) 11443 // if (condition) 11444 // CALL(0); 11445 // 11446 if (Body->hasLeadingEmptyMacro()) 11447 return false; 11448 11449 // Get line numbers of statement and body. 11450 bool StmtLineInvalid; 11451 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11452 &StmtLineInvalid); 11453 if (StmtLineInvalid) 11454 return false; 11455 11456 bool BodyLineInvalid; 11457 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11458 &BodyLineInvalid); 11459 if (BodyLineInvalid) 11460 return false; 11461 11462 // Warn if null statement and body are on the same line. 11463 if (StmtLine != BodyLine) 11464 return false; 11465 11466 return true; 11467 } 11468 } // end anonymous namespace 11469 11470 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11471 const Stmt *Body, 11472 unsigned DiagID) { 11473 // Since this is a syntactic check, don't emit diagnostic for template 11474 // instantiations, this just adds noise. 11475 if (CurrentInstantiationScope) 11476 return; 11477 11478 // The body should be a null statement. 11479 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11480 if (!NBody) 11481 return; 11482 11483 // Do the usual checks. 11484 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11485 return; 11486 11487 Diag(NBody->getSemiLoc(), DiagID); 11488 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11489 } 11490 11491 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11492 const Stmt *PossibleBody) { 11493 assert(!CurrentInstantiationScope); // Ensured by caller 11494 11495 SourceLocation StmtLoc; 11496 const Stmt *Body; 11497 unsigned DiagID; 11498 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11499 StmtLoc = FS->getRParenLoc(); 11500 Body = FS->getBody(); 11501 DiagID = diag::warn_empty_for_body; 11502 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11503 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11504 Body = WS->getBody(); 11505 DiagID = diag::warn_empty_while_body; 11506 } else 11507 return; // Neither `for' nor `while'. 11508 11509 // The body should be a null statement. 11510 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11511 if (!NBody) 11512 return; 11513 11514 // Skip expensive checks if diagnostic is disabled. 11515 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11516 return; 11517 11518 // Do the usual checks. 11519 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11520 return; 11521 11522 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11523 // noise level low, emit diagnostics only if for/while is followed by a 11524 // CompoundStmt, e.g.: 11525 // for (int i = 0; i < n; i++); 11526 // { 11527 // a(i); 11528 // } 11529 // or if for/while is followed by a statement with more indentation 11530 // than for/while itself: 11531 // for (int i = 0; i < n; i++); 11532 // a(i); 11533 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11534 if (!ProbableTypo) { 11535 bool BodyColInvalid; 11536 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11537 PossibleBody->getLocStart(), 11538 &BodyColInvalid); 11539 if (BodyColInvalid) 11540 return; 11541 11542 bool StmtColInvalid; 11543 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11544 S->getLocStart(), 11545 &StmtColInvalid); 11546 if (StmtColInvalid) 11547 return; 11548 11549 if (BodyCol > StmtCol) 11550 ProbableTypo = true; 11551 } 11552 11553 if (ProbableTypo) { 11554 Diag(NBody->getSemiLoc(), DiagID); 11555 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11556 } 11557 } 11558 11559 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11560 11561 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11562 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11563 SourceLocation OpLoc) { 11564 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11565 return; 11566 11567 if (inTemplateInstantiation()) 11568 return; 11569 11570 // Strip parens and casts away. 11571 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11572 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11573 11574 // Check for a call expression 11575 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11576 if (!CE || CE->getNumArgs() != 1) 11577 return; 11578 11579 // Check for a call to std::move 11580 const FunctionDecl *FD = CE->getDirectCallee(); 11581 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 11582 !FD->getIdentifier()->isStr("move")) 11583 return; 11584 11585 // Get argument from std::move 11586 RHSExpr = CE->getArg(0); 11587 11588 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11589 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11590 11591 // Two DeclRefExpr's, check that the decls are the same. 11592 if (LHSDeclRef && RHSDeclRef) { 11593 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11594 return; 11595 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11596 RHSDeclRef->getDecl()->getCanonicalDecl()) 11597 return; 11598 11599 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11600 << LHSExpr->getSourceRange() 11601 << RHSExpr->getSourceRange(); 11602 return; 11603 } 11604 11605 // Member variables require a different approach to check for self moves. 11606 // MemberExpr's are the same if every nested MemberExpr refers to the same 11607 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11608 // the base Expr's are CXXThisExpr's. 11609 const Expr *LHSBase = LHSExpr; 11610 const Expr *RHSBase = RHSExpr; 11611 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11612 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11613 if (!LHSME || !RHSME) 11614 return; 11615 11616 while (LHSME && RHSME) { 11617 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11618 RHSME->getMemberDecl()->getCanonicalDecl()) 11619 return; 11620 11621 LHSBase = LHSME->getBase(); 11622 RHSBase = RHSME->getBase(); 11623 LHSME = dyn_cast<MemberExpr>(LHSBase); 11624 RHSME = dyn_cast<MemberExpr>(RHSBase); 11625 } 11626 11627 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11628 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11629 if (LHSDeclRef && RHSDeclRef) { 11630 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11631 return; 11632 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11633 RHSDeclRef->getDecl()->getCanonicalDecl()) 11634 return; 11635 11636 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11637 << LHSExpr->getSourceRange() 11638 << RHSExpr->getSourceRange(); 11639 return; 11640 } 11641 11642 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11643 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11644 << LHSExpr->getSourceRange() 11645 << RHSExpr->getSourceRange(); 11646 } 11647 11648 //===--- Layout compatibility ----------------------------------------------// 11649 11650 namespace { 11651 11652 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11653 11654 /// \brief Check if two enumeration types are layout-compatible. 11655 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11656 // C++11 [dcl.enum] p8: 11657 // Two enumeration types are layout-compatible if they have the same 11658 // underlying type. 11659 return ED1->isComplete() && ED2->isComplete() && 11660 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11661 } 11662 11663 /// \brief Check if two fields are layout-compatible. 11664 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11665 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11666 return false; 11667 11668 if (Field1->isBitField() != Field2->isBitField()) 11669 return false; 11670 11671 if (Field1->isBitField()) { 11672 // Make sure that the bit-fields are the same length. 11673 unsigned Bits1 = Field1->getBitWidthValue(C); 11674 unsigned Bits2 = Field2->getBitWidthValue(C); 11675 11676 if (Bits1 != Bits2) 11677 return false; 11678 } 11679 11680 return true; 11681 } 11682 11683 /// \brief Check if two standard-layout structs are layout-compatible. 11684 /// (C++11 [class.mem] p17) 11685 bool isLayoutCompatibleStruct(ASTContext &C, 11686 RecordDecl *RD1, 11687 RecordDecl *RD2) { 11688 // If both records are C++ classes, check that base classes match. 11689 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11690 // If one of records is a CXXRecordDecl we are in C++ mode, 11691 // thus the other one is a CXXRecordDecl, too. 11692 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11693 // Check number of base classes. 11694 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11695 return false; 11696 11697 // Check the base classes. 11698 for (CXXRecordDecl::base_class_const_iterator 11699 Base1 = D1CXX->bases_begin(), 11700 BaseEnd1 = D1CXX->bases_end(), 11701 Base2 = D2CXX->bases_begin(); 11702 Base1 != BaseEnd1; 11703 ++Base1, ++Base2) { 11704 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11705 return false; 11706 } 11707 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11708 // If only RD2 is a C++ class, it should have zero base classes. 11709 if (D2CXX->getNumBases() > 0) 11710 return false; 11711 } 11712 11713 // Check the fields. 11714 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11715 Field2End = RD2->field_end(), 11716 Field1 = RD1->field_begin(), 11717 Field1End = RD1->field_end(); 11718 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11719 if (!isLayoutCompatible(C, *Field1, *Field2)) 11720 return false; 11721 } 11722 if (Field1 != Field1End || Field2 != Field2End) 11723 return false; 11724 11725 return true; 11726 } 11727 11728 /// \brief Check if two standard-layout unions are layout-compatible. 11729 /// (C++11 [class.mem] p18) 11730 bool isLayoutCompatibleUnion(ASTContext &C, 11731 RecordDecl *RD1, 11732 RecordDecl *RD2) { 11733 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11734 for (auto *Field2 : RD2->fields()) 11735 UnmatchedFields.insert(Field2); 11736 11737 for (auto *Field1 : RD1->fields()) { 11738 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11739 I = UnmatchedFields.begin(), 11740 E = UnmatchedFields.end(); 11741 11742 for ( ; I != E; ++I) { 11743 if (isLayoutCompatible(C, Field1, *I)) { 11744 bool Result = UnmatchedFields.erase(*I); 11745 (void) Result; 11746 assert(Result); 11747 break; 11748 } 11749 } 11750 if (I == E) 11751 return false; 11752 } 11753 11754 return UnmatchedFields.empty(); 11755 } 11756 11757 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11758 if (RD1->isUnion() != RD2->isUnion()) 11759 return false; 11760 11761 if (RD1->isUnion()) 11762 return isLayoutCompatibleUnion(C, RD1, RD2); 11763 else 11764 return isLayoutCompatibleStruct(C, RD1, RD2); 11765 } 11766 11767 /// \brief Check if two types are layout-compatible in C++11 sense. 11768 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 11769 if (T1.isNull() || T2.isNull()) 11770 return false; 11771 11772 // C++11 [basic.types] p11: 11773 // If two types T1 and T2 are the same type, then T1 and T2 are 11774 // layout-compatible types. 11775 if (C.hasSameType(T1, T2)) 11776 return true; 11777 11778 T1 = T1.getCanonicalType().getUnqualifiedType(); 11779 T2 = T2.getCanonicalType().getUnqualifiedType(); 11780 11781 const Type::TypeClass TC1 = T1->getTypeClass(); 11782 const Type::TypeClass TC2 = T2->getTypeClass(); 11783 11784 if (TC1 != TC2) 11785 return false; 11786 11787 if (TC1 == Type::Enum) { 11788 return isLayoutCompatible(C, 11789 cast<EnumType>(T1)->getDecl(), 11790 cast<EnumType>(T2)->getDecl()); 11791 } else if (TC1 == Type::Record) { 11792 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 11793 return false; 11794 11795 return isLayoutCompatible(C, 11796 cast<RecordType>(T1)->getDecl(), 11797 cast<RecordType>(T2)->getDecl()); 11798 } 11799 11800 return false; 11801 } 11802 } // end anonymous namespace 11803 11804 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 11805 11806 namespace { 11807 /// \brief Given a type tag expression find the type tag itself. 11808 /// 11809 /// \param TypeExpr Type tag expression, as it appears in user's code. 11810 /// 11811 /// \param VD Declaration of an identifier that appears in a type tag. 11812 /// 11813 /// \param MagicValue Type tag magic value. 11814 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 11815 const ValueDecl **VD, uint64_t *MagicValue) { 11816 while(true) { 11817 if (!TypeExpr) 11818 return false; 11819 11820 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 11821 11822 switch (TypeExpr->getStmtClass()) { 11823 case Stmt::UnaryOperatorClass: { 11824 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 11825 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 11826 TypeExpr = UO->getSubExpr(); 11827 continue; 11828 } 11829 return false; 11830 } 11831 11832 case Stmt::DeclRefExprClass: { 11833 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 11834 *VD = DRE->getDecl(); 11835 return true; 11836 } 11837 11838 case Stmt::IntegerLiteralClass: { 11839 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 11840 llvm::APInt MagicValueAPInt = IL->getValue(); 11841 if (MagicValueAPInt.getActiveBits() <= 64) { 11842 *MagicValue = MagicValueAPInt.getZExtValue(); 11843 return true; 11844 } else 11845 return false; 11846 } 11847 11848 case Stmt::BinaryConditionalOperatorClass: 11849 case Stmt::ConditionalOperatorClass: { 11850 const AbstractConditionalOperator *ACO = 11851 cast<AbstractConditionalOperator>(TypeExpr); 11852 bool Result; 11853 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 11854 if (Result) 11855 TypeExpr = ACO->getTrueExpr(); 11856 else 11857 TypeExpr = ACO->getFalseExpr(); 11858 continue; 11859 } 11860 return false; 11861 } 11862 11863 case Stmt::BinaryOperatorClass: { 11864 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 11865 if (BO->getOpcode() == BO_Comma) { 11866 TypeExpr = BO->getRHS(); 11867 continue; 11868 } 11869 return false; 11870 } 11871 11872 default: 11873 return false; 11874 } 11875 } 11876 } 11877 11878 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 11879 /// 11880 /// \param TypeExpr Expression that specifies a type tag. 11881 /// 11882 /// \param MagicValues Registered magic values. 11883 /// 11884 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 11885 /// kind. 11886 /// 11887 /// \param TypeInfo Information about the corresponding C type. 11888 /// 11889 /// \returns true if the corresponding C type was found. 11890 bool GetMatchingCType( 11891 const IdentifierInfo *ArgumentKind, 11892 const Expr *TypeExpr, const ASTContext &Ctx, 11893 const llvm::DenseMap<Sema::TypeTagMagicValue, 11894 Sema::TypeTagData> *MagicValues, 11895 bool &FoundWrongKind, 11896 Sema::TypeTagData &TypeInfo) { 11897 FoundWrongKind = false; 11898 11899 // Variable declaration that has type_tag_for_datatype attribute. 11900 const ValueDecl *VD = nullptr; 11901 11902 uint64_t MagicValue; 11903 11904 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 11905 return false; 11906 11907 if (VD) { 11908 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 11909 if (I->getArgumentKind() != ArgumentKind) { 11910 FoundWrongKind = true; 11911 return false; 11912 } 11913 TypeInfo.Type = I->getMatchingCType(); 11914 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 11915 TypeInfo.MustBeNull = I->getMustBeNull(); 11916 return true; 11917 } 11918 return false; 11919 } 11920 11921 if (!MagicValues) 11922 return false; 11923 11924 llvm::DenseMap<Sema::TypeTagMagicValue, 11925 Sema::TypeTagData>::const_iterator I = 11926 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 11927 if (I == MagicValues->end()) 11928 return false; 11929 11930 TypeInfo = I->second; 11931 return true; 11932 } 11933 } // end anonymous namespace 11934 11935 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 11936 uint64_t MagicValue, QualType Type, 11937 bool LayoutCompatible, 11938 bool MustBeNull) { 11939 if (!TypeTagForDatatypeMagicValues) 11940 TypeTagForDatatypeMagicValues.reset( 11941 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 11942 11943 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 11944 (*TypeTagForDatatypeMagicValues)[Magic] = 11945 TypeTagData(Type, LayoutCompatible, MustBeNull); 11946 } 11947 11948 namespace { 11949 bool IsSameCharType(QualType T1, QualType T2) { 11950 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 11951 if (!BT1) 11952 return false; 11953 11954 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 11955 if (!BT2) 11956 return false; 11957 11958 BuiltinType::Kind T1Kind = BT1->getKind(); 11959 BuiltinType::Kind T2Kind = BT2->getKind(); 11960 11961 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 11962 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 11963 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 11964 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 11965 } 11966 } // end anonymous namespace 11967 11968 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 11969 const Expr * const *ExprArgs) { 11970 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 11971 bool IsPointerAttr = Attr->getIsPointer(); 11972 11973 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 11974 bool FoundWrongKind; 11975 TypeTagData TypeInfo; 11976 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 11977 TypeTagForDatatypeMagicValues.get(), 11978 FoundWrongKind, TypeInfo)) { 11979 if (FoundWrongKind) 11980 Diag(TypeTagExpr->getExprLoc(), 11981 diag::warn_type_tag_for_datatype_wrong_kind) 11982 << TypeTagExpr->getSourceRange(); 11983 return; 11984 } 11985 11986 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 11987 if (IsPointerAttr) { 11988 // Skip implicit cast of pointer to `void *' (as a function argument). 11989 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 11990 if (ICE->getType()->isVoidPointerType() && 11991 ICE->getCastKind() == CK_BitCast) 11992 ArgumentExpr = ICE->getSubExpr(); 11993 } 11994 QualType ArgumentType = ArgumentExpr->getType(); 11995 11996 // Passing a `void*' pointer shouldn't trigger a warning. 11997 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 11998 return; 11999 12000 if (TypeInfo.MustBeNull) { 12001 // Type tag with matching void type requires a null pointer. 12002 if (!ArgumentExpr->isNullPointerConstant(Context, 12003 Expr::NPC_ValueDependentIsNotNull)) { 12004 Diag(ArgumentExpr->getExprLoc(), 12005 diag::warn_type_safety_null_pointer_required) 12006 << ArgumentKind->getName() 12007 << ArgumentExpr->getSourceRange() 12008 << TypeTagExpr->getSourceRange(); 12009 } 12010 return; 12011 } 12012 12013 QualType RequiredType = TypeInfo.Type; 12014 if (IsPointerAttr) 12015 RequiredType = Context.getPointerType(RequiredType); 12016 12017 bool mismatch = false; 12018 if (!TypeInfo.LayoutCompatible) { 12019 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12020 12021 // C++11 [basic.fundamental] p1: 12022 // Plain char, signed char, and unsigned char are three distinct types. 12023 // 12024 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12025 // char' depending on the current char signedness mode. 12026 if (mismatch) 12027 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12028 RequiredType->getPointeeType())) || 12029 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12030 mismatch = false; 12031 } else 12032 if (IsPointerAttr) 12033 mismatch = !isLayoutCompatible(Context, 12034 ArgumentType->getPointeeType(), 12035 RequiredType->getPointeeType()); 12036 else 12037 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12038 12039 if (mismatch) 12040 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12041 << ArgumentType << ArgumentKind 12042 << TypeInfo.LayoutCompatible << RequiredType 12043 << ArgumentExpr->getSourceRange() 12044 << TypeTagExpr->getSourceRange(); 12045 } 12046 12047 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12048 CharUnits Alignment) { 12049 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12050 } 12051 12052 void Sema::DiagnoseMisalignedMembers() { 12053 for (MisalignedMember &m : MisalignedMembers) { 12054 const NamedDecl *ND = m.RD; 12055 if (ND->getName().empty()) { 12056 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12057 ND = TD; 12058 } 12059 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12060 << m.MD << ND << m.E->getSourceRange(); 12061 } 12062 MisalignedMembers.clear(); 12063 } 12064 12065 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12066 E = E->IgnoreParens(); 12067 if (!T->isPointerType() && !T->isIntegerType()) 12068 return; 12069 if (isa<UnaryOperator>(E) && 12070 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 12071 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 12072 if (isa<MemberExpr>(Op)) { 12073 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 12074 MisalignedMember(Op)); 12075 if (MA != MisalignedMembers.end() && 12076 (T->isIntegerType() || 12077 (T->isPointerType() && 12078 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment))) 12079 MisalignedMembers.erase(MA); 12080 } 12081 } 12082 } 12083 12084 void Sema::RefersToMemberWithReducedAlignment( 12085 Expr *E, 12086 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12087 Action) { 12088 const auto *ME = dyn_cast<MemberExpr>(E); 12089 if (!ME) 12090 return; 12091 12092 // No need to check expressions with an __unaligned-qualified type. 12093 if (E->getType().getQualifiers().hasUnaligned()) 12094 return; 12095 12096 // For a chain of MemberExpr like "a.b.c.d" this list 12097 // will keep FieldDecl's like [d, c, b]. 12098 SmallVector<FieldDecl *, 4> ReverseMemberChain; 12099 const MemberExpr *TopME = nullptr; 12100 bool AnyIsPacked = false; 12101 do { 12102 QualType BaseType = ME->getBase()->getType(); 12103 if (ME->isArrow()) 12104 BaseType = BaseType->getPointeeType(); 12105 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 12106 if (RD->isInvalidDecl()) 12107 return; 12108 12109 ValueDecl *MD = ME->getMemberDecl(); 12110 auto *FD = dyn_cast<FieldDecl>(MD); 12111 // We do not care about non-data members. 12112 if (!FD || FD->isInvalidDecl()) 12113 return; 12114 12115 AnyIsPacked = 12116 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 12117 ReverseMemberChain.push_back(FD); 12118 12119 TopME = ME; 12120 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 12121 } while (ME); 12122 assert(TopME && "We did not compute a topmost MemberExpr!"); 12123 12124 // Not the scope of this diagnostic. 12125 if (!AnyIsPacked) 12126 return; 12127 12128 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 12129 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 12130 // TODO: The innermost base of the member expression may be too complicated. 12131 // For now, just disregard these cases. This is left for future 12132 // improvement. 12133 if (!DRE && !isa<CXXThisExpr>(TopBase)) 12134 return; 12135 12136 // Alignment expected by the whole expression. 12137 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 12138 12139 // No need to do anything else with this case. 12140 if (ExpectedAlignment.isOne()) 12141 return; 12142 12143 // Synthesize offset of the whole access. 12144 CharUnits Offset; 12145 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 12146 I++) { 12147 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 12148 } 12149 12150 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 12151 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 12152 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 12153 12154 // The base expression of the innermost MemberExpr may give 12155 // stronger guarantees than the class containing the member. 12156 if (DRE && !TopME->isArrow()) { 12157 const ValueDecl *VD = DRE->getDecl(); 12158 if (!VD->getType()->isReferenceType()) 12159 CompleteObjectAlignment = 12160 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 12161 } 12162 12163 // Check if the synthesized offset fulfills the alignment. 12164 if (Offset % ExpectedAlignment != 0 || 12165 // It may fulfill the offset it but the effective alignment may still be 12166 // lower than the expected expression alignment. 12167 CompleteObjectAlignment < ExpectedAlignment) { 12168 // If this happens, we want to determine a sensible culprit of this. 12169 // Intuitively, watching the chain of member expressions from right to 12170 // left, we start with the required alignment (as required by the field 12171 // type) but some packed attribute in that chain has reduced the alignment. 12172 // It may happen that another packed structure increases it again. But if 12173 // we are here such increase has not been enough. So pointing the first 12174 // FieldDecl that either is packed or else its RecordDecl is, 12175 // seems reasonable. 12176 FieldDecl *FD = nullptr; 12177 CharUnits Alignment; 12178 for (FieldDecl *FDI : ReverseMemberChain) { 12179 if (FDI->hasAttr<PackedAttr>() || 12180 FDI->getParent()->hasAttr<PackedAttr>()) { 12181 FD = FDI; 12182 Alignment = std::min( 12183 Context.getTypeAlignInChars(FD->getType()), 12184 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 12185 break; 12186 } 12187 } 12188 assert(FD && "We did not find a packed FieldDecl!"); 12189 Action(E, FD->getParent(), FD, Alignment); 12190 } 12191 } 12192 12193 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 12194 using namespace std::placeholders; 12195 RefersToMemberWithReducedAlignment( 12196 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 12197 _2, _3, _4)); 12198 } 12199 12200