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_enqueue_kernel_expected_type) << "block"; 313 return true; 314 } 315 return checkOpenCLBlockArgs(S, BlockArg); 316 } 317 318 /// Diagnose integer type and any valid implicit conversion to it. 319 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 320 const QualType &IntType); 321 322 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 323 unsigned Start, unsigned End) { 324 bool IllegalParams = false; 325 for (unsigned I = Start; I <= End; ++I) 326 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 327 S.Context.getSizeType()); 328 return IllegalParams; 329 } 330 331 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 332 /// 'local void*' parameter of passed block. 333 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 334 Expr *BlockArg, 335 unsigned NumNonVarArgs) { 336 const BlockPointerType *BPT = 337 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 338 unsigned NumBlockParams = 339 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 340 unsigned TotalNumArgs = TheCall->getNumArgs(); 341 342 // For each argument passed to the block, a corresponding uint needs to 343 // be passed to describe the size of the local memory. 344 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 345 S.Diag(TheCall->getLocStart(), 346 diag::err_opencl_enqueue_kernel_local_size_args); 347 return true; 348 } 349 350 // Check that the sizes of the local memory are specified by integers. 351 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 352 TotalNumArgs - 1); 353 } 354 355 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 356 /// overload formats specified in Table 6.13.17.1. 357 /// int enqueue_kernel(queue_t queue, 358 /// kernel_enqueue_flags_t flags, 359 /// const ndrange_t ndrange, 360 /// void (^block)(void)) 361 /// int enqueue_kernel(queue_t queue, 362 /// kernel_enqueue_flags_t flags, 363 /// const ndrange_t ndrange, 364 /// uint num_events_in_wait_list, 365 /// clk_event_t *event_wait_list, 366 /// clk_event_t *event_ret, 367 /// void (^block)(void)) 368 /// int enqueue_kernel(queue_t queue, 369 /// kernel_enqueue_flags_t flags, 370 /// const ndrange_t ndrange, 371 /// void (^block)(local void*, ...), 372 /// uint size0, ...) 373 /// int enqueue_kernel(queue_t queue, 374 /// kernel_enqueue_flags_t flags, 375 /// const ndrange_t ndrange, 376 /// uint num_events_in_wait_list, 377 /// clk_event_t *event_wait_list, 378 /// clk_event_t *event_ret, 379 /// void (^block)(local void*, ...), 380 /// uint size0, ...) 381 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 382 unsigned NumArgs = TheCall->getNumArgs(); 383 384 if (NumArgs < 4) { 385 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 386 return true; 387 } 388 389 Expr *Arg0 = TheCall->getArg(0); 390 Expr *Arg1 = TheCall->getArg(1); 391 Expr *Arg2 = TheCall->getArg(2); 392 Expr *Arg3 = TheCall->getArg(3); 393 394 // First argument always needs to be a queue_t type. 395 if (!Arg0->getType()->isQueueT()) { 396 S.Diag(TheCall->getArg(0)->getLocStart(), 397 diag::err_opencl_enqueue_kernel_expected_type) 398 << S.Context.OCLQueueTy; 399 return true; 400 } 401 402 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 403 if (!Arg1->getType()->isIntegerType()) { 404 S.Diag(TheCall->getArg(1)->getLocStart(), 405 diag::err_opencl_enqueue_kernel_expected_type) 406 << "'kernel_enqueue_flags_t' (i.e. uint)"; 407 return true; 408 } 409 410 // Third argument is always an ndrange_t type. 411 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 412 S.Diag(TheCall->getArg(2)->getLocStart(), 413 diag::err_opencl_enqueue_kernel_expected_type) 414 << "'ndrange_t'"; 415 return true; 416 } 417 418 // With four arguments, there is only one form that the function could be 419 // called in: no events and no variable arguments. 420 if (NumArgs == 4) { 421 // check that the last argument is the right block type. 422 if (!isBlockPointer(Arg3)) { 423 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 424 << "block"; 425 return true; 426 } 427 // we have a block type, check the prototype 428 const BlockPointerType *BPT = 429 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 430 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 431 S.Diag(Arg3->getLocStart(), 432 diag::err_opencl_enqueue_kernel_blocks_no_args); 433 return true; 434 } 435 return false; 436 } 437 // we can have block + varargs. 438 if (isBlockPointer(Arg3)) 439 return (checkOpenCLBlockArgs(S, Arg3) || 440 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 441 // last two cases with either exactly 7 args or 7 args and varargs. 442 if (NumArgs >= 7) { 443 // check common block argument. 444 Expr *Arg6 = TheCall->getArg(6); 445 if (!isBlockPointer(Arg6)) { 446 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 447 << "block"; 448 return true; 449 } 450 if (checkOpenCLBlockArgs(S, Arg6)) 451 return true; 452 453 // Forth argument has to be any integer type. 454 if (!Arg3->getType()->isIntegerType()) { 455 S.Diag(TheCall->getArg(3)->getLocStart(), 456 diag::err_opencl_enqueue_kernel_expected_type) 457 << "integer"; 458 return true; 459 } 460 // check remaining common arguments. 461 Expr *Arg4 = TheCall->getArg(4); 462 Expr *Arg5 = TheCall->getArg(5); 463 464 // Fifth argument is always passed as a pointer to clk_event_t. 465 if (!Arg4->isNullPointerConstant(S.Context, 466 Expr::NPC_ValueDependentIsNotNull) && 467 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 468 S.Diag(TheCall->getArg(4)->getLocStart(), 469 diag::err_opencl_enqueue_kernel_expected_type) 470 << S.Context.getPointerType(S.Context.OCLClkEventTy); 471 return true; 472 } 473 474 // Sixth argument is always passed as a pointer to clk_event_t. 475 if (!Arg5->isNullPointerConstant(S.Context, 476 Expr::NPC_ValueDependentIsNotNull) && 477 !(Arg5->getType()->isPointerType() && 478 Arg5->getType()->getPointeeType()->isClkEventT())) { 479 S.Diag(TheCall->getArg(5)->getLocStart(), 480 diag::err_opencl_enqueue_kernel_expected_type) 481 << S.Context.getPointerType(S.Context.OCLClkEventTy); 482 return true; 483 } 484 485 if (NumArgs == 7) 486 return false; 487 488 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 489 } 490 491 // None of the specific case has been detected, give generic error 492 S.Diag(TheCall->getLocStart(), 493 diag::err_opencl_enqueue_kernel_incorrect_args); 494 return true; 495 } 496 497 /// Returns OpenCL access qual. 498 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 499 return D->getAttr<OpenCLAccessAttr>(); 500 } 501 502 /// Returns true if pipe element type is different from the pointer. 503 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 504 const Expr *Arg0 = Call->getArg(0); 505 // First argument type should always be pipe. 506 if (!Arg0->getType()->isPipeType()) { 507 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 508 << Call->getDirectCallee() << Arg0->getSourceRange(); 509 return true; 510 } 511 OpenCLAccessAttr *AccessQual = 512 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 513 // Validates the access qualifier is compatible with the call. 514 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 515 // read_only and write_only, and assumed to be read_only if no qualifier is 516 // specified. 517 switch (Call->getDirectCallee()->getBuiltinID()) { 518 case Builtin::BIread_pipe: 519 case Builtin::BIreserve_read_pipe: 520 case Builtin::BIcommit_read_pipe: 521 case Builtin::BIwork_group_reserve_read_pipe: 522 case Builtin::BIsub_group_reserve_read_pipe: 523 case Builtin::BIwork_group_commit_read_pipe: 524 case Builtin::BIsub_group_commit_read_pipe: 525 if (!(!AccessQual || AccessQual->isReadOnly())) { 526 S.Diag(Arg0->getLocStart(), 527 diag::err_opencl_builtin_pipe_invalid_access_modifier) 528 << "read_only" << Arg0->getSourceRange(); 529 return true; 530 } 531 break; 532 case Builtin::BIwrite_pipe: 533 case Builtin::BIreserve_write_pipe: 534 case Builtin::BIcommit_write_pipe: 535 case Builtin::BIwork_group_reserve_write_pipe: 536 case Builtin::BIsub_group_reserve_write_pipe: 537 case Builtin::BIwork_group_commit_write_pipe: 538 case Builtin::BIsub_group_commit_write_pipe: 539 if (!(AccessQual && AccessQual->isWriteOnly())) { 540 S.Diag(Arg0->getLocStart(), 541 diag::err_opencl_builtin_pipe_invalid_access_modifier) 542 << "write_only" << Arg0->getSourceRange(); 543 return true; 544 } 545 break; 546 default: 547 break; 548 } 549 return false; 550 } 551 552 /// Returns true if pipe element type is different from the pointer. 553 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 554 const Expr *Arg0 = Call->getArg(0); 555 const Expr *ArgIdx = Call->getArg(Idx); 556 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 557 const QualType EltTy = PipeTy->getElementType(); 558 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 559 // The Idx argument should be a pointer and the type of the pointer and 560 // the type of pipe element should also be the same. 561 if (!ArgTy || 562 !S.Context.hasSameType( 563 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 564 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 565 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 566 << ArgIdx->getType() << ArgIdx->getSourceRange(); 567 return true; 568 } 569 return false; 570 } 571 572 // \brief Performs semantic analysis for the read/write_pipe call. 573 // \param S Reference to the semantic analyzer. 574 // \param Call A pointer to the builtin call. 575 // \return True if a semantic error has been found, false otherwise. 576 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 577 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 578 // functions have two forms. 579 switch (Call->getNumArgs()) { 580 case 2: { 581 if (checkOpenCLPipeArg(S, Call)) 582 return true; 583 // The call with 2 arguments should be 584 // read/write_pipe(pipe T, T*). 585 // Check packet type T. 586 if (checkOpenCLPipePacketType(S, Call, 1)) 587 return true; 588 } break; 589 590 case 4: { 591 if (checkOpenCLPipeArg(S, Call)) 592 return true; 593 // The call with 4 arguments should be 594 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 595 // Check reserve_id_t. 596 if (!Call->getArg(1)->getType()->isReserveIDT()) { 597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 598 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 599 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 600 return true; 601 } 602 603 // Check the index. 604 const Expr *Arg2 = Call->getArg(2); 605 if (!Arg2->getType()->isIntegerType() && 606 !Arg2->getType()->isUnsignedIntegerType()) { 607 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 608 << Call->getDirectCallee() << S.Context.UnsignedIntTy 609 << Arg2->getType() << Arg2->getSourceRange(); 610 return true; 611 } 612 613 // Check packet type T. 614 if (checkOpenCLPipePacketType(S, Call, 3)) 615 return true; 616 } break; 617 default: 618 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 619 << Call->getDirectCallee() << Call->getSourceRange(); 620 return true; 621 } 622 623 return false; 624 } 625 626 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 627 // /_}reserve_{read/write}_pipe 628 // \param S Reference to the semantic analyzer. 629 // \param Call The call to the builtin function to be analyzed. 630 // \return True if a semantic error was found, false otherwise. 631 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 632 if (checkArgCount(S, Call, 2)) 633 return true; 634 635 if (checkOpenCLPipeArg(S, Call)) 636 return true; 637 638 // Check the reserve size. 639 if (!Call->getArg(1)->getType()->isIntegerType() && 640 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 641 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 642 << Call->getDirectCallee() << S.Context.UnsignedIntTy 643 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 644 return true; 645 } 646 647 return false; 648 } 649 650 // \brief Performs a semantic analysis on {work_group_/sub_group_ 651 // /_}commit_{read/write}_pipe 652 // \param S Reference to the semantic analyzer. 653 // \param Call The call to the builtin function to be analyzed. 654 // \return True if a semantic error was found, false otherwise. 655 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 656 if (checkArgCount(S, Call, 2)) 657 return true; 658 659 if (checkOpenCLPipeArg(S, Call)) 660 return true; 661 662 // Check reserve_id_t. 663 if (!Call->getArg(1)->getType()->isReserveIDT()) { 664 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 665 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 666 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 667 return true; 668 } 669 670 return false; 671 } 672 673 // \brief Performs a semantic analysis on the call to built-in Pipe 674 // Query Functions. 675 // \param S Reference to the semantic analyzer. 676 // \param Call The call to the builtin function to be analyzed. 677 // \return True if a semantic error was found, false otherwise. 678 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 679 if (checkArgCount(S, Call, 1)) 680 return true; 681 682 if (!Call->getArg(0)->getType()->isPipeType()) { 683 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 684 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 685 return true; 686 } 687 688 return false; 689 } 690 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 691 // \brief Performs semantic analysis for the to_global/local/private call. 692 // \param S Reference to the semantic analyzer. 693 // \param BuiltinID ID of the builtin function. 694 // \param Call A pointer to the builtin call. 695 // \return True if a semantic error has been found, false otherwise. 696 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 697 CallExpr *Call) { 698 if (Call->getNumArgs() != 1) { 699 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 700 << Call->getDirectCallee() << Call->getSourceRange(); 701 return true; 702 } 703 704 auto RT = Call->getArg(0)->getType(); 705 if (!RT->isPointerType() || RT->getPointeeType() 706 .getAddressSpace() == LangAS::opencl_constant) { 707 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 708 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 709 return true; 710 } 711 712 RT = RT->getPointeeType(); 713 auto Qual = RT.getQualifiers(); 714 switch (BuiltinID) { 715 case Builtin::BIto_global: 716 Qual.setAddressSpace(LangAS::opencl_global); 717 break; 718 case Builtin::BIto_local: 719 Qual.setAddressSpace(LangAS::opencl_local); 720 break; 721 default: 722 Qual.removeAddressSpace(); 723 } 724 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 725 RT.getUnqualifiedType(), Qual))); 726 727 return false; 728 } 729 730 ExprResult 731 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 732 CallExpr *TheCall) { 733 ExprResult TheCallResult(TheCall); 734 735 // Find out if any arguments are required to be integer constant expressions. 736 unsigned ICEArguments = 0; 737 ASTContext::GetBuiltinTypeError Error; 738 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 739 if (Error != ASTContext::GE_None) 740 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 741 742 // If any arguments are required to be ICE's, check and diagnose. 743 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 744 // Skip arguments not required to be ICE's. 745 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 746 747 llvm::APSInt Result; 748 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 749 return true; 750 ICEArguments &= ~(1 << ArgNo); 751 } 752 753 switch (BuiltinID) { 754 case Builtin::BI__builtin___CFStringMakeConstantString: 755 assert(TheCall->getNumArgs() == 1 && 756 "Wrong # arguments to builtin CFStringMakeConstantString"); 757 if (CheckObjCString(TheCall->getArg(0))) 758 return ExprError(); 759 break; 760 case Builtin::BI__builtin_stdarg_start: 761 case Builtin::BI__builtin_va_start: 762 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 763 return ExprError(); 764 break; 765 case Builtin::BI__va_start: { 766 switch (Context.getTargetInfo().getTriple().getArch()) { 767 case llvm::Triple::arm: 768 case llvm::Triple::thumb: 769 if (SemaBuiltinVAStartARM(TheCall)) 770 return ExprError(); 771 break; 772 default: 773 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 774 return ExprError(); 775 break; 776 } 777 break; 778 } 779 case Builtin::BI__builtin_isgreater: 780 case Builtin::BI__builtin_isgreaterequal: 781 case Builtin::BI__builtin_isless: 782 case Builtin::BI__builtin_islessequal: 783 case Builtin::BI__builtin_islessgreater: 784 case Builtin::BI__builtin_isunordered: 785 if (SemaBuiltinUnorderedCompare(TheCall)) 786 return ExprError(); 787 break; 788 case Builtin::BI__builtin_fpclassify: 789 if (SemaBuiltinFPClassification(TheCall, 6)) 790 return ExprError(); 791 break; 792 case Builtin::BI__builtin_isfinite: 793 case Builtin::BI__builtin_isinf: 794 case Builtin::BI__builtin_isinf_sign: 795 case Builtin::BI__builtin_isnan: 796 case Builtin::BI__builtin_isnormal: 797 if (SemaBuiltinFPClassification(TheCall, 1)) 798 return ExprError(); 799 break; 800 case Builtin::BI__builtin_shufflevector: 801 return SemaBuiltinShuffleVector(TheCall); 802 // TheCall will be freed by the smart pointer here, but that's fine, since 803 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 804 case Builtin::BI__builtin_prefetch: 805 if (SemaBuiltinPrefetch(TheCall)) 806 return ExprError(); 807 break; 808 case Builtin::BI__builtin_alloca_with_align: 809 if (SemaBuiltinAllocaWithAlign(TheCall)) 810 return ExprError(); 811 break; 812 case Builtin::BI__assume: 813 case Builtin::BI__builtin_assume: 814 if (SemaBuiltinAssume(TheCall)) 815 return ExprError(); 816 break; 817 case Builtin::BI__builtin_assume_aligned: 818 if (SemaBuiltinAssumeAligned(TheCall)) 819 return ExprError(); 820 break; 821 case Builtin::BI__builtin_object_size: 822 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 823 return ExprError(); 824 break; 825 case Builtin::BI__builtin_longjmp: 826 if (SemaBuiltinLongjmp(TheCall)) 827 return ExprError(); 828 break; 829 case Builtin::BI__builtin_setjmp: 830 if (SemaBuiltinSetjmp(TheCall)) 831 return ExprError(); 832 break; 833 case Builtin::BI_setjmp: 834 case Builtin::BI_setjmpex: 835 if (checkArgCount(*this, TheCall, 1)) 836 return true; 837 break; 838 839 case Builtin::BI__builtin_classify_type: 840 if (checkArgCount(*this, TheCall, 1)) return true; 841 TheCall->setType(Context.IntTy); 842 break; 843 case Builtin::BI__builtin_constant_p: 844 if (checkArgCount(*this, TheCall, 1)) return true; 845 TheCall->setType(Context.IntTy); 846 break; 847 case Builtin::BI__sync_fetch_and_add: 848 case Builtin::BI__sync_fetch_and_add_1: 849 case Builtin::BI__sync_fetch_and_add_2: 850 case Builtin::BI__sync_fetch_and_add_4: 851 case Builtin::BI__sync_fetch_and_add_8: 852 case Builtin::BI__sync_fetch_and_add_16: 853 case Builtin::BI__sync_fetch_and_sub: 854 case Builtin::BI__sync_fetch_and_sub_1: 855 case Builtin::BI__sync_fetch_and_sub_2: 856 case Builtin::BI__sync_fetch_and_sub_4: 857 case Builtin::BI__sync_fetch_and_sub_8: 858 case Builtin::BI__sync_fetch_and_sub_16: 859 case Builtin::BI__sync_fetch_and_or: 860 case Builtin::BI__sync_fetch_and_or_1: 861 case Builtin::BI__sync_fetch_and_or_2: 862 case Builtin::BI__sync_fetch_and_or_4: 863 case Builtin::BI__sync_fetch_and_or_8: 864 case Builtin::BI__sync_fetch_and_or_16: 865 case Builtin::BI__sync_fetch_and_and: 866 case Builtin::BI__sync_fetch_and_and_1: 867 case Builtin::BI__sync_fetch_and_and_2: 868 case Builtin::BI__sync_fetch_and_and_4: 869 case Builtin::BI__sync_fetch_and_and_8: 870 case Builtin::BI__sync_fetch_and_and_16: 871 case Builtin::BI__sync_fetch_and_xor: 872 case Builtin::BI__sync_fetch_and_xor_1: 873 case Builtin::BI__sync_fetch_and_xor_2: 874 case Builtin::BI__sync_fetch_and_xor_4: 875 case Builtin::BI__sync_fetch_and_xor_8: 876 case Builtin::BI__sync_fetch_and_xor_16: 877 case Builtin::BI__sync_fetch_and_nand: 878 case Builtin::BI__sync_fetch_and_nand_1: 879 case Builtin::BI__sync_fetch_and_nand_2: 880 case Builtin::BI__sync_fetch_and_nand_4: 881 case Builtin::BI__sync_fetch_and_nand_8: 882 case Builtin::BI__sync_fetch_and_nand_16: 883 case Builtin::BI__sync_add_and_fetch: 884 case Builtin::BI__sync_add_and_fetch_1: 885 case Builtin::BI__sync_add_and_fetch_2: 886 case Builtin::BI__sync_add_and_fetch_4: 887 case Builtin::BI__sync_add_and_fetch_8: 888 case Builtin::BI__sync_add_and_fetch_16: 889 case Builtin::BI__sync_sub_and_fetch: 890 case Builtin::BI__sync_sub_and_fetch_1: 891 case Builtin::BI__sync_sub_and_fetch_2: 892 case Builtin::BI__sync_sub_and_fetch_4: 893 case Builtin::BI__sync_sub_and_fetch_8: 894 case Builtin::BI__sync_sub_and_fetch_16: 895 case Builtin::BI__sync_and_and_fetch: 896 case Builtin::BI__sync_and_and_fetch_1: 897 case Builtin::BI__sync_and_and_fetch_2: 898 case Builtin::BI__sync_and_and_fetch_4: 899 case Builtin::BI__sync_and_and_fetch_8: 900 case Builtin::BI__sync_and_and_fetch_16: 901 case Builtin::BI__sync_or_and_fetch: 902 case Builtin::BI__sync_or_and_fetch_1: 903 case Builtin::BI__sync_or_and_fetch_2: 904 case Builtin::BI__sync_or_and_fetch_4: 905 case Builtin::BI__sync_or_and_fetch_8: 906 case Builtin::BI__sync_or_and_fetch_16: 907 case Builtin::BI__sync_xor_and_fetch: 908 case Builtin::BI__sync_xor_and_fetch_1: 909 case Builtin::BI__sync_xor_and_fetch_2: 910 case Builtin::BI__sync_xor_and_fetch_4: 911 case Builtin::BI__sync_xor_and_fetch_8: 912 case Builtin::BI__sync_xor_and_fetch_16: 913 case Builtin::BI__sync_nand_and_fetch: 914 case Builtin::BI__sync_nand_and_fetch_1: 915 case Builtin::BI__sync_nand_and_fetch_2: 916 case Builtin::BI__sync_nand_and_fetch_4: 917 case Builtin::BI__sync_nand_and_fetch_8: 918 case Builtin::BI__sync_nand_and_fetch_16: 919 case Builtin::BI__sync_val_compare_and_swap: 920 case Builtin::BI__sync_val_compare_and_swap_1: 921 case Builtin::BI__sync_val_compare_and_swap_2: 922 case Builtin::BI__sync_val_compare_and_swap_4: 923 case Builtin::BI__sync_val_compare_and_swap_8: 924 case Builtin::BI__sync_val_compare_and_swap_16: 925 case Builtin::BI__sync_bool_compare_and_swap: 926 case Builtin::BI__sync_bool_compare_and_swap_1: 927 case Builtin::BI__sync_bool_compare_and_swap_2: 928 case Builtin::BI__sync_bool_compare_and_swap_4: 929 case Builtin::BI__sync_bool_compare_and_swap_8: 930 case Builtin::BI__sync_bool_compare_and_swap_16: 931 case Builtin::BI__sync_lock_test_and_set: 932 case Builtin::BI__sync_lock_test_and_set_1: 933 case Builtin::BI__sync_lock_test_and_set_2: 934 case Builtin::BI__sync_lock_test_and_set_4: 935 case Builtin::BI__sync_lock_test_and_set_8: 936 case Builtin::BI__sync_lock_test_and_set_16: 937 case Builtin::BI__sync_lock_release: 938 case Builtin::BI__sync_lock_release_1: 939 case Builtin::BI__sync_lock_release_2: 940 case Builtin::BI__sync_lock_release_4: 941 case Builtin::BI__sync_lock_release_8: 942 case Builtin::BI__sync_lock_release_16: 943 case Builtin::BI__sync_swap: 944 case Builtin::BI__sync_swap_1: 945 case Builtin::BI__sync_swap_2: 946 case Builtin::BI__sync_swap_4: 947 case Builtin::BI__sync_swap_8: 948 case Builtin::BI__sync_swap_16: 949 return SemaBuiltinAtomicOverloaded(TheCallResult); 950 case Builtin::BI__builtin_nontemporal_load: 951 case Builtin::BI__builtin_nontemporal_store: 952 return SemaBuiltinNontemporalOverloaded(TheCallResult); 953 #define BUILTIN(ID, TYPE, ATTRS) 954 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 955 case Builtin::BI##ID: \ 956 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 957 #include "clang/Basic/Builtins.def" 958 case Builtin::BI__builtin_annotation: 959 if (SemaBuiltinAnnotation(*this, TheCall)) 960 return ExprError(); 961 break; 962 case Builtin::BI__builtin_addressof: 963 if (SemaBuiltinAddressof(*this, TheCall)) 964 return ExprError(); 965 break; 966 case Builtin::BI__builtin_add_overflow: 967 case Builtin::BI__builtin_sub_overflow: 968 case Builtin::BI__builtin_mul_overflow: 969 if (SemaBuiltinOverflow(*this, TheCall)) 970 return ExprError(); 971 break; 972 case Builtin::BI__builtin_operator_new: 973 case Builtin::BI__builtin_operator_delete: 974 if (!getLangOpts().CPlusPlus) { 975 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 976 << (BuiltinID == Builtin::BI__builtin_operator_new 977 ? "__builtin_operator_new" 978 : "__builtin_operator_delete") 979 << "C++"; 980 return ExprError(); 981 } 982 // CodeGen assumes it can find the global new and delete to call, 983 // so ensure that they are declared. 984 DeclareGlobalNewDelete(); 985 break; 986 987 // check secure string manipulation functions where overflows 988 // are detectable at compile time 989 case Builtin::BI__builtin___memcpy_chk: 990 case Builtin::BI__builtin___memmove_chk: 991 case Builtin::BI__builtin___memset_chk: 992 case Builtin::BI__builtin___strlcat_chk: 993 case Builtin::BI__builtin___strlcpy_chk: 994 case Builtin::BI__builtin___strncat_chk: 995 case Builtin::BI__builtin___strncpy_chk: 996 case Builtin::BI__builtin___stpncpy_chk: 997 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 998 break; 999 case Builtin::BI__builtin___memccpy_chk: 1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1001 break; 1002 case Builtin::BI__builtin___snprintf_chk: 1003 case Builtin::BI__builtin___vsnprintf_chk: 1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1005 break; 1006 case Builtin::BI__builtin_call_with_static_chain: 1007 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1008 return ExprError(); 1009 break; 1010 case Builtin::BI__exception_code: 1011 case Builtin::BI_exception_code: 1012 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1013 diag::err_seh___except_block)) 1014 return ExprError(); 1015 break; 1016 case Builtin::BI__exception_info: 1017 case Builtin::BI_exception_info: 1018 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1019 diag::err_seh___except_filter)) 1020 return ExprError(); 1021 break; 1022 case Builtin::BI__GetExceptionInfo: 1023 if (checkArgCount(*this, TheCall, 1)) 1024 return ExprError(); 1025 1026 if (CheckCXXThrowOperand( 1027 TheCall->getLocStart(), 1028 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1029 TheCall)) 1030 return ExprError(); 1031 1032 TheCall->setType(Context.VoidPtrTy); 1033 break; 1034 // OpenCL v2.0, s6.13.16 - Pipe functions 1035 case Builtin::BIread_pipe: 1036 case Builtin::BIwrite_pipe: 1037 // Since those two functions are declared with var args, we need a semantic 1038 // check for the argument. 1039 if (SemaBuiltinRWPipe(*this, TheCall)) 1040 return ExprError(); 1041 TheCall->setType(Context.IntTy); 1042 break; 1043 case Builtin::BIreserve_read_pipe: 1044 case Builtin::BIreserve_write_pipe: 1045 case Builtin::BIwork_group_reserve_read_pipe: 1046 case Builtin::BIwork_group_reserve_write_pipe: 1047 case Builtin::BIsub_group_reserve_read_pipe: 1048 case Builtin::BIsub_group_reserve_write_pipe: 1049 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1050 return ExprError(); 1051 // Since return type of reserve_read/write_pipe built-in function is 1052 // reserve_id_t, which is not defined in the builtin def file , we used int 1053 // as return type and need to override the return type of these functions. 1054 TheCall->setType(Context.OCLReserveIDTy); 1055 break; 1056 case Builtin::BIcommit_read_pipe: 1057 case Builtin::BIcommit_write_pipe: 1058 case Builtin::BIwork_group_commit_read_pipe: 1059 case Builtin::BIwork_group_commit_write_pipe: 1060 case Builtin::BIsub_group_commit_read_pipe: 1061 case Builtin::BIsub_group_commit_write_pipe: 1062 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1063 return ExprError(); 1064 break; 1065 case Builtin::BIget_pipe_num_packets: 1066 case Builtin::BIget_pipe_max_packets: 1067 if (SemaBuiltinPipePackets(*this, TheCall)) 1068 return ExprError(); 1069 TheCall->setType(Context.UnsignedIntTy); 1070 break; 1071 case Builtin::BIto_global: 1072 case Builtin::BIto_local: 1073 case Builtin::BIto_private: 1074 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1075 return ExprError(); 1076 break; 1077 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1078 case Builtin::BIenqueue_kernel: 1079 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1080 return ExprError(); 1081 break; 1082 case Builtin::BIget_kernel_work_group_size: 1083 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1084 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1085 return ExprError(); 1086 break; 1087 case Builtin::BI__builtin_os_log_format: 1088 case Builtin::BI__builtin_os_log_format_buffer_size: 1089 if (SemaBuiltinOSLogFormat(TheCall)) { 1090 return ExprError(); 1091 } 1092 break; 1093 } 1094 1095 // Since the target specific builtins for each arch overlap, only check those 1096 // of the arch we are compiling for. 1097 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1098 switch (Context.getTargetInfo().getTriple().getArch()) { 1099 case llvm::Triple::arm: 1100 case llvm::Triple::armeb: 1101 case llvm::Triple::thumb: 1102 case llvm::Triple::thumbeb: 1103 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1104 return ExprError(); 1105 break; 1106 case llvm::Triple::aarch64: 1107 case llvm::Triple::aarch64_be: 1108 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1109 return ExprError(); 1110 break; 1111 case llvm::Triple::mips: 1112 case llvm::Triple::mipsel: 1113 case llvm::Triple::mips64: 1114 case llvm::Triple::mips64el: 1115 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1116 return ExprError(); 1117 break; 1118 case llvm::Triple::systemz: 1119 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1120 return ExprError(); 1121 break; 1122 case llvm::Triple::x86: 1123 case llvm::Triple::x86_64: 1124 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1125 return ExprError(); 1126 break; 1127 case llvm::Triple::ppc: 1128 case llvm::Triple::ppc64: 1129 case llvm::Triple::ppc64le: 1130 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1131 return ExprError(); 1132 break; 1133 default: 1134 break; 1135 } 1136 } 1137 1138 return TheCallResult; 1139 } 1140 1141 // Get the valid immediate range for the specified NEON type code. 1142 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1143 NeonTypeFlags Type(t); 1144 int IsQuad = ForceQuad ? true : Type.isQuad(); 1145 switch (Type.getEltType()) { 1146 case NeonTypeFlags::Int8: 1147 case NeonTypeFlags::Poly8: 1148 return shift ? 7 : (8 << IsQuad) - 1; 1149 case NeonTypeFlags::Int16: 1150 case NeonTypeFlags::Poly16: 1151 return shift ? 15 : (4 << IsQuad) - 1; 1152 case NeonTypeFlags::Int32: 1153 return shift ? 31 : (2 << IsQuad) - 1; 1154 case NeonTypeFlags::Int64: 1155 case NeonTypeFlags::Poly64: 1156 return shift ? 63 : (1 << IsQuad) - 1; 1157 case NeonTypeFlags::Poly128: 1158 return shift ? 127 : (1 << IsQuad) - 1; 1159 case NeonTypeFlags::Float16: 1160 assert(!shift && "cannot shift float types!"); 1161 return (4 << IsQuad) - 1; 1162 case NeonTypeFlags::Float32: 1163 assert(!shift && "cannot shift float types!"); 1164 return (2 << IsQuad) - 1; 1165 case NeonTypeFlags::Float64: 1166 assert(!shift && "cannot shift float types!"); 1167 return (1 << IsQuad) - 1; 1168 } 1169 llvm_unreachable("Invalid NeonTypeFlag!"); 1170 } 1171 1172 /// getNeonEltType - Return the QualType corresponding to the elements of 1173 /// the vector type specified by the NeonTypeFlags. This is used to check 1174 /// the pointer arguments for Neon load/store intrinsics. 1175 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1176 bool IsPolyUnsigned, bool IsInt64Long) { 1177 switch (Flags.getEltType()) { 1178 case NeonTypeFlags::Int8: 1179 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1180 case NeonTypeFlags::Int16: 1181 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1182 case NeonTypeFlags::Int32: 1183 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1184 case NeonTypeFlags::Int64: 1185 if (IsInt64Long) 1186 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1187 else 1188 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1189 : Context.LongLongTy; 1190 case NeonTypeFlags::Poly8: 1191 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1192 case NeonTypeFlags::Poly16: 1193 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1194 case NeonTypeFlags::Poly64: 1195 if (IsInt64Long) 1196 return Context.UnsignedLongTy; 1197 else 1198 return Context.UnsignedLongLongTy; 1199 case NeonTypeFlags::Poly128: 1200 break; 1201 case NeonTypeFlags::Float16: 1202 return Context.HalfTy; 1203 case NeonTypeFlags::Float32: 1204 return Context.FloatTy; 1205 case NeonTypeFlags::Float64: 1206 return Context.DoubleTy; 1207 } 1208 llvm_unreachable("Invalid NeonTypeFlag!"); 1209 } 1210 1211 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1212 llvm::APSInt Result; 1213 uint64_t mask = 0; 1214 unsigned TV = 0; 1215 int PtrArgNum = -1; 1216 bool HasConstPtr = false; 1217 switch (BuiltinID) { 1218 #define GET_NEON_OVERLOAD_CHECK 1219 #include "clang/Basic/arm_neon.inc" 1220 #undef GET_NEON_OVERLOAD_CHECK 1221 } 1222 1223 // For NEON intrinsics which are overloaded on vector element type, validate 1224 // the immediate which specifies which variant to emit. 1225 unsigned ImmArg = TheCall->getNumArgs()-1; 1226 if (mask) { 1227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1228 return true; 1229 1230 TV = Result.getLimitedValue(64); 1231 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1232 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1233 << TheCall->getArg(ImmArg)->getSourceRange(); 1234 } 1235 1236 if (PtrArgNum >= 0) { 1237 // Check that pointer arguments have the specified type. 1238 Expr *Arg = TheCall->getArg(PtrArgNum); 1239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1240 Arg = ICE->getSubExpr(); 1241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1242 QualType RHSTy = RHS.get()->getType(); 1243 1244 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1246 Arch == llvm::Triple::aarch64_be; 1247 bool IsInt64Long = 1248 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1249 QualType EltTy = 1250 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1251 if (HasConstPtr) 1252 EltTy = EltTy.withConst(); 1253 QualType LHSTy = Context.getPointerType(EltTy); 1254 AssignConvertType ConvTy; 1255 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1256 if (RHS.isInvalid()) 1257 return true; 1258 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1259 RHS.get(), AA_Assigning)) 1260 return true; 1261 } 1262 1263 // For NEON intrinsics which take an immediate value as part of the 1264 // instruction, range check them here. 1265 unsigned i = 0, l = 0, u = 0; 1266 switch (BuiltinID) { 1267 default: 1268 return false; 1269 #define GET_NEON_IMMEDIATE_CHECK 1270 #include "clang/Basic/arm_neon.inc" 1271 #undef GET_NEON_IMMEDIATE_CHECK 1272 } 1273 1274 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1275 } 1276 1277 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1278 unsigned MaxWidth) { 1279 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1280 BuiltinID == ARM::BI__builtin_arm_ldaex || 1281 BuiltinID == ARM::BI__builtin_arm_strex || 1282 BuiltinID == ARM::BI__builtin_arm_stlex || 1283 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1284 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1285 BuiltinID == AArch64::BI__builtin_arm_strex || 1286 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1287 "unexpected ARM builtin"); 1288 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1289 BuiltinID == ARM::BI__builtin_arm_ldaex || 1290 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1291 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1292 1293 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1294 1295 // Ensure that we have the proper number of arguments. 1296 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1297 return true; 1298 1299 // Inspect the pointer argument of the atomic builtin. This should always be 1300 // a pointer type, whose element is an integral scalar or pointer type. 1301 // Because it is a pointer type, we don't have to worry about any implicit 1302 // casts here. 1303 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1304 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1305 if (PointerArgRes.isInvalid()) 1306 return true; 1307 PointerArg = PointerArgRes.get(); 1308 1309 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1310 if (!pointerType) { 1311 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1312 << PointerArg->getType() << PointerArg->getSourceRange(); 1313 return true; 1314 } 1315 1316 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1317 // task is to insert the appropriate casts into the AST. First work out just 1318 // what the appropriate type is. 1319 QualType ValType = pointerType->getPointeeType(); 1320 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1321 if (IsLdrex) 1322 AddrType.addConst(); 1323 1324 // Issue a warning if the cast is dodgy. 1325 CastKind CastNeeded = CK_NoOp; 1326 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1327 CastNeeded = CK_BitCast; 1328 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1329 << PointerArg->getType() 1330 << Context.getPointerType(AddrType) 1331 << AA_Passing << PointerArg->getSourceRange(); 1332 } 1333 1334 // Finally, do the cast and replace the argument with the corrected version. 1335 AddrType = Context.getPointerType(AddrType); 1336 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1337 if (PointerArgRes.isInvalid()) 1338 return true; 1339 PointerArg = PointerArgRes.get(); 1340 1341 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1342 1343 // In general, we allow ints, floats and pointers to be loaded and stored. 1344 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1345 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1346 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1347 << PointerArg->getType() << PointerArg->getSourceRange(); 1348 return true; 1349 } 1350 1351 // But ARM doesn't have instructions to deal with 128-bit versions. 1352 if (Context.getTypeSize(ValType) > MaxWidth) { 1353 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1354 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1355 << PointerArg->getType() << PointerArg->getSourceRange(); 1356 return true; 1357 } 1358 1359 switch (ValType.getObjCLifetime()) { 1360 case Qualifiers::OCL_None: 1361 case Qualifiers::OCL_ExplicitNone: 1362 // okay 1363 break; 1364 1365 case Qualifiers::OCL_Weak: 1366 case Qualifiers::OCL_Strong: 1367 case Qualifiers::OCL_Autoreleasing: 1368 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1369 << ValType << PointerArg->getSourceRange(); 1370 return true; 1371 } 1372 1373 if (IsLdrex) { 1374 TheCall->setType(ValType); 1375 return false; 1376 } 1377 1378 // Initialize the argument to be stored. 1379 ExprResult ValArg = TheCall->getArg(0); 1380 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1381 Context, ValType, /*consume*/ false); 1382 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1383 if (ValArg.isInvalid()) 1384 return true; 1385 TheCall->setArg(0, ValArg.get()); 1386 1387 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1388 // but the custom checker bypasses all default analysis. 1389 TheCall->setType(Context.IntTy); 1390 return false; 1391 } 1392 1393 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1394 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1395 BuiltinID == ARM::BI__builtin_arm_ldaex || 1396 BuiltinID == ARM::BI__builtin_arm_strex || 1397 BuiltinID == ARM::BI__builtin_arm_stlex) { 1398 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1399 } 1400 1401 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1402 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1403 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1404 } 1405 1406 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1407 BuiltinID == ARM::BI__builtin_arm_wsr64) 1408 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1409 1410 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1411 BuiltinID == ARM::BI__builtin_arm_rsrp || 1412 BuiltinID == ARM::BI__builtin_arm_wsr || 1413 BuiltinID == ARM::BI__builtin_arm_wsrp) 1414 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1415 1416 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1417 return true; 1418 1419 // For intrinsics which take an immediate value as part of the instruction, 1420 // range check them here. 1421 unsigned i = 0, l = 0, u = 0; 1422 switch (BuiltinID) { 1423 default: return false; 1424 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1425 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1426 case ARM::BI__builtin_arm_vcvtr_f: 1427 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1428 case ARM::BI__builtin_arm_dmb: 1429 case ARM::BI__builtin_arm_dsb: 1430 case ARM::BI__builtin_arm_isb: 1431 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1432 } 1433 1434 // FIXME: VFP Intrinsics should error if VFP not present. 1435 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1436 } 1437 1438 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1439 CallExpr *TheCall) { 1440 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1441 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1442 BuiltinID == AArch64::BI__builtin_arm_strex || 1443 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1444 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1445 } 1446 1447 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1448 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1449 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1450 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1451 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1452 } 1453 1454 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1455 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1456 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1457 1458 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1459 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1460 BuiltinID == AArch64::BI__builtin_arm_wsr || 1461 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1462 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1463 1464 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1465 return true; 1466 1467 // For intrinsics which take an immediate value as part of the instruction, 1468 // range check them here. 1469 unsigned i = 0, l = 0, u = 0; 1470 switch (BuiltinID) { 1471 default: return false; 1472 case AArch64::BI__builtin_arm_dmb: 1473 case AArch64::BI__builtin_arm_dsb: 1474 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1475 } 1476 1477 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1478 } 1479 1480 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1481 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1482 // ordering for DSP is unspecified. MSA is ordered by the data format used 1483 // by the underlying instruction i.e., df/m, df/n and then by size. 1484 // 1485 // FIXME: The size tests here should instead be tablegen'd along with the 1486 // definitions from include/clang/Basic/BuiltinsMips.def. 1487 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1488 // be too. 1489 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1490 unsigned i = 0, l = 0, u = 0, m = 0; 1491 switch (BuiltinID) { 1492 default: return false; 1493 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1494 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1495 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1496 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1497 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1498 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1499 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1500 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1501 // df/m field. 1502 // These intrinsics take an unsigned 3 bit immediate. 1503 case Mips::BI__builtin_msa_bclri_b: 1504 case Mips::BI__builtin_msa_bnegi_b: 1505 case Mips::BI__builtin_msa_bseti_b: 1506 case Mips::BI__builtin_msa_sat_s_b: 1507 case Mips::BI__builtin_msa_sat_u_b: 1508 case Mips::BI__builtin_msa_slli_b: 1509 case Mips::BI__builtin_msa_srai_b: 1510 case Mips::BI__builtin_msa_srari_b: 1511 case Mips::BI__builtin_msa_srli_b: 1512 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1513 case Mips::BI__builtin_msa_binsli_b: 1514 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1515 // These intrinsics take an unsigned 4 bit immediate. 1516 case Mips::BI__builtin_msa_bclri_h: 1517 case Mips::BI__builtin_msa_bnegi_h: 1518 case Mips::BI__builtin_msa_bseti_h: 1519 case Mips::BI__builtin_msa_sat_s_h: 1520 case Mips::BI__builtin_msa_sat_u_h: 1521 case Mips::BI__builtin_msa_slli_h: 1522 case Mips::BI__builtin_msa_srai_h: 1523 case Mips::BI__builtin_msa_srari_h: 1524 case Mips::BI__builtin_msa_srli_h: 1525 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1526 case Mips::BI__builtin_msa_binsli_h: 1527 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1528 // These intrinsics take an unsigned 5 bit immedate. 1529 // The first block of intrinsics actually have an unsigned 5 bit field, 1530 // not a df/n field. 1531 case Mips::BI__builtin_msa_clei_u_b: 1532 case Mips::BI__builtin_msa_clei_u_h: 1533 case Mips::BI__builtin_msa_clei_u_w: 1534 case Mips::BI__builtin_msa_clei_u_d: 1535 case Mips::BI__builtin_msa_clti_u_b: 1536 case Mips::BI__builtin_msa_clti_u_h: 1537 case Mips::BI__builtin_msa_clti_u_w: 1538 case Mips::BI__builtin_msa_clti_u_d: 1539 case Mips::BI__builtin_msa_maxi_u_b: 1540 case Mips::BI__builtin_msa_maxi_u_h: 1541 case Mips::BI__builtin_msa_maxi_u_w: 1542 case Mips::BI__builtin_msa_maxi_u_d: 1543 case Mips::BI__builtin_msa_mini_u_b: 1544 case Mips::BI__builtin_msa_mini_u_h: 1545 case Mips::BI__builtin_msa_mini_u_w: 1546 case Mips::BI__builtin_msa_mini_u_d: 1547 case Mips::BI__builtin_msa_addvi_b: 1548 case Mips::BI__builtin_msa_addvi_h: 1549 case Mips::BI__builtin_msa_addvi_w: 1550 case Mips::BI__builtin_msa_addvi_d: 1551 case Mips::BI__builtin_msa_bclri_w: 1552 case Mips::BI__builtin_msa_bnegi_w: 1553 case Mips::BI__builtin_msa_bseti_w: 1554 case Mips::BI__builtin_msa_sat_s_w: 1555 case Mips::BI__builtin_msa_sat_u_w: 1556 case Mips::BI__builtin_msa_slli_w: 1557 case Mips::BI__builtin_msa_srai_w: 1558 case Mips::BI__builtin_msa_srari_w: 1559 case Mips::BI__builtin_msa_srli_w: 1560 case Mips::BI__builtin_msa_srlri_w: 1561 case Mips::BI__builtin_msa_subvi_b: 1562 case Mips::BI__builtin_msa_subvi_h: 1563 case Mips::BI__builtin_msa_subvi_w: 1564 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1565 case Mips::BI__builtin_msa_binsli_w: 1566 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1567 // These intrinsics take an unsigned 6 bit immediate. 1568 case Mips::BI__builtin_msa_bclri_d: 1569 case Mips::BI__builtin_msa_bnegi_d: 1570 case Mips::BI__builtin_msa_bseti_d: 1571 case Mips::BI__builtin_msa_sat_s_d: 1572 case Mips::BI__builtin_msa_sat_u_d: 1573 case Mips::BI__builtin_msa_slli_d: 1574 case Mips::BI__builtin_msa_srai_d: 1575 case Mips::BI__builtin_msa_srari_d: 1576 case Mips::BI__builtin_msa_srli_d: 1577 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1578 case Mips::BI__builtin_msa_binsli_d: 1579 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1580 // These intrinsics take a signed 5 bit immediate. 1581 case Mips::BI__builtin_msa_ceqi_b: 1582 case Mips::BI__builtin_msa_ceqi_h: 1583 case Mips::BI__builtin_msa_ceqi_w: 1584 case Mips::BI__builtin_msa_ceqi_d: 1585 case Mips::BI__builtin_msa_clti_s_b: 1586 case Mips::BI__builtin_msa_clti_s_h: 1587 case Mips::BI__builtin_msa_clti_s_w: 1588 case Mips::BI__builtin_msa_clti_s_d: 1589 case Mips::BI__builtin_msa_clei_s_b: 1590 case Mips::BI__builtin_msa_clei_s_h: 1591 case Mips::BI__builtin_msa_clei_s_w: 1592 case Mips::BI__builtin_msa_clei_s_d: 1593 case Mips::BI__builtin_msa_maxi_s_b: 1594 case Mips::BI__builtin_msa_maxi_s_h: 1595 case Mips::BI__builtin_msa_maxi_s_w: 1596 case Mips::BI__builtin_msa_maxi_s_d: 1597 case Mips::BI__builtin_msa_mini_s_b: 1598 case Mips::BI__builtin_msa_mini_s_h: 1599 case Mips::BI__builtin_msa_mini_s_w: 1600 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1601 // These intrinsics take an unsigned 8 bit immediate. 1602 case Mips::BI__builtin_msa_andi_b: 1603 case Mips::BI__builtin_msa_nori_b: 1604 case Mips::BI__builtin_msa_ori_b: 1605 case Mips::BI__builtin_msa_shf_b: 1606 case Mips::BI__builtin_msa_shf_h: 1607 case Mips::BI__builtin_msa_shf_w: 1608 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1609 case Mips::BI__builtin_msa_bseli_b: 1610 case Mips::BI__builtin_msa_bmnzi_b: 1611 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1612 // df/n format 1613 // These intrinsics take an unsigned 4 bit immediate. 1614 case Mips::BI__builtin_msa_copy_s_b: 1615 case Mips::BI__builtin_msa_copy_u_b: 1616 case Mips::BI__builtin_msa_insve_b: 1617 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1618 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1619 // These intrinsics take an unsigned 3 bit immediate. 1620 case Mips::BI__builtin_msa_copy_s_h: 1621 case Mips::BI__builtin_msa_copy_u_h: 1622 case Mips::BI__builtin_msa_insve_h: 1623 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1624 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1625 // These intrinsics take an unsigned 2 bit immediate. 1626 case Mips::BI__builtin_msa_copy_s_w: 1627 case Mips::BI__builtin_msa_copy_u_w: 1628 case Mips::BI__builtin_msa_insve_w: 1629 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1630 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1631 // These intrinsics take an unsigned 1 bit immediate. 1632 case Mips::BI__builtin_msa_copy_s_d: 1633 case Mips::BI__builtin_msa_copy_u_d: 1634 case Mips::BI__builtin_msa_insve_d: 1635 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1636 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1637 // Memory offsets and immediate loads. 1638 // These intrinsics take a signed 10 bit immediate. 1639 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 1640 case Mips::BI__builtin_msa_ldi_h: 1641 case Mips::BI__builtin_msa_ldi_w: 1642 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1643 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1644 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1645 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1646 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1647 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1648 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1649 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1650 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1651 } 1652 1653 if (!m) 1654 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1655 1656 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1657 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1658 } 1659 1660 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1661 unsigned i = 0, l = 0, u = 0; 1662 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1663 BuiltinID == PPC::BI__builtin_divdeu || 1664 BuiltinID == PPC::BI__builtin_bpermd; 1665 bool IsTarget64Bit = Context.getTargetInfo() 1666 .getTypeWidth(Context 1667 .getTargetInfo() 1668 .getIntPtrType()) == 64; 1669 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1670 BuiltinID == PPC::BI__builtin_divweu || 1671 BuiltinID == PPC::BI__builtin_divde || 1672 BuiltinID == PPC::BI__builtin_divdeu; 1673 1674 if (Is64BitBltin && !IsTarget64Bit) 1675 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1676 << TheCall->getSourceRange(); 1677 1678 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1679 (BuiltinID == PPC::BI__builtin_bpermd && 1680 !Context.getTargetInfo().hasFeature("bpermd"))) 1681 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1682 << TheCall->getSourceRange(); 1683 1684 switch (BuiltinID) { 1685 default: return false; 1686 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1687 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1688 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1689 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1690 case PPC::BI__builtin_tbegin: 1691 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1692 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1693 case PPC::BI__builtin_tabortwc: 1694 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1695 case PPC::BI__builtin_tabortwci: 1696 case PPC::BI__builtin_tabortdci: 1697 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1698 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1699 case PPC::BI__builtin_vsx_xxpermdi: 1700 case PPC::BI__builtin_vsx_xxsldwi: 1701 return SemaBuiltinVSX(TheCall); 1702 } 1703 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1704 } 1705 1706 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1707 CallExpr *TheCall) { 1708 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1709 Expr *Arg = TheCall->getArg(0); 1710 llvm::APSInt AbortCode(32); 1711 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1712 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1713 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1714 << Arg->getSourceRange(); 1715 } 1716 1717 // For intrinsics which take an immediate value as part of the instruction, 1718 // range check them here. 1719 unsigned i = 0, l = 0, u = 0; 1720 switch (BuiltinID) { 1721 default: return false; 1722 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1723 case SystemZ::BI__builtin_s390_verimb: 1724 case SystemZ::BI__builtin_s390_verimh: 1725 case SystemZ::BI__builtin_s390_verimf: 1726 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1727 case SystemZ::BI__builtin_s390_vfaeb: 1728 case SystemZ::BI__builtin_s390_vfaeh: 1729 case SystemZ::BI__builtin_s390_vfaef: 1730 case SystemZ::BI__builtin_s390_vfaebs: 1731 case SystemZ::BI__builtin_s390_vfaehs: 1732 case SystemZ::BI__builtin_s390_vfaefs: 1733 case SystemZ::BI__builtin_s390_vfaezb: 1734 case SystemZ::BI__builtin_s390_vfaezh: 1735 case SystemZ::BI__builtin_s390_vfaezf: 1736 case SystemZ::BI__builtin_s390_vfaezbs: 1737 case SystemZ::BI__builtin_s390_vfaezhs: 1738 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1739 case SystemZ::BI__builtin_s390_vfidb: 1740 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1741 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1742 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1743 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1744 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1745 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1746 case SystemZ::BI__builtin_s390_vstrcb: 1747 case SystemZ::BI__builtin_s390_vstrch: 1748 case SystemZ::BI__builtin_s390_vstrcf: 1749 case SystemZ::BI__builtin_s390_vstrczb: 1750 case SystemZ::BI__builtin_s390_vstrczh: 1751 case SystemZ::BI__builtin_s390_vstrczf: 1752 case SystemZ::BI__builtin_s390_vstrcbs: 1753 case SystemZ::BI__builtin_s390_vstrchs: 1754 case SystemZ::BI__builtin_s390_vstrcfs: 1755 case SystemZ::BI__builtin_s390_vstrczbs: 1756 case SystemZ::BI__builtin_s390_vstrczhs: 1757 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1758 } 1759 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1760 } 1761 1762 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1763 /// This checks that the target supports __builtin_cpu_supports and 1764 /// that the string argument is constant and valid. 1765 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1766 Expr *Arg = TheCall->getArg(0); 1767 1768 // Check if the argument is a string literal. 1769 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1770 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1771 << Arg->getSourceRange(); 1772 1773 // Check the contents of the string. 1774 StringRef Feature = 1775 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1776 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1777 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1778 << Arg->getSourceRange(); 1779 return false; 1780 } 1781 1782 // Check if the rounding mode is legal. 1783 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1784 // Indicates if this instruction has rounding control or just SAE. 1785 bool HasRC = false; 1786 1787 unsigned ArgNum = 0; 1788 switch (BuiltinID) { 1789 default: 1790 return false; 1791 case X86::BI__builtin_ia32_vcvttsd2si32: 1792 case X86::BI__builtin_ia32_vcvttsd2si64: 1793 case X86::BI__builtin_ia32_vcvttsd2usi32: 1794 case X86::BI__builtin_ia32_vcvttsd2usi64: 1795 case X86::BI__builtin_ia32_vcvttss2si32: 1796 case X86::BI__builtin_ia32_vcvttss2si64: 1797 case X86::BI__builtin_ia32_vcvttss2usi32: 1798 case X86::BI__builtin_ia32_vcvttss2usi64: 1799 ArgNum = 1; 1800 break; 1801 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1802 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1803 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1804 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1805 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1806 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1807 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1808 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1809 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1810 case X86::BI__builtin_ia32_exp2pd_mask: 1811 case X86::BI__builtin_ia32_exp2ps_mask: 1812 case X86::BI__builtin_ia32_getexppd512_mask: 1813 case X86::BI__builtin_ia32_getexpps512_mask: 1814 case X86::BI__builtin_ia32_rcp28pd_mask: 1815 case X86::BI__builtin_ia32_rcp28ps_mask: 1816 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1817 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1818 case X86::BI__builtin_ia32_vcomisd: 1819 case X86::BI__builtin_ia32_vcomiss: 1820 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1821 ArgNum = 3; 1822 break; 1823 case X86::BI__builtin_ia32_cmppd512_mask: 1824 case X86::BI__builtin_ia32_cmpps512_mask: 1825 case X86::BI__builtin_ia32_cmpsd_mask: 1826 case X86::BI__builtin_ia32_cmpss_mask: 1827 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1828 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1829 case X86::BI__builtin_ia32_getexpss128_round_mask: 1830 case X86::BI__builtin_ia32_maxpd512_mask: 1831 case X86::BI__builtin_ia32_maxps512_mask: 1832 case X86::BI__builtin_ia32_maxsd_round_mask: 1833 case X86::BI__builtin_ia32_maxss_round_mask: 1834 case X86::BI__builtin_ia32_minpd512_mask: 1835 case X86::BI__builtin_ia32_minps512_mask: 1836 case X86::BI__builtin_ia32_minsd_round_mask: 1837 case X86::BI__builtin_ia32_minss_round_mask: 1838 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1839 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1840 case X86::BI__builtin_ia32_reducepd512_mask: 1841 case X86::BI__builtin_ia32_reduceps512_mask: 1842 case X86::BI__builtin_ia32_rndscalepd_mask: 1843 case X86::BI__builtin_ia32_rndscaleps_mask: 1844 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1845 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1846 ArgNum = 4; 1847 break; 1848 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1849 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1850 case X86::BI__builtin_ia32_fixupimmps512_mask: 1851 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1852 case X86::BI__builtin_ia32_fixupimmsd_mask: 1853 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1854 case X86::BI__builtin_ia32_fixupimmss_mask: 1855 case X86::BI__builtin_ia32_fixupimmss_maskz: 1856 case X86::BI__builtin_ia32_rangepd512_mask: 1857 case X86::BI__builtin_ia32_rangeps512_mask: 1858 case X86::BI__builtin_ia32_rangesd128_round_mask: 1859 case X86::BI__builtin_ia32_rangess128_round_mask: 1860 case X86::BI__builtin_ia32_reducesd_mask: 1861 case X86::BI__builtin_ia32_reducess_mask: 1862 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1863 case X86::BI__builtin_ia32_rndscaless_round_mask: 1864 ArgNum = 5; 1865 break; 1866 case X86::BI__builtin_ia32_vcvtsd2si64: 1867 case X86::BI__builtin_ia32_vcvtsd2si32: 1868 case X86::BI__builtin_ia32_vcvtsd2usi32: 1869 case X86::BI__builtin_ia32_vcvtsd2usi64: 1870 case X86::BI__builtin_ia32_vcvtss2si32: 1871 case X86::BI__builtin_ia32_vcvtss2si64: 1872 case X86::BI__builtin_ia32_vcvtss2usi32: 1873 case X86::BI__builtin_ia32_vcvtss2usi64: 1874 ArgNum = 1; 1875 HasRC = true; 1876 break; 1877 case X86::BI__builtin_ia32_cvtsi2sd64: 1878 case X86::BI__builtin_ia32_cvtsi2ss32: 1879 case X86::BI__builtin_ia32_cvtsi2ss64: 1880 case X86::BI__builtin_ia32_cvtusi2sd64: 1881 case X86::BI__builtin_ia32_cvtusi2ss32: 1882 case X86::BI__builtin_ia32_cvtusi2ss64: 1883 ArgNum = 2; 1884 HasRC = true; 1885 break; 1886 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1887 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1888 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1889 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1890 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1891 case X86::BI__builtin_ia32_cvtps2qq512_mask: 1892 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 1893 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 1894 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 1895 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 1896 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 1897 case X86::BI__builtin_ia32_sqrtpd512_mask: 1898 case X86::BI__builtin_ia32_sqrtps512_mask: 1899 ArgNum = 3; 1900 HasRC = true; 1901 break; 1902 case X86::BI__builtin_ia32_addpd512_mask: 1903 case X86::BI__builtin_ia32_addps512_mask: 1904 case X86::BI__builtin_ia32_divpd512_mask: 1905 case X86::BI__builtin_ia32_divps512_mask: 1906 case X86::BI__builtin_ia32_mulpd512_mask: 1907 case X86::BI__builtin_ia32_mulps512_mask: 1908 case X86::BI__builtin_ia32_subpd512_mask: 1909 case X86::BI__builtin_ia32_subps512_mask: 1910 case X86::BI__builtin_ia32_addss_round_mask: 1911 case X86::BI__builtin_ia32_addsd_round_mask: 1912 case X86::BI__builtin_ia32_divss_round_mask: 1913 case X86::BI__builtin_ia32_divsd_round_mask: 1914 case X86::BI__builtin_ia32_mulss_round_mask: 1915 case X86::BI__builtin_ia32_mulsd_round_mask: 1916 case X86::BI__builtin_ia32_subss_round_mask: 1917 case X86::BI__builtin_ia32_subsd_round_mask: 1918 case X86::BI__builtin_ia32_scalefpd512_mask: 1919 case X86::BI__builtin_ia32_scalefps512_mask: 1920 case X86::BI__builtin_ia32_scalefsd_round_mask: 1921 case X86::BI__builtin_ia32_scalefss_round_mask: 1922 case X86::BI__builtin_ia32_getmantpd512_mask: 1923 case X86::BI__builtin_ia32_getmantps512_mask: 1924 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 1925 case X86::BI__builtin_ia32_sqrtsd_round_mask: 1926 case X86::BI__builtin_ia32_sqrtss_round_mask: 1927 case X86::BI__builtin_ia32_vfmaddpd512_mask: 1928 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 1929 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 1930 case X86::BI__builtin_ia32_vfmaddps512_mask: 1931 case X86::BI__builtin_ia32_vfmaddps512_mask3: 1932 case X86::BI__builtin_ia32_vfmaddps512_maskz: 1933 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 1934 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 1935 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 1936 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 1937 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 1938 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 1939 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 1940 case X86::BI__builtin_ia32_vfmsubps512_mask3: 1941 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 1942 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 1943 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 1944 case X86::BI__builtin_ia32_vfnmaddps512_mask: 1945 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 1946 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 1947 case X86::BI__builtin_ia32_vfnmsubps512_mask: 1948 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 1949 case X86::BI__builtin_ia32_vfmaddsd3_mask: 1950 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 1951 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 1952 case X86::BI__builtin_ia32_vfmaddss3_mask: 1953 case X86::BI__builtin_ia32_vfmaddss3_maskz: 1954 case X86::BI__builtin_ia32_vfmaddss3_mask3: 1955 ArgNum = 4; 1956 HasRC = true; 1957 break; 1958 case X86::BI__builtin_ia32_getmantsd_round_mask: 1959 case X86::BI__builtin_ia32_getmantss_round_mask: 1960 ArgNum = 5; 1961 HasRC = true; 1962 break; 1963 } 1964 1965 llvm::APSInt Result; 1966 1967 // We can't check the value of a dependent argument. 1968 Expr *Arg = TheCall->getArg(ArgNum); 1969 if (Arg->isTypeDependent() || Arg->isValueDependent()) 1970 return false; 1971 1972 // Check constant-ness first. 1973 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 1974 return true; 1975 1976 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 1977 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 1978 // combined with ROUND_NO_EXC. 1979 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 1980 Result == 8/*ROUND_NO_EXC*/ || 1981 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 1982 return false; 1983 1984 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 1985 << Arg->getSourceRange(); 1986 } 1987 1988 // Check if the gather/scatter scale is legal. 1989 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 1990 CallExpr *TheCall) { 1991 unsigned ArgNum = 0; 1992 switch (BuiltinID) { 1993 default: 1994 return false; 1995 case X86::BI__builtin_ia32_gatherpfdpd: 1996 case X86::BI__builtin_ia32_gatherpfdps: 1997 case X86::BI__builtin_ia32_gatherpfqpd: 1998 case X86::BI__builtin_ia32_gatherpfqps: 1999 case X86::BI__builtin_ia32_scatterpfdpd: 2000 case X86::BI__builtin_ia32_scatterpfdps: 2001 case X86::BI__builtin_ia32_scatterpfqpd: 2002 case X86::BI__builtin_ia32_scatterpfqps: 2003 ArgNum = 3; 2004 break; 2005 case X86::BI__builtin_ia32_gatherd_pd: 2006 case X86::BI__builtin_ia32_gatherd_pd256: 2007 case X86::BI__builtin_ia32_gatherq_pd: 2008 case X86::BI__builtin_ia32_gatherq_pd256: 2009 case X86::BI__builtin_ia32_gatherd_ps: 2010 case X86::BI__builtin_ia32_gatherd_ps256: 2011 case X86::BI__builtin_ia32_gatherq_ps: 2012 case X86::BI__builtin_ia32_gatherq_ps256: 2013 case X86::BI__builtin_ia32_gatherd_q: 2014 case X86::BI__builtin_ia32_gatherd_q256: 2015 case X86::BI__builtin_ia32_gatherq_q: 2016 case X86::BI__builtin_ia32_gatherq_q256: 2017 case X86::BI__builtin_ia32_gatherd_d: 2018 case X86::BI__builtin_ia32_gatherd_d256: 2019 case X86::BI__builtin_ia32_gatherq_d: 2020 case X86::BI__builtin_ia32_gatherq_d256: 2021 case X86::BI__builtin_ia32_gather3div2df: 2022 case X86::BI__builtin_ia32_gather3div2di: 2023 case X86::BI__builtin_ia32_gather3div4df: 2024 case X86::BI__builtin_ia32_gather3div4di: 2025 case X86::BI__builtin_ia32_gather3div4sf: 2026 case X86::BI__builtin_ia32_gather3div4si: 2027 case X86::BI__builtin_ia32_gather3div8sf: 2028 case X86::BI__builtin_ia32_gather3div8si: 2029 case X86::BI__builtin_ia32_gather3siv2df: 2030 case X86::BI__builtin_ia32_gather3siv2di: 2031 case X86::BI__builtin_ia32_gather3siv4df: 2032 case X86::BI__builtin_ia32_gather3siv4di: 2033 case X86::BI__builtin_ia32_gather3siv4sf: 2034 case X86::BI__builtin_ia32_gather3siv4si: 2035 case X86::BI__builtin_ia32_gather3siv8sf: 2036 case X86::BI__builtin_ia32_gather3siv8si: 2037 case X86::BI__builtin_ia32_gathersiv8df: 2038 case X86::BI__builtin_ia32_gathersiv16sf: 2039 case X86::BI__builtin_ia32_gatherdiv8df: 2040 case X86::BI__builtin_ia32_gatherdiv16sf: 2041 case X86::BI__builtin_ia32_gathersiv8di: 2042 case X86::BI__builtin_ia32_gathersiv16si: 2043 case X86::BI__builtin_ia32_gatherdiv8di: 2044 case X86::BI__builtin_ia32_gatherdiv16si: 2045 case X86::BI__builtin_ia32_scatterdiv2df: 2046 case X86::BI__builtin_ia32_scatterdiv2di: 2047 case X86::BI__builtin_ia32_scatterdiv4df: 2048 case X86::BI__builtin_ia32_scatterdiv4di: 2049 case X86::BI__builtin_ia32_scatterdiv4sf: 2050 case X86::BI__builtin_ia32_scatterdiv4si: 2051 case X86::BI__builtin_ia32_scatterdiv8sf: 2052 case X86::BI__builtin_ia32_scatterdiv8si: 2053 case X86::BI__builtin_ia32_scattersiv2df: 2054 case X86::BI__builtin_ia32_scattersiv2di: 2055 case X86::BI__builtin_ia32_scattersiv4df: 2056 case X86::BI__builtin_ia32_scattersiv4di: 2057 case X86::BI__builtin_ia32_scattersiv4sf: 2058 case X86::BI__builtin_ia32_scattersiv4si: 2059 case X86::BI__builtin_ia32_scattersiv8sf: 2060 case X86::BI__builtin_ia32_scattersiv8si: 2061 case X86::BI__builtin_ia32_scattersiv8df: 2062 case X86::BI__builtin_ia32_scattersiv16sf: 2063 case X86::BI__builtin_ia32_scatterdiv8df: 2064 case X86::BI__builtin_ia32_scatterdiv16sf: 2065 case X86::BI__builtin_ia32_scattersiv8di: 2066 case X86::BI__builtin_ia32_scattersiv16si: 2067 case X86::BI__builtin_ia32_scatterdiv8di: 2068 case X86::BI__builtin_ia32_scatterdiv16si: 2069 ArgNum = 4; 2070 break; 2071 } 2072 2073 llvm::APSInt Result; 2074 2075 // We can't check the value of a dependent argument. 2076 Expr *Arg = TheCall->getArg(ArgNum); 2077 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2078 return false; 2079 2080 // Check constant-ness first. 2081 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2082 return true; 2083 2084 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2085 return false; 2086 2087 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2088 << Arg->getSourceRange(); 2089 } 2090 2091 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2092 if (BuiltinID == X86::BI__builtin_cpu_supports) 2093 return SemaBuiltinCpuSupports(*this, TheCall); 2094 2095 if (BuiltinID == X86::BI__builtin_ms_va_start) 2096 return SemaBuiltinVAStart(BuiltinID, TheCall); 2097 2098 // If the intrinsic has rounding or SAE make sure its valid. 2099 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2100 return true; 2101 2102 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2103 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2104 return true; 2105 2106 // For intrinsics which take an immediate value as part of the instruction, 2107 // range check them here. 2108 int i = 0, l = 0, u = 0; 2109 switch (BuiltinID) { 2110 default: 2111 return false; 2112 case X86::BI_mm_prefetch: 2113 i = 1; l = 0; u = 3; 2114 break; 2115 case X86::BI__builtin_ia32_sha1rnds4: 2116 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2117 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2118 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2119 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2120 i = 2; l = 0; u = 3; 2121 break; 2122 case X86::BI__builtin_ia32_vpermil2pd: 2123 case X86::BI__builtin_ia32_vpermil2pd256: 2124 case X86::BI__builtin_ia32_vpermil2ps: 2125 case X86::BI__builtin_ia32_vpermil2ps256: 2126 i = 3; l = 0; u = 3; 2127 break; 2128 case X86::BI__builtin_ia32_cmpb128_mask: 2129 case X86::BI__builtin_ia32_cmpw128_mask: 2130 case X86::BI__builtin_ia32_cmpd128_mask: 2131 case X86::BI__builtin_ia32_cmpq128_mask: 2132 case X86::BI__builtin_ia32_cmpb256_mask: 2133 case X86::BI__builtin_ia32_cmpw256_mask: 2134 case X86::BI__builtin_ia32_cmpd256_mask: 2135 case X86::BI__builtin_ia32_cmpq256_mask: 2136 case X86::BI__builtin_ia32_cmpb512_mask: 2137 case X86::BI__builtin_ia32_cmpw512_mask: 2138 case X86::BI__builtin_ia32_cmpd512_mask: 2139 case X86::BI__builtin_ia32_cmpq512_mask: 2140 case X86::BI__builtin_ia32_ucmpb128_mask: 2141 case X86::BI__builtin_ia32_ucmpw128_mask: 2142 case X86::BI__builtin_ia32_ucmpd128_mask: 2143 case X86::BI__builtin_ia32_ucmpq128_mask: 2144 case X86::BI__builtin_ia32_ucmpb256_mask: 2145 case X86::BI__builtin_ia32_ucmpw256_mask: 2146 case X86::BI__builtin_ia32_ucmpd256_mask: 2147 case X86::BI__builtin_ia32_ucmpq256_mask: 2148 case X86::BI__builtin_ia32_ucmpb512_mask: 2149 case X86::BI__builtin_ia32_ucmpw512_mask: 2150 case X86::BI__builtin_ia32_ucmpd512_mask: 2151 case X86::BI__builtin_ia32_ucmpq512_mask: 2152 case X86::BI__builtin_ia32_vpcomub: 2153 case X86::BI__builtin_ia32_vpcomuw: 2154 case X86::BI__builtin_ia32_vpcomud: 2155 case X86::BI__builtin_ia32_vpcomuq: 2156 case X86::BI__builtin_ia32_vpcomb: 2157 case X86::BI__builtin_ia32_vpcomw: 2158 case X86::BI__builtin_ia32_vpcomd: 2159 case X86::BI__builtin_ia32_vpcomq: 2160 i = 2; l = 0; u = 7; 2161 break; 2162 case X86::BI__builtin_ia32_roundps: 2163 case X86::BI__builtin_ia32_roundpd: 2164 case X86::BI__builtin_ia32_roundps256: 2165 case X86::BI__builtin_ia32_roundpd256: 2166 i = 1; l = 0; u = 15; 2167 break; 2168 case X86::BI__builtin_ia32_roundss: 2169 case X86::BI__builtin_ia32_roundsd: 2170 case X86::BI__builtin_ia32_rangepd128_mask: 2171 case X86::BI__builtin_ia32_rangepd256_mask: 2172 case X86::BI__builtin_ia32_rangepd512_mask: 2173 case X86::BI__builtin_ia32_rangeps128_mask: 2174 case X86::BI__builtin_ia32_rangeps256_mask: 2175 case X86::BI__builtin_ia32_rangeps512_mask: 2176 case X86::BI__builtin_ia32_getmantsd_round_mask: 2177 case X86::BI__builtin_ia32_getmantss_round_mask: 2178 i = 2; l = 0; u = 15; 2179 break; 2180 case X86::BI__builtin_ia32_cmpps: 2181 case X86::BI__builtin_ia32_cmpss: 2182 case X86::BI__builtin_ia32_cmppd: 2183 case X86::BI__builtin_ia32_cmpsd: 2184 case X86::BI__builtin_ia32_cmpps256: 2185 case X86::BI__builtin_ia32_cmppd256: 2186 case X86::BI__builtin_ia32_cmpps128_mask: 2187 case X86::BI__builtin_ia32_cmppd128_mask: 2188 case X86::BI__builtin_ia32_cmpps256_mask: 2189 case X86::BI__builtin_ia32_cmppd256_mask: 2190 case X86::BI__builtin_ia32_cmpps512_mask: 2191 case X86::BI__builtin_ia32_cmppd512_mask: 2192 case X86::BI__builtin_ia32_cmpsd_mask: 2193 case X86::BI__builtin_ia32_cmpss_mask: 2194 i = 2; l = 0; u = 31; 2195 break; 2196 case X86::BI__builtin_ia32_xabort: 2197 i = 0; l = -128; u = 255; 2198 break; 2199 case X86::BI__builtin_ia32_pshufw: 2200 case X86::BI__builtin_ia32_aeskeygenassist128: 2201 i = 1; l = -128; u = 255; 2202 break; 2203 case X86::BI__builtin_ia32_vcvtps2ph: 2204 case X86::BI__builtin_ia32_vcvtps2ph256: 2205 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2206 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2207 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2208 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2209 case X86::BI__builtin_ia32_rndscaleps_mask: 2210 case X86::BI__builtin_ia32_rndscalepd_mask: 2211 case X86::BI__builtin_ia32_reducepd128_mask: 2212 case X86::BI__builtin_ia32_reducepd256_mask: 2213 case X86::BI__builtin_ia32_reducepd512_mask: 2214 case X86::BI__builtin_ia32_reduceps128_mask: 2215 case X86::BI__builtin_ia32_reduceps256_mask: 2216 case X86::BI__builtin_ia32_reduceps512_mask: 2217 case X86::BI__builtin_ia32_prold512_mask: 2218 case X86::BI__builtin_ia32_prolq512_mask: 2219 case X86::BI__builtin_ia32_prold128_mask: 2220 case X86::BI__builtin_ia32_prold256_mask: 2221 case X86::BI__builtin_ia32_prolq128_mask: 2222 case X86::BI__builtin_ia32_prolq256_mask: 2223 case X86::BI__builtin_ia32_prord128_mask: 2224 case X86::BI__builtin_ia32_prord256_mask: 2225 case X86::BI__builtin_ia32_prorq128_mask: 2226 case X86::BI__builtin_ia32_prorq256_mask: 2227 case X86::BI__builtin_ia32_fpclasspd128_mask: 2228 case X86::BI__builtin_ia32_fpclasspd256_mask: 2229 case X86::BI__builtin_ia32_fpclassps128_mask: 2230 case X86::BI__builtin_ia32_fpclassps256_mask: 2231 case X86::BI__builtin_ia32_fpclassps512_mask: 2232 case X86::BI__builtin_ia32_fpclasspd512_mask: 2233 case X86::BI__builtin_ia32_fpclasssd_mask: 2234 case X86::BI__builtin_ia32_fpclassss_mask: 2235 i = 1; l = 0; u = 255; 2236 break; 2237 case X86::BI__builtin_ia32_palignr: 2238 case X86::BI__builtin_ia32_insertps128: 2239 case X86::BI__builtin_ia32_dpps: 2240 case X86::BI__builtin_ia32_dppd: 2241 case X86::BI__builtin_ia32_dpps256: 2242 case X86::BI__builtin_ia32_mpsadbw128: 2243 case X86::BI__builtin_ia32_mpsadbw256: 2244 case X86::BI__builtin_ia32_pcmpistrm128: 2245 case X86::BI__builtin_ia32_pcmpistri128: 2246 case X86::BI__builtin_ia32_pcmpistria128: 2247 case X86::BI__builtin_ia32_pcmpistric128: 2248 case X86::BI__builtin_ia32_pcmpistrio128: 2249 case X86::BI__builtin_ia32_pcmpistris128: 2250 case X86::BI__builtin_ia32_pcmpistriz128: 2251 case X86::BI__builtin_ia32_pclmulqdq128: 2252 case X86::BI__builtin_ia32_vperm2f128_pd256: 2253 case X86::BI__builtin_ia32_vperm2f128_ps256: 2254 case X86::BI__builtin_ia32_vperm2f128_si256: 2255 case X86::BI__builtin_ia32_permti256: 2256 i = 2; l = -128; u = 255; 2257 break; 2258 case X86::BI__builtin_ia32_palignr128: 2259 case X86::BI__builtin_ia32_palignr256: 2260 case X86::BI__builtin_ia32_palignr512_mask: 2261 case X86::BI__builtin_ia32_vcomisd: 2262 case X86::BI__builtin_ia32_vcomiss: 2263 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2264 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2265 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2266 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2267 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2268 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2269 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2270 i = 2; l = 0; u = 255; 2271 break; 2272 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2273 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2274 case X86::BI__builtin_ia32_fixupimmps512_mask: 2275 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2276 case X86::BI__builtin_ia32_fixupimmsd_mask: 2277 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2278 case X86::BI__builtin_ia32_fixupimmss_mask: 2279 case X86::BI__builtin_ia32_fixupimmss_maskz: 2280 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2281 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2282 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2283 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2284 case X86::BI__builtin_ia32_fixupimmps128_mask: 2285 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2286 case X86::BI__builtin_ia32_fixupimmps256_mask: 2287 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2288 case X86::BI__builtin_ia32_pternlogd512_mask: 2289 case X86::BI__builtin_ia32_pternlogd512_maskz: 2290 case X86::BI__builtin_ia32_pternlogq512_mask: 2291 case X86::BI__builtin_ia32_pternlogq512_maskz: 2292 case X86::BI__builtin_ia32_pternlogd128_mask: 2293 case X86::BI__builtin_ia32_pternlogd128_maskz: 2294 case X86::BI__builtin_ia32_pternlogd256_mask: 2295 case X86::BI__builtin_ia32_pternlogd256_maskz: 2296 case X86::BI__builtin_ia32_pternlogq128_mask: 2297 case X86::BI__builtin_ia32_pternlogq128_maskz: 2298 case X86::BI__builtin_ia32_pternlogq256_mask: 2299 case X86::BI__builtin_ia32_pternlogq256_maskz: 2300 i = 3; l = 0; u = 255; 2301 break; 2302 case X86::BI__builtin_ia32_gatherpfdpd: 2303 case X86::BI__builtin_ia32_gatherpfdps: 2304 case X86::BI__builtin_ia32_gatherpfqpd: 2305 case X86::BI__builtin_ia32_gatherpfqps: 2306 case X86::BI__builtin_ia32_scatterpfdpd: 2307 case X86::BI__builtin_ia32_scatterpfdps: 2308 case X86::BI__builtin_ia32_scatterpfqpd: 2309 case X86::BI__builtin_ia32_scatterpfqps: 2310 i = 4; l = 2; u = 3; 2311 break; 2312 case X86::BI__builtin_ia32_pcmpestrm128: 2313 case X86::BI__builtin_ia32_pcmpestri128: 2314 case X86::BI__builtin_ia32_pcmpestria128: 2315 case X86::BI__builtin_ia32_pcmpestric128: 2316 case X86::BI__builtin_ia32_pcmpestrio128: 2317 case X86::BI__builtin_ia32_pcmpestris128: 2318 case X86::BI__builtin_ia32_pcmpestriz128: 2319 i = 4; l = -128; u = 255; 2320 break; 2321 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2322 case X86::BI__builtin_ia32_rndscaless_round_mask: 2323 i = 4; l = 0; u = 255; 2324 break; 2325 } 2326 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2327 } 2328 2329 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2330 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2331 /// Returns true when the format fits the function and the FormatStringInfo has 2332 /// been populated. 2333 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2334 FormatStringInfo *FSI) { 2335 FSI->HasVAListArg = Format->getFirstArg() == 0; 2336 FSI->FormatIdx = Format->getFormatIdx() - 1; 2337 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2338 2339 // The way the format attribute works in GCC, the implicit this argument 2340 // of member functions is counted. However, it doesn't appear in our own 2341 // lists, so decrement format_idx in that case. 2342 if (IsCXXMember) { 2343 if(FSI->FormatIdx == 0) 2344 return false; 2345 --FSI->FormatIdx; 2346 if (FSI->FirstDataArg != 0) 2347 --FSI->FirstDataArg; 2348 } 2349 return true; 2350 } 2351 2352 /// Checks if a the given expression evaluates to null. 2353 /// 2354 /// \brief Returns true if the value evaluates to null. 2355 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2356 // If the expression has non-null type, it doesn't evaluate to null. 2357 if (auto nullability 2358 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2359 if (*nullability == NullabilityKind::NonNull) 2360 return false; 2361 } 2362 2363 // As a special case, transparent unions initialized with zero are 2364 // considered null for the purposes of the nonnull attribute. 2365 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2366 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2367 if (const CompoundLiteralExpr *CLE = 2368 dyn_cast<CompoundLiteralExpr>(Expr)) 2369 if (const InitListExpr *ILE = 2370 dyn_cast<InitListExpr>(CLE->getInitializer())) 2371 Expr = ILE->getInit(0); 2372 } 2373 2374 bool Result; 2375 return (!Expr->isValueDependent() && 2376 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2377 !Result); 2378 } 2379 2380 static void CheckNonNullArgument(Sema &S, 2381 const Expr *ArgExpr, 2382 SourceLocation CallSiteLoc) { 2383 if (CheckNonNullExpr(S, ArgExpr)) 2384 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2385 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2386 } 2387 2388 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2389 FormatStringInfo FSI; 2390 if ((GetFormatStringType(Format) == FST_NSString) && 2391 getFormatStringInfo(Format, false, &FSI)) { 2392 Idx = FSI.FormatIdx; 2393 return true; 2394 } 2395 return false; 2396 } 2397 /// \brief Diagnose use of %s directive in an NSString which is being passed 2398 /// as formatting string to formatting method. 2399 static void 2400 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2401 const NamedDecl *FDecl, 2402 Expr **Args, 2403 unsigned NumArgs) { 2404 unsigned Idx = 0; 2405 bool Format = false; 2406 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2407 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2408 Idx = 2; 2409 Format = true; 2410 } 2411 else 2412 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2413 if (S.GetFormatNSStringIdx(I, Idx)) { 2414 Format = true; 2415 break; 2416 } 2417 } 2418 if (!Format || NumArgs <= Idx) 2419 return; 2420 const Expr *FormatExpr = Args[Idx]; 2421 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2422 FormatExpr = CSCE->getSubExpr(); 2423 const StringLiteral *FormatString; 2424 if (const ObjCStringLiteral *OSL = 2425 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2426 FormatString = OSL->getString(); 2427 else 2428 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2429 if (!FormatString) 2430 return; 2431 if (S.FormatStringHasSArg(FormatString)) { 2432 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2433 << "%s" << 1 << 1; 2434 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2435 << FDecl->getDeclName(); 2436 } 2437 } 2438 2439 /// Determine whether the given type has a non-null nullability annotation. 2440 static bool isNonNullType(ASTContext &ctx, QualType type) { 2441 if (auto nullability = type->getNullability(ctx)) 2442 return *nullability == NullabilityKind::NonNull; 2443 2444 return false; 2445 } 2446 2447 static void CheckNonNullArguments(Sema &S, 2448 const NamedDecl *FDecl, 2449 const FunctionProtoType *Proto, 2450 ArrayRef<const Expr *> Args, 2451 SourceLocation CallSiteLoc) { 2452 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2453 2454 // Check the attributes attached to the method/function itself. 2455 llvm::SmallBitVector NonNullArgs; 2456 if (FDecl) { 2457 // Handle the nonnull attribute on the function/method declaration itself. 2458 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2459 if (!NonNull->args_size()) { 2460 // Easy case: all pointer arguments are nonnull. 2461 for (const auto *Arg : Args) 2462 if (S.isValidPointerAttrType(Arg->getType())) 2463 CheckNonNullArgument(S, Arg, CallSiteLoc); 2464 return; 2465 } 2466 2467 for (unsigned Val : NonNull->args()) { 2468 if (Val >= Args.size()) 2469 continue; 2470 if (NonNullArgs.empty()) 2471 NonNullArgs.resize(Args.size()); 2472 NonNullArgs.set(Val); 2473 } 2474 } 2475 } 2476 2477 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2478 // Handle the nonnull attribute on the parameters of the 2479 // function/method. 2480 ArrayRef<ParmVarDecl*> parms; 2481 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2482 parms = FD->parameters(); 2483 else 2484 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2485 2486 unsigned ParamIndex = 0; 2487 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2488 I != E; ++I, ++ParamIndex) { 2489 const ParmVarDecl *PVD = *I; 2490 if (PVD->hasAttr<NonNullAttr>() || 2491 isNonNullType(S.Context, PVD->getType())) { 2492 if (NonNullArgs.empty()) 2493 NonNullArgs.resize(Args.size()); 2494 2495 NonNullArgs.set(ParamIndex); 2496 } 2497 } 2498 } else { 2499 // If we have a non-function, non-method declaration but no 2500 // function prototype, try to dig out the function prototype. 2501 if (!Proto) { 2502 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2503 QualType type = VD->getType().getNonReferenceType(); 2504 if (auto pointerType = type->getAs<PointerType>()) 2505 type = pointerType->getPointeeType(); 2506 else if (auto blockType = type->getAs<BlockPointerType>()) 2507 type = blockType->getPointeeType(); 2508 // FIXME: data member pointers? 2509 2510 // Dig out the function prototype, if there is one. 2511 Proto = type->getAs<FunctionProtoType>(); 2512 } 2513 } 2514 2515 // Fill in non-null argument information from the nullability 2516 // information on the parameter types (if we have them). 2517 if (Proto) { 2518 unsigned Index = 0; 2519 for (auto paramType : Proto->getParamTypes()) { 2520 if (isNonNullType(S.Context, paramType)) { 2521 if (NonNullArgs.empty()) 2522 NonNullArgs.resize(Args.size()); 2523 2524 NonNullArgs.set(Index); 2525 } 2526 2527 ++Index; 2528 } 2529 } 2530 } 2531 2532 // Check for non-null arguments. 2533 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2534 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2535 if (NonNullArgs[ArgIndex]) 2536 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2537 } 2538 } 2539 2540 /// Handles the checks for format strings, non-POD arguments to vararg 2541 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2542 /// attributes. 2543 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2544 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2545 bool IsMemberFunction, SourceLocation Loc, 2546 SourceRange Range, VariadicCallType CallType) { 2547 // FIXME: We should check as much as we can in the template definition. 2548 if (CurContext->isDependentContext()) 2549 return; 2550 2551 // Printf and scanf checking. 2552 llvm::SmallBitVector CheckedVarArgs; 2553 if (FDecl) { 2554 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2555 // Only create vector if there are format attributes. 2556 CheckedVarArgs.resize(Args.size()); 2557 2558 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2559 CheckedVarArgs); 2560 } 2561 } 2562 2563 // Refuse POD arguments that weren't caught by the format string 2564 // checks above. 2565 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2566 if (CallType != VariadicDoesNotApply && 2567 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2568 unsigned NumParams = Proto ? Proto->getNumParams() 2569 : FDecl && isa<FunctionDecl>(FDecl) 2570 ? cast<FunctionDecl>(FDecl)->getNumParams() 2571 : FDecl && isa<ObjCMethodDecl>(FDecl) 2572 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2573 : 0; 2574 2575 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2576 // Args[ArgIdx] can be null in malformed code. 2577 if (const Expr *Arg = Args[ArgIdx]) { 2578 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2579 checkVariadicArgument(Arg, CallType); 2580 } 2581 } 2582 } 2583 2584 if (FDecl || Proto) { 2585 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2586 2587 // Type safety checking. 2588 if (FDecl) { 2589 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2590 CheckArgumentWithTypeTag(I, Args.data()); 2591 } 2592 } 2593 2594 if (FD) 2595 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 2596 } 2597 2598 /// CheckConstructorCall - Check a constructor call for correctness and safety 2599 /// properties not enforced by the C type system. 2600 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2601 ArrayRef<const Expr *> Args, 2602 const FunctionProtoType *Proto, 2603 SourceLocation Loc) { 2604 VariadicCallType CallType = 2605 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2606 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 2607 Loc, SourceRange(), CallType); 2608 } 2609 2610 /// CheckFunctionCall - Check a direct function call for various correctness 2611 /// and safety properties not strictly enforced by the C type system. 2612 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2613 const FunctionProtoType *Proto) { 2614 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2615 isa<CXXMethodDecl>(FDecl); 2616 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2617 IsMemberOperatorCall; 2618 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2619 TheCall->getCallee()); 2620 Expr** Args = TheCall->getArgs(); 2621 unsigned NumArgs = TheCall->getNumArgs(); 2622 2623 Expr *ImplicitThis = nullptr; 2624 if (IsMemberOperatorCall) { 2625 // If this is a call to a member operator, hide the first argument 2626 // from checkCall. 2627 // FIXME: Our choice of AST representation here is less than ideal. 2628 ImplicitThis = Args[0]; 2629 ++Args; 2630 --NumArgs; 2631 } else if (IsMemberFunction) 2632 ImplicitThis = 2633 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 2634 2635 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 2636 IsMemberFunction, TheCall->getRParenLoc(), 2637 TheCall->getCallee()->getSourceRange(), CallType); 2638 2639 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2640 // None of the checks below are needed for functions that don't have 2641 // simple names (e.g., C++ conversion functions). 2642 if (!FnInfo) 2643 return false; 2644 2645 CheckAbsoluteValueFunction(TheCall, FDecl); 2646 CheckMaxUnsignedZero(TheCall, FDecl); 2647 2648 if (getLangOpts().ObjC1) 2649 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2650 2651 unsigned CMId = FDecl->getMemoryFunctionKind(); 2652 if (CMId == 0) 2653 return false; 2654 2655 // Handle memory setting and copying functions. 2656 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2657 CheckStrlcpycatArguments(TheCall, FnInfo); 2658 else if (CMId == Builtin::BIstrncat) 2659 CheckStrncatArguments(TheCall, FnInfo); 2660 else 2661 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2662 2663 return false; 2664 } 2665 2666 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2667 ArrayRef<const Expr *> Args) { 2668 VariadicCallType CallType = 2669 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2670 2671 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 2672 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2673 CallType); 2674 2675 return false; 2676 } 2677 2678 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2679 const FunctionProtoType *Proto) { 2680 QualType Ty; 2681 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2682 Ty = V->getType().getNonReferenceType(); 2683 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2684 Ty = F->getType().getNonReferenceType(); 2685 else 2686 return false; 2687 2688 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2689 !Ty->isFunctionProtoType()) 2690 return false; 2691 2692 VariadicCallType CallType; 2693 if (!Proto || !Proto->isVariadic()) { 2694 CallType = VariadicDoesNotApply; 2695 } else if (Ty->isBlockPointerType()) { 2696 CallType = VariadicBlock; 2697 } else { // Ty->isFunctionPointerType() 2698 CallType = VariadicFunction; 2699 } 2700 2701 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 2702 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2703 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2704 TheCall->getCallee()->getSourceRange(), CallType); 2705 2706 return false; 2707 } 2708 2709 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2710 /// such as function pointers returned from functions. 2711 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2712 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2713 TheCall->getCallee()); 2714 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 2715 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2716 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2717 TheCall->getCallee()->getSourceRange(), CallType); 2718 2719 return false; 2720 } 2721 2722 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2723 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2724 return false; 2725 2726 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2727 switch (Op) { 2728 case AtomicExpr::AO__c11_atomic_init: 2729 llvm_unreachable("There is no ordering argument for an init"); 2730 2731 case AtomicExpr::AO__c11_atomic_load: 2732 case AtomicExpr::AO__atomic_load_n: 2733 case AtomicExpr::AO__atomic_load: 2734 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2735 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2736 2737 case AtomicExpr::AO__c11_atomic_store: 2738 case AtomicExpr::AO__atomic_store: 2739 case AtomicExpr::AO__atomic_store_n: 2740 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2741 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2742 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2743 2744 default: 2745 return true; 2746 } 2747 } 2748 2749 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2750 AtomicExpr::AtomicOp Op) { 2751 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2752 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2753 2754 // All these operations take one of the following forms: 2755 enum { 2756 // C __c11_atomic_init(A *, C) 2757 Init, 2758 // C __c11_atomic_load(A *, int) 2759 Load, 2760 // void __atomic_load(A *, CP, int) 2761 LoadCopy, 2762 // void __atomic_store(A *, CP, int) 2763 Copy, 2764 // C __c11_atomic_add(A *, M, int) 2765 Arithmetic, 2766 // C __atomic_exchange_n(A *, CP, int) 2767 Xchg, 2768 // void __atomic_exchange(A *, C *, CP, int) 2769 GNUXchg, 2770 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2771 C11CmpXchg, 2772 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2773 GNUCmpXchg 2774 } Form = Init; 2775 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2776 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2777 // where: 2778 // C is an appropriate type, 2779 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2780 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2781 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2782 // the int parameters are for orderings. 2783 2784 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2785 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2786 AtomicExpr::AO__atomic_load, 2787 "need to update code for modified C11 atomics"); 2788 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 2789 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 2790 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2791 Op == AtomicExpr::AO__atomic_store_n || 2792 Op == AtomicExpr::AO__atomic_exchange_n || 2793 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2794 bool IsAddSub = false; 2795 2796 switch (Op) { 2797 case AtomicExpr::AO__c11_atomic_init: 2798 Form = Init; 2799 break; 2800 2801 case AtomicExpr::AO__c11_atomic_load: 2802 case AtomicExpr::AO__atomic_load_n: 2803 Form = Load; 2804 break; 2805 2806 case AtomicExpr::AO__atomic_load: 2807 Form = LoadCopy; 2808 break; 2809 2810 case AtomicExpr::AO__c11_atomic_store: 2811 case AtomicExpr::AO__atomic_store: 2812 case AtomicExpr::AO__atomic_store_n: 2813 Form = Copy; 2814 break; 2815 2816 case AtomicExpr::AO__c11_atomic_fetch_add: 2817 case AtomicExpr::AO__c11_atomic_fetch_sub: 2818 case AtomicExpr::AO__atomic_fetch_add: 2819 case AtomicExpr::AO__atomic_fetch_sub: 2820 case AtomicExpr::AO__atomic_add_fetch: 2821 case AtomicExpr::AO__atomic_sub_fetch: 2822 IsAddSub = true; 2823 // Fall through. 2824 case AtomicExpr::AO__c11_atomic_fetch_and: 2825 case AtomicExpr::AO__c11_atomic_fetch_or: 2826 case AtomicExpr::AO__c11_atomic_fetch_xor: 2827 case AtomicExpr::AO__atomic_fetch_and: 2828 case AtomicExpr::AO__atomic_fetch_or: 2829 case AtomicExpr::AO__atomic_fetch_xor: 2830 case AtomicExpr::AO__atomic_fetch_nand: 2831 case AtomicExpr::AO__atomic_and_fetch: 2832 case AtomicExpr::AO__atomic_or_fetch: 2833 case AtomicExpr::AO__atomic_xor_fetch: 2834 case AtomicExpr::AO__atomic_nand_fetch: 2835 Form = Arithmetic; 2836 break; 2837 2838 case AtomicExpr::AO__c11_atomic_exchange: 2839 case AtomicExpr::AO__atomic_exchange_n: 2840 Form = Xchg; 2841 break; 2842 2843 case AtomicExpr::AO__atomic_exchange: 2844 Form = GNUXchg; 2845 break; 2846 2847 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2848 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2849 Form = C11CmpXchg; 2850 break; 2851 2852 case AtomicExpr::AO__atomic_compare_exchange: 2853 case AtomicExpr::AO__atomic_compare_exchange_n: 2854 Form = GNUCmpXchg; 2855 break; 2856 } 2857 2858 // Check we have the right number of arguments. 2859 if (TheCall->getNumArgs() < NumArgs[Form]) { 2860 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2861 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2862 << TheCall->getCallee()->getSourceRange(); 2863 return ExprError(); 2864 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 2865 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 2866 diag::err_typecheck_call_too_many_args) 2867 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2868 << TheCall->getCallee()->getSourceRange(); 2869 return ExprError(); 2870 } 2871 2872 // Inspect the first argument of the atomic operation. 2873 Expr *Ptr = TheCall->getArg(0); 2874 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2875 if (ConvertedPtr.isInvalid()) 2876 return ExprError(); 2877 2878 Ptr = ConvertedPtr.get(); 2879 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2880 if (!pointerType) { 2881 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2882 << Ptr->getType() << Ptr->getSourceRange(); 2883 return ExprError(); 2884 } 2885 2886 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2887 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2888 QualType ValType = AtomTy; // 'C' 2889 if (IsC11) { 2890 if (!AtomTy->isAtomicType()) { 2891 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 2892 << Ptr->getType() << Ptr->getSourceRange(); 2893 return ExprError(); 2894 } 2895 if (AtomTy.isConstQualified()) { 2896 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 2897 << Ptr->getType() << Ptr->getSourceRange(); 2898 return ExprError(); 2899 } 2900 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 2901 } else if (Form != Load && Form != LoadCopy) { 2902 if (ValType.isConstQualified()) { 2903 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 2904 << Ptr->getType() << Ptr->getSourceRange(); 2905 return ExprError(); 2906 } 2907 } 2908 2909 // For an arithmetic operation, the implied arithmetic must be well-formed. 2910 if (Form == Arithmetic) { 2911 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 2912 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 2913 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2914 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2915 return ExprError(); 2916 } 2917 if (!IsAddSub && !ValType->isIntegerType()) { 2918 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 2919 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2920 return ExprError(); 2921 } 2922 if (IsC11 && ValType->isPointerType() && 2923 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 2924 diag::err_incomplete_type)) { 2925 return ExprError(); 2926 } 2927 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 2928 // For __atomic_*_n operations, the value type must be a scalar integral or 2929 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 2930 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2931 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2932 return ExprError(); 2933 } 2934 2935 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 2936 !AtomTy->isScalarType()) { 2937 // For GNU atomics, require a trivially-copyable type. This is not part of 2938 // the GNU atomics specification, but we enforce it for sanity. 2939 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 2940 << Ptr->getType() << Ptr->getSourceRange(); 2941 return ExprError(); 2942 } 2943 2944 switch (ValType.getObjCLifetime()) { 2945 case Qualifiers::OCL_None: 2946 case Qualifiers::OCL_ExplicitNone: 2947 // okay 2948 break; 2949 2950 case Qualifiers::OCL_Weak: 2951 case Qualifiers::OCL_Strong: 2952 case Qualifiers::OCL_Autoreleasing: 2953 // FIXME: Can this happen? By this point, ValType should be known 2954 // to be trivially copyable. 2955 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 2956 << ValType << Ptr->getSourceRange(); 2957 return ExprError(); 2958 } 2959 2960 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 2961 // volatile-ness of the pointee-type inject itself into the result or the 2962 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 2963 ValType.removeLocalVolatile(); 2964 ValType.removeLocalConst(); 2965 QualType ResultType = ValType; 2966 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init) 2967 ResultType = Context.VoidTy; 2968 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 2969 ResultType = Context.BoolTy; 2970 2971 // The type of a parameter passed 'by value'. In the GNU atomics, such 2972 // arguments are actually passed as pointers. 2973 QualType ByValType = ValType; // 'CP' 2974 if (!IsC11 && !IsN) 2975 ByValType = Ptr->getType(); 2976 2977 // The first argument --- the pointer --- has a fixed type; we 2978 // deduce the types of the rest of the arguments accordingly. Walk 2979 // the remaining arguments, converting them to the deduced value type. 2980 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 2981 QualType Ty; 2982 if (i < NumVals[Form] + 1) { 2983 switch (i) { 2984 case 1: 2985 // The second argument is the non-atomic operand. For arithmetic, this 2986 // is always passed by value, and for a compare_exchange it is always 2987 // passed by address. For the rest, GNU uses by-address and C11 uses 2988 // by-value. 2989 assert(Form != Load); 2990 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 2991 Ty = ValType; 2992 else if (Form == Copy || Form == Xchg) 2993 Ty = ByValType; 2994 else if (Form == Arithmetic) 2995 Ty = Context.getPointerDiffType(); 2996 else { 2997 Expr *ValArg = TheCall->getArg(i); 2998 // Treat this argument as _Nonnull as we want to show a warning if 2999 // NULL is passed into it. 3000 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3001 unsigned AS = 0; 3002 // Keep address space of non-atomic pointer type. 3003 if (const PointerType *PtrTy = 3004 ValArg->getType()->getAs<PointerType>()) { 3005 AS = PtrTy->getPointeeType().getAddressSpace(); 3006 } 3007 Ty = Context.getPointerType( 3008 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3009 } 3010 break; 3011 case 2: 3012 // The third argument to compare_exchange / GNU exchange is a 3013 // (pointer to a) desired value. 3014 Ty = ByValType; 3015 break; 3016 case 3: 3017 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3018 Ty = Context.BoolTy; 3019 break; 3020 } 3021 } else { 3022 // The order(s) are always converted to int. 3023 Ty = Context.IntTy; 3024 } 3025 3026 InitializedEntity Entity = 3027 InitializedEntity::InitializeParameter(Context, Ty, false); 3028 ExprResult Arg = TheCall->getArg(i); 3029 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3030 if (Arg.isInvalid()) 3031 return true; 3032 TheCall->setArg(i, Arg.get()); 3033 } 3034 3035 // Permute the arguments into a 'consistent' order. 3036 SmallVector<Expr*, 5> SubExprs; 3037 SubExprs.push_back(Ptr); 3038 switch (Form) { 3039 case Init: 3040 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3041 SubExprs.push_back(TheCall->getArg(1)); // Val1 3042 break; 3043 case Load: 3044 SubExprs.push_back(TheCall->getArg(1)); // Order 3045 break; 3046 case LoadCopy: 3047 case Copy: 3048 case Arithmetic: 3049 case Xchg: 3050 SubExprs.push_back(TheCall->getArg(2)); // Order 3051 SubExprs.push_back(TheCall->getArg(1)); // Val1 3052 break; 3053 case GNUXchg: 3054 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3055 SubExprs.push_back(TheCall->getArg(3)); // Order 3056 SubExprs.push_back(TheCall->getArg(1)); // Val1 3057 SubExprs.push_back(TheCall->getArg(2)); // Val2 3058 break; 3059 case C11CmpXchg: 3060 SubExprs.push_back(TheCall->getArg(3)); // Order 3061 SubExprs.push_back(TheCall->getArg(1)); // Val1 3062 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3063 SubExprs.push_back(TheCall->getArg(2)); // Val2 3064 break; 3065 case GNUCmpXchg: 3066 SubExprs.push_back(TheCall->getArg(4)); // Order 3067 SubExprs.push_back(TheCall->getArg(1)); // Val1 3068 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3069 SubExprs.push_back(TheCall->getArg(2)); // Val2 3070 SubExprs.push_back(TheCall->getArg(3)); // Weak 3071 break; 3072 } 3073 3074 if (SubExprs.size() >= 2 && Form != Init) { 3075 llvm::APSInt Result(32); 3076 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3077 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3078 Diag(SubExprs[1]->getLocStart(), 3079 diag::warn_atomic_op_has_invalid_memory_order) 3080 << SubExprs[1]->getSourceRange(); 3081 } 3082 3083 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3084 SubExprs, ResultType, Op, 3085 TheCall->getRParenLoc()); 3086 3087 if ((Op == AtomicExpr::AO__c11_atomic_load || 3088 (Op == AtomicExpr::AO__c11_atomic_store)) && 3089 Context.AtomicUsesUnsupportedLibcall(AE)) 3090 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 3091 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 3092 3093 return AE; 3094 } 3095 3096 /// checkBuiltinArgument - Given a call to a builtin function, perform 3097 /// normal type-checking on the given argument, updating the call in 3098 /// place. This is useful when a builtin function requires custom 3099 /// type-checking for some of its arguments but not necessarily all of 3100 /// them. 3101 /// 3102 /// Returns true on error. 3103 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3104 FunctionDecl *Fn = E->getDirectCallee(); 3105 assert(Fn && "builtin call without direct callee!"); 3106 3107 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3108 InitializedEntity Entity = 3109 InitializedEntity::InitializeParameter(S.Context, Param); 3110 3111 ExprResult Arg = E->getArg(0); 3112 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3113 if (Arg.isInvalid()) 3114 return true; 3115 3116 E->setArg(ArgIndex, Arg.get()); 3117 return false; 3118 } 3119 3120 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3121 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3122 /// type of its first argument. The main ActOnCallExpr routines have already 3123 /// promoted the types of arguments because all of these calls are prototyped as 3124 /// void(...). 3125 /// 3126 /// This function goes through and does final semantic checking for these 3127 /// builtins, 3128 ExprResult 3129 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3130 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3131 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3132 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3133 3134 // Ensure that we have at least one argument to do type inference from. 3135 if (TheCall->getNumArgs() < 1) { 3136 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3137 << 0 << 1 << TheCall->getNumArgs() 3138 << TheCall->getCallee()->getSourceRange(); 3139 return ExprError(); 3140 } 3141 3142 // Inspect the first argument of the atomic builtin. This should always be 3143 // a pointer type, whose element is an integral scalar or pointer type. 3144 // Because it is a pointer type, we don't have to worry about any implicit 3145 // casts here. 3146 // FIXME: We don't allow floating point scalars as input. 3147 Expr *FirstArg = TheCall->getArg(0); 3148 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3149 if (FirstArgResult.isInvalid()) 3150 return ExprError(); 3151 FirstArg = FirstArgResult.get(); 3152 TheCall->setArg(0, FirstArg); 3153 3154 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3155 if (!pointerType) { 3156 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3157 << FirstArg->getType() << FirstArg->getSourceRange(); 3158 return ExprError(); 3159 } 3160 3161 QualType ValType = pointerType->getPointeeType(); 3162 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3163 !ValType->isBlockPointerType()) { 3164 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3165 << FirstArg->getType() << FirstArg->getSourceRange(); 3166 return ExprError(); 3167 } 3168 3169 switch (ValType.getObjCLifetime()) { 3170 case Qualifiers::OCL_None: 3171 case Qualifiers::OCL_ExplicitNone: 3172 // okay 3173 break; 3174 3175 case Qualifiers::OCL_Weak: 3176 case Qualifiers::OCL_Strong: 3177 case Qualifiers::OCL_Autoreleasing: 3178 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3179 << ValType << FirstArg->getSourceRange(); 3180 return ExprError(); 3181 } 3182 3183 // Strip any qualifiers off ValType. 3184 ValType = ValType.getUnqualifiedType(); 3185 3186 // The majority of builtins return a value, but a few have special return 3187 // types, so allow them to override appropriately below. 3188 QualType ResultType = ValType; 3189 3190 // We need to figure out which concrete builtin this maps onto. For example, 3191 // __sync_fetch_and_add with a 2 byte object turns into 3192 // __sync_fetch_and_add_2. 3193 #define BUILTIN_ROW(x) \ 3194 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3195 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3196 3197 static const unsigned BuiltinIndices[][5] = { 3198 BUILTIN_ROW(__sync_fetch_and_add), 3199 BUILTIN_ROW(__sync_fetch_and_sub), 3200 BUILTIN_ROW(__sync_fetch_and_or), 3201 BUILTIN_ROW(__sync_fetch_and_and), 3202 BUILTIN_ROW(__sync_fetch_and_xor), 3203 BUILTIN_ROW(__sync_fetch_and_nand), 3204 3205 BUILTIN_ROW(__sync_add_and_fetch), 3206 BUILTIN_ROW(__sync_sub_and_fetch), 3207 BUILTIN_ROW(__sync_and_and_fetch), 3208 BUILTIN_ROW(__sync_or_and_fetch), 3209 BUILTIN_ROW(__sync_xor_and_fetch), 3210 BUILTIN_ROW(__sync_nand_and_fetch), 3211 3212 BUILTIN_ROW(__sync_val_compare_and_swap), 3213 BUILTIN_ROW(__sync_bool_compare_and_swap), 3214 BUILTIN_ROW(__sync_lock_test_and_set), 3215 BUILTIN_ROW(__sync_lock_release), 3216 BUILTIN_ROW(__sync_swap) 3217 }; 3218 #undef BUILTIN_ROW 3219 3220 // Determine the index of the size. 3221 unsigned SizeIndex; 3222 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3223 case 1: SizeIndex = 0; break; 3224 case 2: SizeIndex = 1; break; 3225 case 4: SizeIndex = 2; break; 3226 case 8: SizeIndex = 3; break; 3227 case 16: SizeIndex = 4; break; 3228 default: 3229 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3230 << FirstArg->getType() << FirstArg->getSourceRange(); 3231 return ExprError(); 3232 } 3233 3234 // Each of these builtins has one pointer argument, followed by some number of 3235 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3236 // that we ignore. Find out which row of BuiltinIndices to read from as well 3237 // as the number of fixed args. 3238 unsigned BuiltinID = FDecl->getBuiltinID(); 3239 unsigned BuiltinIndex, NumFixed = 1; 3240 bool WarnAboutSemanticsChange = false; 3241 switch (BuiltinID) { 3242 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3243 case Builtin::BI__sync_fetch_and_add: 3244 case Builtin::BI__sync_fetch_and_add_1: 3245 case Builtin::BI__sync_fetch_and_add_2: 3246 case Builtin::BI__sync_fetch_and_add_4: 3247 case Builtin::BI__sync_fetch_and_add_8: 3248 case Builtin::BI__sync_fetch_and_add_16: 3249 BuiltinIndex = 0; 3250 break; 3251 3252 case Builtin::BI__sync_fetch_and_sub: 3253 case Builtin::BI__sync_fetch_and_sub_1: 3254 case Builtin::BI__sync_fetch_and_sub_2: 3255 case Builtin::BI__sync_fetch_and_sub_4: 3256 case Builtin::BI__sync_fetch_and_sub_8: 3257 case Builtin::BI__sync_fetch_and_sub_16: 3258 BuiltinIndex = 1; 3259 break; 3260 3261 case Builtin::BI__sync_fetch_and_or: 3262 case Builtin::BI__sync_fetch_and_or_1: 3263 case Builtin::BI__sync_fetch_and_or_2: 3264 case Builtin::BI__sync_fetch_and_or_4: 3265 case Builtin::BI__sync_fetch_and_or_8: 3266 case Builtin::BI__sync_fetch_and_or_16: 3267 BuiltinIndex = 2; 3268 break; 3269 3270 case Builtin::BI__sync_fetch_and_and: 3271 case Builtin::BI__sync_fetch_and_and_1: 3272 case Builtin::BI__sync_fetch_and_and_2: 3273 case Builtin::BI__sync_fetch_and_and_4: 3274 case Builtin::BI__sync_fetch_and_and_8: 3275 case Builtin::BI__sync_fetch_and_and_16: 3276 BuiltinIndex = 3; 3277 break; 3278 3279 case Builtin::BI__sync_fetch_and_xor: 3280 case Builtin::BI__sync_fetch_and_xor_1: 3281 case Builtin::BI__sync_fetch_and_xor_2: 3282 case Builtin::BI__sync_fetch_and_xor_4: 3283 case Builtin::BI__sync_fetch_and_xor_8: 3284 case Builtin::BI__sync_fetch_and_xor_16: 3285 BuiltinIndex = 4; 3286 break; 3287 3288 case Builtin::BI__sync_fetch_and_nand: 3289 case Builtin::BI__sync_fetch_and_nand_1: 3290 case Builtin::BI__sync_fetch_and_nand_2: 3291 case Builtin::BI__sync_fetch_and_nand_4: 3292 case Builtin::BI__sync_fetch_and_nand_8: 3293 case Builtin::BI__sync_fetch_and_nand_16: 3294 BuiltinIndex = 5; 3295 WarnAboutSemanticsChange = true; 3296 break; 3297 3298 case Builtin::BI__sync_add_and_fetch: 3299 case Builtin::BI__sync_add_and_fetch_1: 3300 case Builtin::BI__sync_add_and_fetch_2: 3301 case Builtin::BI__sync_add_and_fetch_4: 3302 case Builtin::BI__sync_add_and_fetch_8: 3303 case Builtin::BI__sync_add_and_fetch_16: 3304 BuiltinIndex = 6; 3305 break; 3306 3307 case Builtin::BI__sync_sub_and_fetch: 3308 case Builtin::BI__sync_sub_and_fetch_1: 3309 case Builtin::BI__sync_sub_and_fetch_2: 3310 case Builtin::BI__sync_sub_and_fetch_4: 3311 case Builtin::BI__sync_sub_and_fetch_8: 3312 case Builtin::BI__sync_sub_and_fetch_16: 3313 BuiltinIndex = 7; 3314 break; 3315 3316 case Builtin::BI__sync_and_and_fetch: 3317 case Builtin::BI__sync_and_and_fetch_1: 3318 case Builtin::BI__sync_and_and_fetch_2: 3319 case Builtin::BI__sync_and_and_fetch_4: 3320 case Builtin::BI__sync_and_and_fetch_8: 3321 case Builtin::BI__sync_and_and_fetch_16: 3322 BuiltinIndex = 8; 3323 break; 3324 3325 case Builtin::BI__sync_or_and_fetch: 3326 case Builtin::BI__sync_or_and_fetch_1: 3327 case Builtin::BI__sync_or_and_fetch_2: 3328 case Builtin::BI__sync_or_and_fetch_4: 3329 case Builtin::BI__sync_or_and_fetch_8: 3330 case Builtin::BI__sync_or_and_fetch_16: 3331 BuiltinIndex = 9; 3332 break; 3333 3334 case Builtin::BI__sync_xor_and_fetch: 3335 case Builtin::BI__sync_xor_and_fetch_1: 3336 case Builtin::BI__sync_xor_and_fetch_2: 3337 case Builtin::BI__sync_xor_and_fetch_4: 3338 case Builtin::BI__sync_xor_and_fetch_8: 3339 case Builtin::BI__sync_xor_and_fetch_16: 3340 BuiltinIndex = 10; 3341 break; 3342 3343 case Builtin::BI__sync_nand_and_fetch: 3344 case Builtin::BI__sync_nand_and_fetch_1: 3345 case Builtin::BI__sync_nand_and_fetch_2: 3346 case Builtin::BI__sync_nand_and_fetch_4: 3347 case Builtin::BI__sync_nand_and_fetch_8: 3348 case Builtin::BI__sync_nand_and_fetch_16: 3349 BuiltinIndex = 11; 3350 WarnAboutSemanticsChange = true; 3351 break; 3352 3353 case Builtin::BI__sync_val_compare_and_swap: 3354 case Builtin::BI__sync_val_compare_and_swap_1: 3355 case Builtin::BI__sync_val_compare_and_swap_2: 3356 case Builtin::BI__sync_val_compare_and_swap_4: 3357 case Builtin::BI__sync_val_compare_and_swap_8: 3358 case Builtin::BI__sync_val_compare_and_swap_16: 3359 BuiltinIndex = 12; 3360 NumFixed = 2; 3361 break; 3362 3363 case Builtin::BI__sync_bool_compare_and_swap: 3364 case Builtin::BI__sync_bool_compare_and_swap_1: 3365 case Builtin::BI__sync_bool_compare_and_swap_2: 3366 case Builtin::BI__sync_bool_compare_and_swap_4: 3367 case Builtin::BI__sync_bool_compare_and_swap_8: 3368 case Builtin::BI__sync_bool_compare_and_swap_16: 3369 BuiltinIndex = 13; 3370 NumFixed = 2; 3371 ResultType = Context.BoolTy; 3372 break; 3373 3374 case Builtin::BI__sync_lock_test_and_set: 3375 case Builtin::BI__sync_lock_test_and_set_1: 3376 case Builtin::BI__sync_lock_test_and_set_2: 3377 case Builtin::BI__sync_lock_test_and_set_4: 3378 case Builtin::BI__sync_lock_test_and_set_8: 3379 case Builtin::BI__sync_lock_test_and_set_16: 3380 BuiltinIndex = 14; 3381 break; 3382 3383 case Builtin::BI__sync_lock_release: 3384 case Builtin::BI__sync_lock_release_1: 3385 case Builtin::BI__sync_lock_release_2: 3386 case Builtin::BI__sync_lock_release_4: 3387 case Builtin::BI__sync_lock_release_8: 3388 case Builtin::BI__sync_lock_release_16: 3389 BuiltinIndex = 15; 3390 NumFixed = 0; 3391 ResultType = Context.VoidTy; 3392 break; 3393 3394 case Builtin::BI__sync_swap: 3395 case Builtin::BI__sync_swap_1: 3396 case Builtin::BI__sync_swap_2: 3397 case Builtin::BI__sync_swap_4: 3398 case Builtin::BI__sync_swap_8: 3399 case Builtin::BI__sync_swap_16: 3400 BuiltinIndex = 16; 3401 break; 3402 } 3403 3404 // Now that we know how many fixed arguments we expect, first check that we 3405 // have at least that many. 3406 if (TheCall->getNumArgs() < 1+NumFixed) { 3407 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3408 << 0 << 1+NumFixed << TheCall->getNumArgs() 3409 << TheCall->getCallee()->getSourceRange(); 3410 return ExprError(); 3411 } 3412 3413 if (WarnAboutSemanticsChange) { 3414 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3415 << TheCall->getCallee()->getSourceRange(); 3416 } 3417 3418 // Get the decl for the concrete builtin from this, we can tell what the 3419 // concrete integer type we should convert to is. 3420 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3421 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3422 FunctionDecl *NewBuiltinDecl; 3423 if (NewBuiltinID == BuiltinID) 3424 NewBuiltinDecl = FDecl; 3425 else { 3426 // Perform builtin lookup to avoid redeclaring it. 3427 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3428 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3429 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3430 assert(Res.getFoundDecl()); 3431 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3432 if (!NewBuiltinDecl) 3433 return ExprError(); 3434 } 3435 3436 // The first argument --- the pointer --- has a fixed type; we 3437 // deduce the types of the rest of the arguments accordingly. Walk 3438 // the remaining arguments, converting them to the deduced value type. 3439 for (unsigned i = 0; i != NumFixed; ++i) { 3440 ExprResult Arg = TheCall->getArg(i+1); 3441 3442 // GCC does an implicit conversion to the pointer or integer ValType. This 3443 // can fail in some cases (1i -> int**), check for this error case now. 3444 // Initialize the argument. 3445 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3446 ValType, /*consume*/ false); 3447 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3448 if (Arg.isInvalid()) 3449 return ExprError(); 3450 3451 // Okay, we have something that *can* be converted to the right type. Check 3452 // to see if there is a potentially weird extension going on here. This can 3453 // happen when you do an atomic operation on something like an char* and 3454 // pass in 42. The 42 gets converted to char. This is even more strange 3455 // for things like 45.123 -> char, etc. 3456 // FIXME: Do this check. 3457 TheCall->setArg(i+1, Arg.get()); 3458 } 3459 3460 ASTContext& Context = this->getASTContext(); 3461 3462 // Create a new DeclRefExpr to refer to the new decl. 3463 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3464 Context, 3465 DRE->getQualifierLoc(), 3466 SourceLocation(), 3467 NewBuiltinDecl, 3468 /*enclosing*/ false, 3469 DRE->getLocation(), 3470 Context.BuiltinFnTy, 3471 DRE->getValueKind()); 3472 3473 // Set the callee in the CallExpr. 3474 // FIXME: This loses syntactic information. 3475 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3476 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3477 CK_BuiltinFnToFnPtr); 3478 TheCall->setCallee(PromotedCall.get()); 3479 3480 // Change the result type of the call to match the original value type. This 3481 // is arbitrary, but the codegen for these builtins ins design to handle it 3482 // gracefully. 3483 TheCall->setType(ResultType); 3484 3485 return TheCallResult; 3486 } 3487 3488 /// SemaBuiltinNontemporalOverloaded - We have a call to 3489 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3490 /// overloaded function based on the pointer type of its last argument. 3491 /// 3492 /// This function goes through and does final semantic checking for these 3493 /// builtins. 3494 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3495 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3496 DeclRefExpr *DRE = 3497 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3498 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3499 unsigned BuiltinID = FDecl->getBuiltinID(); 3500 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3501 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3502 "Unexpected nontemporal load/store builtin!"); 3503 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3504 unsigned numArgs = isStore ? 2 : 1; 3505 3506 // Ensure that we have the proper number of arguments. 3507 if (checkArgCount(*this, TheCall, numArgs)) 3508 return ExprError(); 3509 3510 // Inspect the last argument of the nontemporal builtin. This should always 3511 // be a pointer type, from which we imply the type of the memory access. 3512 // Because it is a pointer type, we don't have to worry about any implicit 3513 // casts here. 3514 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3515 ExprResult PointerArgResult = 3516 DefaultFunctionArrayLvalueConversion(PointerArg); 3517 3518 if (PointerArgResult.isInvalid()) 3519 return ExprError(); 3520 PointerArg = PointerArgResult.get(); 3521 TheCall->setArg(numArgs - 1, PointerArg); 3522 3523 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3524 if (!pointerType) { 3525 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3526 << PointerArg->getType() << PointerArg->getSourceRange(); 3527 return ExprError(); 3528 } 3529 3530 QualType ValType = pointerType->getPointeeType(); 3531 3532 // Strip any qualifiers off ValType. 3533 ValType = ValType.getUnqualifiedType(); 3534 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3535 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3536 !ValType->isVectorType()) { 3537 Diag(DRE->getLocStart(), 3538 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3539 << PointerArg->getType() << PointerArg->getSourceRange(); 3540 return ExprError(); 3541 } 3542 3543 if (!isStore) { 3544 TheCall->setType(ValType); 3545 return TheCallResult; 3546 } 3547 3548 ExprResult ValArg = TheCall->getArg(0); 3549 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3550 Context, ValType, /*consume*/ false); 3551 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3552 if (ValArg.isInvalid()) 3553 return ExprError(); 3554 3555 TheCall->setArg(0, ValArg.get()); 3556 TheCall->setType(Context.VoidTy); 3557 return TheCallResult; 3558 } 3559 3560 /// CheckObjCString - Checks that the argument to the builtin 3561 /// CFString constructor is correct 3562 /// Note: It might also make sense to do the UTF-16 conversion here (would 3563 /// simplify the backend). 3564 bool Sema::CheckObjCString(Expr *Arg) { 3565 Arg = Arg->IgnoreParenCasts(); 3566 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3567 3568 if (!Literal || !Literal->isAscii()) { 3569 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3570 << Arg->getSourceRange(); 3571 return true; 3572 } 3573 3574 if (Literal->containsNonAsciiOrNull()) { 3575 StringRef String = Literal->getString(); 3576 unsigned NumBytes = String.size(); 3577 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3578 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3579 llvm::UTF16 *ToPtr = &ToBuf[0]; 3580 3581 llvm::ConversionResult Result = 3582 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3583 ToPtr + NumBytes, llvm::strictConversion); 3584 // Check for conversion failure. 3585 if (Result != llvm::conversionOK) 3586 Diag(Arg->getLocStart(), 3587 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3588 } 3589 return false; 3590 } 3591 3592 /// CheckObjCString - Checks that the format string argument to the os_log() 3593 /// and os_trace() functions is correct, and converts it to const char *. 3594 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3595 Arg = Arg->IgnoreParenCasts(); 3596 auto *Literal = dyn_cast<StringLiteral>(Arg); 3597 if (!Literal) { 3598 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3599 Literal = ObjcLiteral->getString(); 3600 } 3601 } 3602 3603 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3604 return ExprError( 3605 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3606 << Arg->getSourceRange()); 3607 } 3608 3609 ExprResult Result(Literal); 3610 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3611 InitializedEntity Entity = 3612 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3613 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3614 return Result; 3615 } 3616 3617 /// Check that the user is calling the appropriate va_start builtin for the 3618 /// target and calling convention. 3619 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 3620 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 3621 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 3622 bool IsWindows = TT.isOSWindows(); 3623 bool IsMSVAStart = BuiltinID == X86::BI__builtin_ms_va_start; 3624 if (IsX64) { 3625 clang::CallingConv CC = CC_C; 3626 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 3627 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3628 if (IsMSVAStart) { 3629 // Don't allow this in System V ABI functions. 3630 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_X86_64Win64)) 3631 return S.Diag(Fn->getLocStart(), 3632 diag::err_ms_va_start_used_in_sysv_function); 3633 } else { 3634 // On x86-64 Unix, don't allow this in Win64 ABI functions. 3635 // On x64 Windows, don't allow this in System V ABI functions. 3636 // (Yes, that means there's no corresponding way to support variadic 3637 // System V ABI functions on Windows.) 3638 if ((IsWindows && CC == CC_X86_64SysV) || 3639 (!IsWindows && CC == CC_X86_64Win64)) 3640 return S.Diag(Fn->getLocStart(), 3641 diag::err_va_start_used_in_wrong_abi_function) 3642 << !IsWindows; 3643 } 3644 return false; 3645 } 3646 3647 if (IsMSVAStart) 3648 return S.Diag(Fn->getLocStart(), diag::err_x86_builtin_64_only); 3649 return false; 3650 } 3651 3652 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 3653 ParmVarDecl **LastParam = nullptr) { 3654 // Determine whether the current function, block, or obj-c method is variadic 3655 // and get its parameter list. 3656 bool IsVariadic = false; 3657 ArrayRef<ParmVarDecl *> Params; 3658 DeclContext *Caller = S.CurContext; 3659 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 3660 IsVariadic = Block->isVariadic(); 3661 Params = Block->parameters(); 3662 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 3663 IsVariadic = FD->isVariadic(); 3664 Params = FD->parameters(); 3665 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 3666 IsVariadic = MD->isVariadic(); 3667 // FIXME: This isn't correct for methods (results in bogus warning). 3668 Params = MD->parameters(); 3669 } else if (isa<CapturedDecl>(Caller)) { 3670 // We don't support va_start in a CapturedDecl. 3671 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 3672 return true; 3673 } else { 3674 // This must be some other declcontext that parses exprs. 3675 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 3676 return true; 3677 } 3678 3679 if (!IsVariadic) { 3680 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 3681 return true; 3682 } 3683 3684 if (LastParam) 3685 *LastParam = Params.empty() ? nullptr : Params.back(); 3686 3687 return false; 3688 } 3689 3690 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3691 /// for validity. Emit an error and return true on failure; return false 3692 /// on success. 3693 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 3694 Expr *Fn = TheCall->getCallee(); 3695 3696 if (checkVAStartABI(*this, BuiltinID, Fn)) 3697 return true; 3698 3699 if (TheCall->getNumArgs() > 2) { 3700 Diag(TheCall->getArg(2)->getLocStart(), 3701 diag::err_typecheck_call_too_many_args) 3702 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3703 << Fn->getSourceRange() 3704 << SourceRange(TheCall->getArg(2)->getLocStart(), 3705 (*(TheCall->arg_end()-1))->getLocEnd()); 3706 return true; 3707 } 3708 3709 if (TheCall->getNumArgs() < 2) { 3710 return Diag(TheCall->getLocEnd(), 3711 diag::err_typecheck_call_too_few_args_at_least) 3712 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3713 } 3714 3715 // Type-check the first argument normally. 3716 if (checkBuiltinArgument(*this, TheCall, 0)) 3717 return true; 3718 3719 // Check that the current function is variadic, and get its last parameter. 3720 ParmVarDecl *LastParam; 3721 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 3722 return true; 3723 3724 // Verify that the second argument to the builtin is the last argument of the 3725 // current function or method. 3726 bool SecondArgIsLastNamedArgument = false; 3727 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3728 3729 // These are valid if SecondArgIsLastNamedArgument is false after the next 3730 // block. 3731 QualType Type; 3732 SourceLocation ParamLoc; 3733 bool IsCRegister = false; 3734 3735 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3736 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3737 SecondArgIsLastNamedArgument = PV == LastParam; 3738 3739 Type = PV->getType(); 3740 ParamLoc = PV->getLocation(); 3741 IsCRegister = 3742 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3743 } 3744 } 3745 3746 if (!SecondArgIsLastNamedArgument) 3747 Diag(TheCall->getArg(1)->getLocStart(), 3748 diag::warn_second_arg_of_va_start_not_last_named_param); 3749 else if (IsCRegister || Type->isReferenceType() || 3750 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3751 // Promotable integers are UB, but enumerations need a bit of 3752 // extra checking to see what their promotable type actually is. 3753 if (!Type->isPromotableIntegerType()) 3754 return false; 3755 if (!Type->isEnumeralType()) 3756 return true; 3757 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3758 return !(ED && 3759 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3760 }()) { 3761 unsigned Reason = 0; 3762 if (Type->isReferenceType()) Reason = 1; 3763 else if (IsCRegister) Reason = 2; 3764 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3765 Diag(ParamLoc, diag::note_parameter_type) << Type; 3766 } 3767 3768 TheCall->setType(Context.VoidTy); 3769 return false; 3770 } 3771 3772 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3773 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3774 // const char *named_addr); 3775 3776 Expr *Func = Call->getCallee(); 3777 3778 if (Call->getNumArgs() < 3) 3779 return Diag(Call->getLocEnd(), 3780 diag::err_typecheck_call_too_few_args_at_least) 3781 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3782 3783 // Type-check the first argument normally. 3784 if (checkBuiltinArgument(*this, Call, 0)) 3785 return true; 3786 3787 // Check that the current function is variadic. 3788 if (checkVAStartIsInVariadicFunction(*this, Func)) 3789 return true; 3790 3791 const struct { 3792 unsigned ArgNo; 3793 QualType Type; 3794 } ArgumentTypes[] = { 3795 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3796 { 2, Context.getSizeType() }, 3797 }; 3798 3799 for (const auto &AT : ArgumentTypes) { 3800 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3801 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3802 continue; 3803 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3804 << Arg->getType() << AT.Type << 1 /* different class */ 3805 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3806 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3807 } 3808 3809 return false; 3810 } 3811 3812 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3813 /// friends. This is declared to take (...), so we have to check everything. 3814 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3815 if (TheCall->getNumArgs() < 2) 3816 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3817 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3818 if (TheCall->getNumArgs() > 2) 3819 return Diag(TheCall->getArg(2)->getLocStart(), 3820 diag::err_typecheck_call_too_many_args) 3821 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3822 << SourceRange(TheCall->getArg(2)->getLocStart(), 3823 (*(TheCall->arg_end()-1))->getLocEnd()); 3824 3825 ExprResult OrigArg0 = TheCall->getArg(0); 3826 ExprResult OrigArg1 = TheCall->getArg(1); 3827 3828 // Do standard promotions between the two arguments, returning their common 3829 // type. 3830 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3831 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3832 return true; 3833 3834 // Make sure any conversions are pushed back into the call; this is 3835 // type safe since unordered compare builtins are declared as "_Bool 3836 // foo(...)". 3837 TheCall->setArg(0, OrigArg0.get()); 3838 TheCall->setArg(1, OrigArg1.get()); 3839 3840 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3841 return false; 3842 3843 // If the common type isn't a real floating type, then the arguments were 3844 // invalid for this operation. 3845 if (Res.isNull() || !Res->isRealFloatingType()) 3846 return Diag(OrigArg0.get()->getLocStart(), 3847 diag::err_typecheck_call_invalid_ordered_compare) 3848 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3849 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3850 3851 return false; 3852 } 3853 3854 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3855 /// __builtin_isnan and friends. This is declared to take (...), so we have 3856 /// to check everything. We expect the last argument to be a floating point 3857 /// value. 3858 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3859 if (TheCall->getNumArgs() < NumArgs) 3860 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3861 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3862 if (TheCall->getNumArgs() > NumArgs) 3863 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3864 diag::err_typecheck_call_too_many_args) 3865 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3866 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3867 (*(TheCall->arg_end()-1))->getLocEnd()); 3868 3869 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3870 3871 if (OrigArg->isTypeDependent()) 3872 return false; 3873 3874 // This operation requires a non-_Complex floating-point number. 3875 if (!OrigArg->getType()->isRealFloatingType()) 3876 return Diag(OrigArg->getLocStart(), 3877 diag::err_typecheck_call_invalid_unary_fp) 3878 << OrigArg->getType() << OrigArg->getSourceRange(); 3879 3880 // If this is an implicit conversion from float -> float or double, remove it. 3881 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 3882 // Only remove standard FloatCasts, leaving other casts inplace 3883 if (Cast->getCastKind() == CK_FloatingCast) { 3884 Expr *CastArg = Cast->getSubExpr(); 3885 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 3886 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 3887 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 3888 "promotion from float to either float or double is the only expected cast here"); 3889 Cast->setSubExpr(nullptr); 3890 TheCall->setArg(NumArgs-1, CastArg); 3891 } 3892 } 3893 } 3894 3895 return false; 3896 } 3897 3898 // Customized Sema Checking for VSX builtins that have the following signature: 3899 // vector [...] builtinName(vector [...], vector [...], const int); 3900 // Which takes the same type of vectors (any legal vector type) for the first 3901 // two arguments and takes compile time constant for the third argument. 3902 // Example builtins are : 3903 // vector double vec_xxpermdi(vector double, vector double, int); 3904 // vector short vec_xxsldwi(vector short, vector short, int); 3905 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 3906 unsigned ExpectedNumArgs = 3; 3907 if (TheCall->getNumArgs() < ExpectedNumArgs) 3908 return Diag(TheCall->getLocEnd(), 3909 diag::err_typecheck_call_too_few_args_at_least) 3910 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 3911 << TheCall->getSourceRange(); 3912 3913 if (TheCall->getNumArgs() > ExpectedNumArgs) 3914 return Diag(TheCall->getLocEnd(), 3915 diag::err_typecheck_call_too_many_args_at_most) 3916 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 3917 << TheCall->getSourceRange(); 3918 3919 // Check the third argument is a compile time constant 3920 llvm::APSInt Value; 3921 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 3922 return Diag(TheCall->getLocStart(), 3923 diag::err_vsx_builtin_nonconstant_argument) 3924 << 3 /* argument index */ << TheCall->getDirectCallee() 3925 << SourceRange(TheCall->getArg(2)->getLocStart(), 3926 TheCall->getArg(2)->getLocEnd()); 3927 3928 QualType Arg1Ty = TheCall->getArg(0)->getType(); 3929 QualType Arg2Ty = TheCall->getArg(1)->getType(); 3930 3931 // Check the type of argument 1 and argument 2 are vectors. 3932 SourceLocation BuiltinLoc = TheCall->getLocStart(); 3933 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 3934 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 3935 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 3936 << TheCall->getDirectCallee() 3937 << SourceRange(TheCall->getArg(0)->getLocStart(), 3938 TheCall->getArg(1)->getLocEnd()); 3939 } 3940 3941 // Check the first two arguments are the same type. 3942 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 3943 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 3944 << TheCall->getDirectCallee() 3945 << SourceRange(TheCall->getArg(0)->getLocStart(), 3946 TheCall->getArg(1)->getLocEnd()); 3947 } 3948 3949 // When default clang type checking is turned off and the customized type 3950 // checking is used, the returning type of the function must be explicitly 3951 // set. Otherwise it is _Bool by default. 3952 TheCall->setType(Arg1Ty); 3953 3954 return false; 3955 } 3956 3957 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 3958 // This is declared to take (...), so we have to check everything. 3959 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 3960 if (TheCall->getNumArgs() < 2) 3961 return ExprError(Diag(TheCall->getLocEnd(), 3962 diag::err_typecheck_call_too_few_args_at_least) 3963 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3964 << TheCall->getSourceRange()); 3965 3966 // Determine which of the following types of shufflevector we're checking: 3967 // 1) unary, vector mask: (lhs, mask) 3968 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 3969 QualType resType = TheCall->getArg(0)->getType(); 3970 unsigned numElements = 0; 3971 3972 if (!TheCall->getArg(0)->isTypeDependent() && 3973 !TheCall->getArg(1)->isTypeDependent()) { 3974 QualType LHSType = TheCall->getArg(0)->getType(); 3975 QualType RHSType = TheCall->getArg(1)->getType(); 3976 3977 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 3978 return ExprError(Diag(TheCall->getLocStart(), 3979 diag::err_vec_builtin_non_vector) 3980 << TheCall->getDirectCallee() 3981 << SourceRange(TheCall->getArg(0)->getLocStart(), 3982 TheCall->getArg(1)->getLocEnd())); 3983 3984 numElements = LHSType->getAs<VectorType>()->getNumElements(); 3985 unsigned numResElements = TheCall->getNumArgs() - 2; 3986 3987 // Check to see if we have a call with 2 vector arguments, the unary shuffle 3988 // with mask. If so, verify that RHS is an integer vector type with the 3989 // same number of elts as lhs. 3990 if (TheCall->getNumArgs() == 2) { 3991 if (!RHSType->hasIntegerRepresentation() || 3992 RHSType->getAs<VectorType>()->getNumElements() != numElements) 3993 return ExprError(Diag(TheCall->getLocStart(), 3994 diag::err_vec_builtin_incompatible_vector) 3995 << TheCall->getDirectCallee() 3996 << SourceRange(TheCall->getArg(1)->getLocStart(), 3997 TheCall->getArg(1)->getLocEnd())); 3998 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 3999 return ExprError(Diag(TheCall->getLocStart(), 4000 diag::err_vec_builtin_incompatible_vector) 4001 << TheCall->getDirectCallee() 4002 << SourceRange(TheCall->getArg(0)->getLocStart(), 4003 TheCall->getArg(1)->getLocEnd())); 4004 } else if (numElements != numResElements) { 4005 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4006 resType = Context.getVectorType(eltType, numResElements, 4007 VectorType::GenericVector); 4008 } 4009 } 4010 4011 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4012 if (TheCall->getArg(i)->isTypeDependent() || 4013 TheCall->getArg(i)->isValueDependent()) 4014 continue; 4015 4016 llvm::APSInt Result(32); 4017 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4018 return ExprError(Diag(TheCall->getLocStart(), 4019 diag::err_shufflevector_nonconstant_argument) 4020 << TheCall->getArg(i)->getSourceRange()); 4021 4022 // Allow -1 which will be translated to undef in the IR. 4023 if (Result.isSigned() && Result.isAllOnesValue()) 4024 continue; 4025 4026 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4027 return ExprError(Diag(TheCall->getLocStart(), 4028 diag::err_shufflevector_argument_too_large) 4029 << TheCall->getArg(i)->getSourceRange()); 4030 } 4031 4032 SmallVector<Expr*, 32> exprs; 4033 4034 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4035 exprs.push_back(TheCall->getArg(i)); 4036 TheCall->setArg(i, nullptr); 4037 } 4038 4039 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4040 TheCall->getCallee()->getLocStart(), 4041 TheCall->getRParenLoc()); 4042 } 4043 4044 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4045 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4046 SourceLocation BuiltinLoc, 4047 SourceLocation RParenLoc) { 4048 ExprValueKind VK = VK_RValue; 4049 ExprObjectKind OK = OK_Ordinary; 4050 QualType DstTy = TInfo->getType(); 4051 QualType SrcTy = E->getType(); 4052 4053 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4054 return ExprError(Diag(BuiltinLoc, 4055 diag::err_convertvector_non_vector) 4056 << E->getSourceRange()); 4057 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4058 return ExprError(Diag(BuiltinLoc, 4059 diag::err_convertvector_non_vector_type)); 4060 4061 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4062 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4063 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4064 if (SrcElts != DstElts) 4065 return ExprError(Diag(BuiltinLoc, 4066 diag::err_convertvector_incompatible_vector) 4067 << E->getSourceRange()); 4068 } 4069 4070 return new (Context) 4071 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4072 } 4073 4074 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4075 // This is declared to take (const void*, ...) and can take two 4076 // optional constant int args. 4077 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4078 unsigned NumArgs = TheCall->getNumArgs(); 4079 4080 if (NumArgs > 3) 4081 return Diag(TheCall->getLocEnd(), 4082 diag::err_typecheck_call_too_many_args_at_most) 4083 << 0 /*function call*/ << 3 << NumArgs 4084 << TheCall->getSourceRange(); 4085 4086 // Argument 0 is checked for us and the remaining arguments must be 4087 // constant integers. 4088 for (unsigned i = 1; i != NumArgs; ++i) 4089 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4090 return true; 4091 4092 return false; 4093 } 4094 4095 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4096 // __assume does not evaluate its arguments, and should warn if its argument 4097 // has side effects. 4098 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4099 Expr *Arg = TheCall->getArg(0); 4100 if (Arg->isInstantiationDependent()) return false; 4101 4102 if (Arg->HasSideEffects(Context)) 4103 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4104 << Arg->getSourceRange() 4105 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4106 4107 return false; 4108 } 4109 4110 /// Handle __builtin_alloca_with_align. This is declared 4111 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4112 /// than 8. 4113 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4114 // The alignment must be a constant integer. 4115 Expr *Arg = TheCall->getArg(1); 4116 4117 // We can't check the value of a dependent argument. 4118 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4119 if (const auto *UE = 4120 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4121 if (UE->getKind() == UETT_AlignOf) 4122 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4123 << Arg->getSourceRange(); 4124 4125 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4126 4127 if (!Result.isPowerOf2()) 4128 return Diag(TheCall->getLocStart(), 4129 diag::err_alignment_not_power_of_two) 4130 << Arg->getSourceRange(); 4131 4132 if (Result < Context.getCharWidth()) 4133 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4134 << (unsigned)Context.getCharWidth() 4135 << Arg->getSourceRange(); 4136 4137 if (Result > INT32_MAX) 4138 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4139 << INT32_MAX 4140 << Arg->getSourceRange(); 4141 } 4142 4143 return false; 4144 } 4145 4146 /// Handle __builtin_assume_aligned. This is declared 4147 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4148 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4149 unsigned NumArgs = TheCall->getNumArgs(); 4150 4151 if (NumArgs > 3) 4152 return Diag(TheCall->getLocEnd(), 4153 diag::err_typecheck_call_too_many_args_at_most) 4154 << 0 /*function call*/ << 3 << NumArgs 4155 << TheCall->getSourceRange(); 4156 4157 // The alignment must be a constant integer. 4158 Expr *Arg = TheCall->getArg(1); 4159 4160 // We can't check the value of a dependent argument. 4161 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4162 llvm::APSInt Result; 4163 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4164 return true; 4165 4166 if (!Result.isPowerOf2()) 4167 return Diag(TheCall->getLocStart(), 4168 diag::err_alignment_not_power_of_two) 4169 << Arg->getSourceRange(); 4170 } 4171 4172 if (NumArgs > 2) { 4173 ExprResult Arg(TheCall->getArg(2)); 4174 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4175 Context.getSizeType(), false); 4176 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4177 if (Arg.isInvalid()) return true; 4178 TheCall->setArg(2, Arg.get()); 4179 } 4180 4181 return false; 4182 } 4183 4184 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4185 unsigned BuiltinID = 4186 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4187 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4188 4189 unsigned NumArgs = TheCall->getNumArgs(); 4190 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4191 if (NumArgs < NumRequiredArgs) { 4192 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4193 << 0 /* function call */ << NumRequiredArgs << NumArgs 4194 << TheCall->getSourceRange(); 4195 } 4196 if (NumArgs >= NumRequiredArgs + 0x100) { 4197 return Diag(TheCall->getLocEnd(), 4198 diag::err_typecheck_call_too_many_args_at_most) 4199 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4200 << TheCall->getSourceRange(); 4201 } 4202 unsigned i = 0; 4203 4204 // For formatting call, check buffer arg. 4205 if (!IsSizeCall) { 4206 ExprResult Arg(TheCall->getArg(i)); 4207 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4208 Context, Context.VoidPtrTy, false); 4209 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4210 if (Arg.isInvalid()) 4211 return true; 4212 TheCall->setArg(i, Arg.get()); 4213 i++; 4214 } 4215 4216 // Check string literal arg. 4217 unsigned FormatIdx = i; 4218 { 4219 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4220 if (Arg.isInvalid()) 4221 return true; 4222 TheCall->setArg(i, Arg.get()); 4223 i++; 4224 } 4225 4226 // Make sure variadic args are scalar. 4227 unsigned FirstDataArg = i; 4228 while (i < NumArgs) { 4229 ExprResult Arg = DefaultVariadicArgumentPromotion( 4230 TheCall->getArg(i), VariadicFunction, nullptr); 4231 if (Arg.isInvalid()) 4232 return true; 4233 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4234 if (ArgSize.getQuantity() >= 0x100) { 4235 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4236 << i << (int)ArgSize.getQuantity() << 0xff 4237 << TheCall->getSourceRange(); 4238 } 4239 TheCall->setArg(i, Arg.get()); 4240 i++; 4241 } 4242 4243 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4244 // call to avoid duplicate diagnostics. 4245 if (!IsSizeCall) { 4246 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4247 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4248 bool Success = CheckFormatArguments( 4249 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4250 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4251 CheckedVarArgs); 4252 if (!Success) 4253 return true; 4254 } 4255 4256 if (IsSizeCall) { 4257 TheCall->setType(Context.getSizeType()); 4258 } else { 4259 TheCall->setType(Context.VoidPtrTy); 4260 } 4261 return false; 4262 } 4263 4264 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4265 /// TheCall is a constant expression. 4266 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4267 llvm::APSInt &Result) { 4268 Expr *Arg = TheCall->getArg(ArgNum); 4269 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4270 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4271 4272 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4273 4274 if (!Arg->isIntegerConstantExpr(Result, Context)) 4275 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4276 << FDecl->getDeclName() << Arg->getSourceRange(); 4277 4278 return false; 4279 } 4280 4281 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4282 /// TheCall is a constant expression in the range [Low, High]. 4283 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4284 int Low, int High) { 4285 llvm::APSInt Result; 4286 4287 // We can't check the value of a dependent argument. 4288 Expr *Arg = TheCall->getArg(ArgNum); 4289 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4290 return false; 4291 4292 // Check constant-ness first. 4293 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4294 return true; 4295 4296 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4297 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4298 << Low << High << Arg->getSourceRange(); 4299 4300 return false; 4301 } 4302 4303 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4304 /// TheCall is a constant expression is a multiple of Num.. 4305 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4306 unsigned Num) { 4307 llvm::APSInt Result; 4308 4309 // We can't check the value of a dependent argument. 4310 Expr *Arg = TheCall->getArg(ArgNum); 4311 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4312 return false; 4313 4314 // Check constant-ness first. 4315 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4316 return true; 4317 4318 if (Result.getSExtValue() % Num != 0) 4319 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4320 << Num << Arg->getSourceRange(); 4321 4322 return false; 4323 } 4324 4325 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4326 /// TheCall is an ARM/AArch64 special register string literal. 4327 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4328 int ArgNum, unsigned ExpectedFieldNum, 4329 bool AllowName) { 4330 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4331 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4332 BuiltinID == ARM::BI__builtin_arm_rsr || 4333 BuiltinID == ARM::BI__builtin_arm_rsrp || 4334 BuiltinID == ARM::BI__builtin_arm_wsr || 4335 BuiltinID == ARM::BI__builtin_arm_wsrp; 4336 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4337 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4338 BuiltinID == AArch64::BI__builtin_arm_rsr || 4339 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4340 BuiltinID == AArch64::BI__builtin_arm_wsr || 4341 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4342 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4343 4344 // We can't check the value of a dependent argument. 4345 Expr *Arg = TheCall->getArg(ArgNum); 4346 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4347 return false; 4348 4349 // Check if the argument is a string literal. 4350 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4351 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4352 << Arg->getSourceRange(); 4353 4354 // Check the type of special register given. 4355 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4356 SmallVector<StringRef, 6> Fields; 4357 Reg.split(Fields, ":"); 4358 4359 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4360 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4361 << Arg->getSourceRange(); 4362 4363 // If the string is the name of a register then we cannot check that it is 4364 // valid here but if the string is of one the forms described in ACLE then we 4365 // can check that the supplied fields are integers and within the valid 4366 // ranges. 4367 if (Fields.size() > 1) { 4368 bool FiveFields = Fields.size() == 5; 4369 4370 bool ValidString = true; 4371 if (IsARMBuiltin) { 4372 ValidString &= Fields[0].startswith_lower("cp") || 4373 Fields[0].startswith_lower("p"); 4374 if (ValidString) 4375 Fields[0] = 4376 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4377 4378 ValidString &= Fields[2].startswith_lower("c"); 4379 if (ValidString) 4380 Fields[2] = Fields[2].drop_front(1); 4381 4382 if (FiveFields) { 4383 ValidString &= Fields[3].startswith_lower("c"); 4384 if (ValidString) 4385 Fields[3] = Fields[3].drop_front(1); 4386 } 4387 } 4388 4389 SmallVector<int, 5> Ranges; 4390 if (FiveFields) 4391 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4392 else 4393 Ranges.append({15, 7, 15}); 4394 4395 for (unsigned i=0; i<Fields.size(); ++i) { 4396 int IntField; 4397 ValidString &= !Fields[i].getAsInteger(10, IntField); 4398 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4399 } 4400 4401 if (!ValidString) 4402 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4403 << Arg->getSourceRange(); 4404 4405 } else if (IsAArch64Builtin && Fields.size() == 1) { 4406 // If the register name is one of those that appear in the condition below 4407 // and the special register builtin being used is one of the write builtins, 4408 // then we require that the argument provided for writing to the register 4409 // is an integer constant expression. This is because it will be lowered to 4410 // an MSR (immediate) instruction, so we need to know the immediate at 4411 // compile time. 4412 if (TheCall->getNumArgs() != 2) 4413 return false; 4414 4415 std::string RegLower = Reg.lower(); 4416 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4417 RegLower != "pan" && RegLower != "uao") 4418 return false; 4419 4420 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4421 } 4422 4423 return false; 4424 } 4425 4426 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4427 /// This checks that the target supports __builtin_longjmp and 4428 /// that val is a constant 1. 4429 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4430 if (!Context.getTargetInfo().hasSjLjLowering()) 4431 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4432 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4433 4434 Expr *Arg = TheCall->getArg(1); 4435 llvm::APSInt Result; 4436 4437 // TODO: This is less than ideal. Overload this to take a value. 4438 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4439 return true; 4440 4441 if (Result != 1) 4442 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4443 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4444 4445 return false; 4446 } 4447 4448 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4449 /// This checks that the target supports __builtin_setjmp. 4450 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4451 if (!Context.getTargetInfo().hasSjLjLowering()) 4452 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4453 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4454 return false; 4455 } 4456 4457 namespace { 4458 class UncoveredArgHandler { 4459 enum { Unknown = -1, AllCovered = -2 }; 4460 signed FirstUncoveredArg; 4461 SmallVector<const Expr *, 4> DiagnosticExprs; 4462 4463 public: 4464 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4465 4466 bool hasUncoveredArg() const { 4467 return (FirstUncoveredArg >= 0); 4468 } 4469 4470 unsigned getUncoveredArg() const { 4471 assert(hasUncoveredArg() && "no uncovered argument"); 4472 return FirstUncoveredArg; 4473 } 4474 4475 void setAllCovered() { 4476 // A string has been found with all arguments covered, so clear out 4477 // the diagnostics. 4478 DiagnosticExprs.clear(); 4479 FirstUncoveredArg = AllCovered; 4480 } 4481 4482 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4483 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4484 4485 // Don't update if a previous string covers all arguments. 4486 if (FirstUncoveredArg == AllCovered) 4487 return; 4488 4489 // UncoveredArgHandler tracks the highest uncovered argument index 4490 // and with it all the strings that match this index. 4491 if (NewFirstUncoveredArg == FirstUncoveredArg) 4492 DiagnosticExprs.push_back(StrExpr); 4493 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4494 DiagnosticExprs.clear(); 4495 DiagnosticExprs.push_back(StrExpr); 4496 FirstUncoveredArg = NewFirstUncoveredArg; 4497 } 4498 } 4499 4500 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4501 }; 4502 4503 enum StringLiteralCheckType { 4504 SLCT_NotALiteral, 4505 SLCT_UncheckedLiteral, 4506 SLCT_CheckedLiteral 4507 }; 4508 } // end anonymous namespace 4509 4510 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4511 BinaryOperatorKind BinOpKind, 4512 bool AddendIsRight) { 4513 unsigned BitWidth = Offset.getBitWidth(); 4514 unsigned AddendBitWidth = Addend.getBitWidth(); 4515 // There might be negative interim results. 4516 if (Addend.isUnsigned()) { 4517 Addend = Addend.zext(++AddendBitWidth); 4518 Addend.setIsSigned(true); 4519 } 4520 // Adjust the bit width of the APSInts. 4521 if (AddendBitWidth > BitWidth) { 4522 Offset = Offset.sext(AddendBitWidth); 4523 BitWidth = AddendBitWidth; 4524 } else if (BitWidth > AddendBitWidth) { 4525 Addend = Addend.sext(BitWidth); 4526 } 4527 4528 bool Ov = false; 4529 llvm::APSInt ResOffset = Offset; 4530 if (BinOpKind == BO_Add) 4531 ResOffset = Offset.sadd_ov(Addend, Ov); 4532 else { 4533 assert(AddendIsRight && BinOpKind == BO_Sub && 4534 "operator must be add or sub with addend on the right"); 4535 ResOffset = Offset.ssub_ov(Addend, Ov); 4536 } 4537 4538 // We add an offset to a pointer here so we should support an offset as big as 4539 // possible. 4540 if (Ov) { 4541 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4542 Offset = Offset.sext(2 * BitWidth); 4543 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4544 return; 4545 } 4546 4547 Offset = ResOffset; 4548 } 4549 4550 namespace { 4551 // This is a wrapper class around StringLiteral to support offsetted string 4552 // literals as format strings. It takes the offset into account when returning 4553 // the string and its length or the source locations to display notes correctly. 4554 class FormatStringLiteral { 4555 const StringLiteral *FExpr; 4556 int64_t Offset; 4557 4558 public: 4559 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4560 : FExpr(fexpr), Offset(Offset) {} 4561 4562 StringRef getString() const { 4563 return FExpr->getString().drop_front(Offset); 4564 } 4565 4566 unsigned getByteLength() const { 4567 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4568 } 4569 unsigned getLength() const { return FExpr->getLength() - Offset; } 4570 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4571 4572 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4573 4574 QualType getType() const { return FExpr->getType(); } 4575 4576 bool isAscii() const { return FExpr->isAscii(); } 4577 bool isWide() const { return FExpr->isWide(); } 4578 bool isUTF8() const { return FExpr->isUTF8(); } 4579 bool isUTF16() const { return FExpr->isUTF16(); } 4580 bool isUTF32() const { return FExpr->isUTF32(); } 4581 bool isPascal() const { return FExpr->isPascal(); } 4582 4583 SourceLocation getLocationOfByte( 4584 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4585 const TargetInfo &Target, unsigned *StartToken = nullptr, 4586 unsigned *StartTokenByteOffset = nullptr) const { 4587 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4588 StartToken, StartTokenByteOffset); 4589 } 4590 4591 SourceLocation getLocStart() const LLVM_READONLY { 4592 return FExpr->getLocStart().getLocWithOffset(Offset); 4593 } 4594 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4595 }; 4596 } // end anonymous namespace 4597 4598 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4599 const Expr *OrigFormatExpr, 4600 ArrayRef<const Expr *> Args, 4601 bool HasVAListArg, unsigned format_idx, 4602 unsigned firstDataArg, 4603 Sema::FormatStringType Type, 4604 bool inFunctionCall, 4605 Sema::VariadicCallType CallType, 4606 llvm::SmallBitVector &CheckedVarArgs, 4607 UncoveredArgHandler &UncoveredArg); 4608 4609 // Determine if an expression is a string literal or constant string. 4610 // If this function returns false on the arguments to a function expecting a 4611 // format string, we will usually need to emit a warning. 4612 // True string literals are then checked by CheckFormatString. 4613 static StringLiteralCheckType 4614 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4615 bool HasVAListArg, unsigned format_idx, 4616 unsigned firstDataArg, Sema::FormatStringType Type, 4617 Sema::VariadicCallType CallType, bool InFunctionCall, 4618 llvm::SmallBitVector &CheckedVarArgs, 4619 UncoveredArgHandler &UncoveredArg, 4620 llvm::APSInt Offset) { 4621 tryAgain: 4622 assert(Offset.isSigned() && "invalid offset"); 4623 4624 if (E->isTypeDependent() || E->isValueDependent()) 4625 return SLCT_NotALiteral; 4626 4627 E = E->IgnoreParenCasts(); 4628 4629 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4630 // Technically -Wformat-nonliteral does not warn about this case. 4631 // The behavior of printf and friends in this case is implementation 4632 // dependent. Ideally if the format string cannot be null then 4633 // it should have a 'nonnull' attribute in the function prototype. 4634 return SLCT_UncheckedLiteral; 4635 4636 switch (E->getStmtClass()) { 4637 case Stmt::BinaryConditionalOperatorClass: 4638 case Stmt::ConditionalOperatorClass: { 4639 // The expression is a literal if both sub-expressions were, and it was 4640 // completely checked only if both sub-expressions were checked. 4641 const AbstractConditionalOperator *C = 4642 cast<AbstractConditionalOperator>(E); 4643 4644 // Determine whether it is necessary to check both sub-expressions, for 4645 // example, because the condition expression is a constant that can be 4646 // evaluated at compile time. 4647 bool CheckLeft = true, CheckRight = true; 4648 4649 bool Cond; 4650 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4651 if (Cond) 4652 CheckRight = false; 4653 else 4654 CheckLeft = false; 4655 } 4656 4657 // We need to maintain the offsets for the right and the left hand side 4658 // separately to check if every possible indexed expression is a valid 4659 // string literal. They might have different offsets for different string 4660 // literals in the end. 4661 StringLiteralCheckType Left; 4662 if (!CheckLeft) 4663 Left = SLCT_UncheckedLiteral; 4664 else { 4665 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4666 HasVAListArg, format_idx, firstDataArg, 4667 Type, CallType, InFunctionCall, 4668 CheckedVarArgs, UncoveredArg, Offset); 4669 if (Left == SLCT_NotALiteral || !CheckRight) { 4670 return Left; 4671 } 4672 } 4673 4674 StringLiteralCheckType Right = 4675 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4676 HasVAListArg, format_idx, firstDataArg, 4677 Type, CallType, InFunctionCall, CheckedVarArgs, 4678 UncoveredArg, Offset); 4679 4680 return (CheckLeft && Left < Right) ? Left : Right; 4681 } 4682 4683 case Stmt::ImplicitCastExprClass: { 4684 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4685 goto tryAgain; 4686 } 4687 4688 case Stmt::OpaqueValueExprClass: 4689 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4690 E = src; 4691 goto tryAgain; 4692 } 4693 return SLCT_NotALiteral; 4694 4695 case Stmt::PredefinedExprClass: 4696 // While __func__, etc., are technically not string literals, they 4697 // cannot contain format specifiers and thus are not a security 4698 // liability. 4699 return SLCT_UncheckedLiteral; 4700 4701 case Stmt::DeclRefExprClass: { 4702 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4703 4704 // As an exception, do not flag errors for variables binding to 4705 // const string literals. 4706 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4707 bool isConstant = false; 4708 QualType T = DR->getType(); 4709 4710 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4711 isConstant = AT->getElementType().isConstant(S.Context); 4712 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4713 isConstant = T.isConstant(S.Context) && 4714 PT->getPointeeType().isConstant(S.Context); 4715 } else if (T->isObjCObjectPointerType()) { 4716 // In ObjC, there is usually no "const ObjectPointer" type, 4717 // so don't check if the pointee type is constant. 4718 isConstant = T.isConstant(S.Context); 4719 } 4720 4721 if (isConstant) { 4722 if (const Expr *Init = VD->getAnyInitializer()) { 4723 // Look through initializers like const char c[] = { "foo" } 4724 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4725 if (InitList->isStringLiteralInit()) 4726 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4727 } 4728 return checkFormatStringExpr(S, Init, Args, 4729 HasVAListArg, format_idx, 4730 firstDataArg, Type, CallType, 4731 /*InFunctionCall*/ false, CheckedVarArgs, 4732 UncoveredArg, Offset); 4733 } 4734 } 4735 4736 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4737 // special check to see if the format string is a function parameter 4738 // of the function calling the printf function. If the function 4739 // has an attribute indicating it is a printf-like function, then we 4740 // should suppress warnings concerning non-literals being used in a call 4741 // to a vprintf function. For example: 4742 // 4743 // void 4744 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4745 // va_list ap; 4746 // va_start(ap, fmt); 4747 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4748 // ... 4749 // } 4750 if (HasVAListArg) { 4751 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4752 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4753 int PVIndex = PV->getFunctionScopeIndex() + 1; 4754 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4755 // adjust for implicit parameter 4756 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4757 if (MD->isInstance()) 4758 ++PVIndex; 4759 // We also check if the formats are compatible. 4760 // We can't pass a 'scanf' string to a 'printf' function. 4761 if (PVIndex == PVFormat->getFormatIdx() && 4762 Type == S.GetFormatStringType(PVFormat)) 4763 return SLCT_UncheckedLiteral; 4764 } 4765 } 4766 } 4767 } 4768 } 4769 4770 return SLCT_NotALiteral; 4771 } 4772 4773 case Stmt::CallExprClass: 4774 case Stmt::CXXMemberCallExprClass: { 4775 const CallExpr *CE = cast<CallExpr>(E); 4776 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4777 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4778 unsigned ArgIndex = FA->getFormatIdx(); 4779 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4780 if (MD->isInstance()) 4781 --ArgIndex; 4782 const Expr *Arg = CE->getArg(ArgIndex - 1); 4783 4784 return checkFormatStringExpr(S, Arg, Args, 4785 HasVAListArg, format_idx, firstDataArg, 4786 Type, CallType, InFunctionCall, 4787 CheckedVarArgs, UncoveredArg, Offset); 4788 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4789 unsigned BuiltinID = FD->getBuiltinID(); 4790 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4791 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4792 const Expr *Arg = CE->getArg(0); 4793 return checkFormatStringExpr(S, Arg, Args, 4794 HasVAListArg, format_idx, 4795 firstDataArg, Type, CallType, 4796 InFunctionCall, CheckedVarArgs, 4797 UncoveredArg, Offset); 4798 } 4799 } 4800 } 4801 4802 return SLCT_NotALiteral; 4803 } 4804 case Stmt::ObjCMessageExprClass: { 4805 const auto *ME = cast<ObjCMessageExpr>(E); 4806 if (const auto *ND = ME->getMethodDecl()) { 4807 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4808 unsigned ArgIndex = FA->getFormatIdx(); 4809 const Expr *Arg = ME->getArg(ArgIndex - 1); 4810 return checkFormatStringExpr( 4811 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4812 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4813 } 4814 } 4815 4816 return SLCT_NotALiteral; 4817 } 4818 case Stmt::ObjCStringLiteralClass: 4819 case Stmt::StringLiteralClass: { 4820 const StringLiteral *StrE = nullptr; 4821 4822 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4823 StrE = ObjCFExpr->getString(); 4824 else 4825 StrE = cast<StringLiteral>(E); 4826 4827 if (StrE) { 4828 if (Offset.isNegative() || Offset > StrE->getLength()) { 4829 // TODO: It would be better to have an explicit warning for out of 4830 // bounds literals. 4831 return SLCT_NotALiteral; 4832 } 4833 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4834 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4835 firstDataArg, Type, InFunctionCall, CallType, 4836 CheckedVarArgs, UncoveredArg); 4837 return SLCT_CheckedLiteral; 4838 } 4839 4840 return SLCT_NotALiteral; 4841 } 4842 case Stmt::BinaryOperatorClass: { 4843 llvm::APSInt LResult; 4844 llvm::APSInt RResult; 4845 4846 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 4847 4848 // A string literal + an int offset is still a string literal. 4849 if (BinOp->isAdditiveOp()) { 4850 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 4851 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 4852 4853 if (LIsInt != RIsInt) { 4854 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 4855 4856 if (LIsInt) { 4857 if (BinOpKind == BO_Add) { 4858 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 4859 E = BinOp->getRHS(); 4860 goto tryAgain; 4861 } 4862 } else { 4863 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 4864 E = BinOp->getLHS(); 4865 goto tryAgain; 4866 } 4867 } 4868 } 4869 4870 return SLCT_NotALiteral; 4871 } 4872 case Stmt::UnaryOperatorClass: { 4873 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 4874 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 4875 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 4876 llvm::APSInt IndexResult; 4877 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 4878 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 4879 E = ASE->getBase(); 4880 goto tryAgain; 4881 } 4882 } 4883 4884 return SLCT_NotALiteral; 4885 } 4886 4887 default: 4888 return SLCT_NotALiteral; 4889 } 4890 } 4891 4892 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 4893 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 4894 .Case("scanf", FST_Scanf) 4895 .Cases("printf", "printf0", FST_Printf) 4896 .Cases("NSString", "CFString", FST_NSString) 4897 .Case("strftime", FST_Strftime) 4898 .Case("strfmon", FST_Strfmon) 4899 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 4900 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 4901 .Case("os_trace", FST_OSLog) 4902 .Case("os_log", FST_OSLog) 4903 .Default(FST_Unknown); 4904 } 4905 4906 /// CheckFormatArguments - Check calls to printf and scanf (and similar 4907 /// functions) for correct use of format strings. 4908 /// Returns true if a format string has been fully checked. 4909 bool Sema::CheckFormatArguments(const FormatAttr *Format, 4910 ArrayRef<const Expr *> Args, 4911 bool IsCXXMember, 4912 VariadicCallType CallType, 4913 SourceLocation Loc, SourceRange Range, 4914 llvm::SmallBitVector &CheckedVarArgs) { 4915 FormatStringInfo FSI; 4916 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 4917 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 4918 FSI.FirstDataArg, GetFormatStringType(Format), 4919 CallType, Loc, Range, CheckedVarArgs); 4920 return false; 4921 } 4922 4923 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 4924 bool HasVAListArg, unsigned format_idx, 4925 unsigned firstDataArg, FormatStringType Type, 4926 VariadicCallType CallType, 4927 SourceLocation Loc, SourceRange Range, 4928 llvm::SmallBitVector &CheckedVarArgs) { 4929 // CHECK: printf/scanf-like function is called with no format string. 4930 if (format_idx >= Args.size()) { 4931 Diag(Loc, diag::warn_missing_format_string) << Range; 4932 return false; 4933 } 4934 4935 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 4936 4937 // CHECK: format string is not a string literal. 4938 // 4939 // Dynamically generated format strings are difficult to 4940 // automatically vet at compile time. Requiring that format strings 4941 // are string literals: (1) permits the checking of format strings by 4942 // the compiler and thereby (2) can practically remove the source of 4943 // many format string exploits. 4944 4945 // Format string can be either ObjC string (e.g. @"%d") or 4946 // C string (e.g. "%d") 4947 // ObjC string uses the same format specifiers as C string, so we can use 4948 // the same format string checking logic for both ObjC and C strings. 4949 UncoveredArgHandler UncoveredArg; 4950 StringLiteralCheckType CT = 4951 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 4952 format_idx, firstDataArg, Type, CallType, 4953 /*IsFunctionCall*/ true, CheckedVarArgs, 4954 UncoveredArg, 4955 /*no string offset*/ llvm::APSInt(64, false) = 0); 4956 4957 // Generate a diagnostic where an uncovered argument is detected. 4958 if (UncoveredArg.hasUncoveredArg()) { 4959 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 4960 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 4961 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 4962 } 4963 4964 if (CT != SLCT_NotALiteral) 4965 // Literal format string found, check done! 4966 return CT == SLCT_CheckedLiteral; 4967 4968 // Strftime is particular as it always uses a single 'time' argument, 4969 // so it is safe to pass a non-literal string. 4970 if (Type == FST_Strftime) 4971 return false; 4972 4973 // Do not emit diag when the string param is a macro expansion and the 4974 // format is either NSString or CFString. This is a hack to prevent 4975 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 4976 // which are usually used in place of NS and CF string literals. 4977 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 4978 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 4979 return false; 4980 4981 // If there are no arguments specified, warn with -Wformat-security, otherwise 4982 // warn only with -Wformat-nonliteral. 4983 if (Args.size() == firstDataArg) { 4984 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 4985 << OrigFormatExpr->getSourceRange(); 4986 switch (Type) { 4987 default: 4988 break; 4989 case FST_Kprintf: 4990 case FST_FreeBSDKPrintf: 4991 case FST_Printf: 4992 Diag(FormatLoc, diag::note_format_security_fixit) 4993 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 4994 break; 4995 case FST_NSString: 4996 Diag(FormatLoc, diag::note_format_security_fixit) 4997 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 4998 break; 4999 } 5000 } else { 5001 Diag(FormatLoc, diag::warn_format_nonliteral) 5002 << OrigFormatExpr->getSourceRange(); 5003 } 5004 return false; 5005 } 5006 5007 namespace { 5008 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5009 protected: 5010 Sema &S; 5011 const FormatStringLiteral *FExpr; 5012 const Expr *OrigFormatExpr; 5013 const Sema::FormatStringType FSType; 5014 const unsigned FirstDataArg; 5015 const unsigned NumDataArgs; 5016 const char *Beg; // Start of format string. 5017 const bool HasVAListArg; 5018 ArrayRef<const Expr *> Args; 5019 unsigned FormatIdx; 5020 llvm::SmallBitVector CoveredArgs; 5021 bool usesPositionalArgs; 5022 bool atFirstArg; 5023 bool inFunctionCall; 5024 Sema::VariadicCallType CallType; 5025 llvm::SmallBitVector &CheckedVarArgs; 5026 UncoveredArgHandler &UncoveredArg; 5027 5028 public: 5029 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5030 const Expr *origFormatExpr, 5031 const Sema::FormatStringType type, unsigned firstDataArg, 5032 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5033 ArrayRef<const Expr *> Args, unsigned formatIdx, 5034 bool inFunctionCall, Sema::VariadicCallType callType, 5035 llvm::SmallBitVector &CheckedVarArgs, 5036 UncoveredArgHandler &UncoveredArg) 5037 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5038 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5039 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5040 usesPositionalArgs(false), atFirstArg(true), 5041 inFunctionCall(inFunctionCall), CallType(callType), 5042 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5043 CoveredArgs.resize(numDataArgs); 5044 CoveredArgs.reset(); 5045 } 5046 5047 void DoneProcessing(); 5048 5049 void HandleIncompleteSpecifier(const char *startSpecifier, 5050 unsigned specifierLen) override; 5051 5052 void HandleInvalidLengthModifier( 5053 const analyze_format_string::FormatSpecifier &FS, 5054 const analyze_format_string::ConversionSpecifier &CS, 5055 const char *startSpecifier, unsigned specifierLen, 5056 unsigned DiagID); 5057 5058 void HandleNonStandardLengthModifier( 5059 const analyze_format_string::FormatSpecifier &FS, 5060 const char *startSpecifier, unsigned specifierLen); 5061 5062 void HandleNonStandardConversionSpecifier( 5063 const analyze_format_string::ConversionSpecifier &CS, 5064 const char *startSpecifier, unsigned specifierLen); 5065 5066 void HandlePosition(const char *startPos, unsigned posLen) override; 5067 5068 void HandleInvalidPosition(const char *startSpecifier, 5069 unsigned specifierLen, 5070 analyze_format_string::PositionContext p) override; 5071 5072 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5073 5074 void HandleNullChar(const char *nullCharacter) override; 5075 5076 template <typename Range> 5077 static void 5078 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5079 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5080 bool IsStringLocation, Range StringRange, 5081 ArrayRef<FixItHint> Fixit = None); 5082 5083 protected: 5084 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5085 const char *startSpec, 5086 unsigned specifierLen, 5087 const char *csStart, unsigned csLen); 5088 5089 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5090 const char *startSpec, 5091 unsigned specifierLen); 5092 5093 SourceRange getFormatStringRange(); 5094 CharSourceRange getSpecifierRange(const char *startSpecifier, 5095 unsigned specifierLen); 5096 SourceLocation getLocationOfByte(const char *x); 5097 5098 const Expr *getDataArg(unsigned i) const; 5099 5100 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5101 const analyze_format_string::ConversionSpecifier &CS, 5102 const char *startSpecifier, unsigned specifierLen, 5103 unsigned argIndex); 5104 5105 template <typename Range> 5106 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5107 bool IsStringLocation, Range StringRange, 5108 ArrayRef<FixItHint> Fixit = None); 5109 }; 5110 } // end anonymous namespace 5111 5112 SourceRange CheckFormatHandler::getFormatStringRange() { 5113 return OrigFormatExpr->getSourceRange(); 5114 } 5115 5116 CharSourceRange CheckFormatHandler:: 5117 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5118 SourceLocation Start = getLocationOfByte(startSpecifier); 5119 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5120 5121 // Advance the end SourceLocation by one due to half-open ranges. 5122 End = End.getLocWithOffset(1); 5123 5124 return CharSourceRange::getCharRange(Start, End); 5125 } 5126 5127 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5128 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5129 S.getLangOpts(), S.Context.getTargetInfo()); 5130 } 5131 5132 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5133 unsigned specifierLen){ 5134 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5135 getLocationOfByte(startSpecifier), 5136 /*IsStringLocation*/true, 5137 getSpecifierRange(startSpecifier, specifierLen)); 5138 } 5139 5140 void CheckFormatHandler::HandleInvalidLengthModifier( 5141 const analyze_format_string::FormatSpecifier &FS, 5142 const analyze_format_string::ConversionSpecifier &CS, 5143 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5144 using namespace analyze_format_string; 5145 5146 const LengthModifier &LM = FS.getLengthModifier(); 5147 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5148 5149 // See if we know how to fix this length modifier. 5150 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5151 if (FixedLM) { 5152 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5153 getLocationOfByte(LM.getStart()), 5154 /*IsStringLocation*/true, 5155 getSpecifierRange(startSpecifier, specifierLen)); 5156 5157 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5158 << FixedLM->toString() 5159 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5160 5161 } else { 5162 FixItHint Hint; 5163 if (DiagID == diag::warn_format_nonsensical_length) 5164 Hint = FixItHint::CreateRemoval(LMRange); 5165 5166 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5167 getLocationOfByte(LM.getStart()), 5168 /*IsStringLocation*/true, 5169 getSpecifierRange(startSpecifier, specifierLen), 5170 Hint); 5171 } 5172 } 5173 5174 void CheckFormatHandler::HandleNonStandardLengthModifier( 5175 const analyze_format_string::FormatSpecifier &FS, 5176 const char *startSpecifier, unsigned specifierLen) { 5177 using namespace analyze_format_string; 5178 5179 const LengthModifier &LM = FS.getLengthModifier(); 5180 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5181 5182 // See if we know how to fix this length modifier. 5183 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5184 if (FixedLM) { 5185 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5186 << LM.toString() << 0, 5187 getLocationOfByte(LM.getStart()), 5188 /*IsStringLocation*/true, 5189 getSpecifierRange(startSpecifier, specifierLen)); 5190 5191 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5192 << FixedLM->toString() 5193 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5194 5195 } else { 5196 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5197 << LM.toString() << 0, 5198 getLocationOfByte(LM.getStart()), 5199 /*IsStringLocation*/true, 5200 getSpecifierRange(startSpecifier, specifierLen)); 5201 } 5202 } 5203 5204 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5205 const analyze_format_string::ConversionSpecifier &CS, 5206 const char *startSpecifier, unsigned specifierLen) { 5207 using namespace analyze_format_string; 5208 5209 // See if we know how to fix this conversion specifier. 5210 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5211 if (FixedCS) { 5212 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5213 << CS.toString() << /*conversion specifier*/1, 5214 getLocationOfByte(CS.getStart()), 5215 /*IsStringLocation*/true, 5216 getSpecifierRange(startSpecifier, specifierLen)); 5217 5218 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5219 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5220 << FixedCS->toString() 5221 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5222 } else { 5223 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5224 << CS.toString() << /*conversion specifier*/1, 5225 getLocationOfByte(CS.getStart()), 5226 /*IsStringLocation*/true, 5227 getSpecifierRange(startSpecifier, specifierLen)); 5228 } 5229 } 5230 5231 void CheckFormatHandler::HandlePosition(const char *startPos, 5232 unsigned posLen) { 5233 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5234 getLocationOfByte(startPos), 5235 /*IsStringLocation*/true, 5236 getSpecifierRange(startPos, posLen)); 5237 } 5238 5239 void 5240 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5241 analyze_format_string::PositionContext p) { 5242 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5243 << (unsigned) p, 5244 getLocationOfByte(startPos), /*IsStringLocation*/true, 5245 getSpecifierRange(startPos, posLen)); 5246 } 5247 5248 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5249 unsigned posLen) { 5250 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5251 getLocationOfByte(startPos), 5252 /*IsStringLocation*/true, 5253 getSpecifierRange(startPos, posLen)); 5254 } 5255 5256 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5257 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5258 // The presence of a null character is likely an error. 5259 EmitFormatDiagnostic( 5260 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5261 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5262 getFormatStringRange()); 5263 } 5264 } 5265 5266 // Note that this may return NULL if there was an error parsing or building 5267 // one of the argument expressions. 5268 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5269 return Args[FirstDataArg + i]; 5270 } 5271 5272 void CheckFormatHandler::DoneProcessing() { 5273 // Does the number of data arguments exceed the number of 5274 // format conversions in the format string? 5275 if (!HasVAListArg) { 5276 // Find any arguments that weren't covered. 5277 CoveredArgs.flip(); 5278 signed notCoveredArg = CoveredArgs.find_first(); 5279 if (notCoveredArg >= 0) { 5280 assert((unsigned)notCoveredArg < NumDataArgs); 5281 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5282 } else { 5283 UncoveredArg.setAllCovered(); 5284 } 5285 } 5286 } 5287 5288 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5289 const Expr *ArgExpr) { 5290 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5291 "Invalid state"); 5292 5293 if (!ArgExpr) 5294 return; 5295 5296 SourceLocation Loc = ArgExpr->getLocStart(); 5297 5298 if (S.getSourceManager().isInSystemMacro(Loc)) 5299 return; 5300 5301 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5302 for (auto E : DiagnosticExprs) 5303 PDiag << E->getSourceRange(); 5304 5305 CheckFormatHandler::EmitFormatDiagnostic( 5306 S, IsFunctionCall, DiagnosticExprs[0], 5307 PDiag, Loc, /*IsStringLocation*/false, 5308 DiagnosticExprs[0]->getSourceRange()); 5309 } 5310 5311 bool 5312 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5313 SourceLocation Loc, 5314 const char *startSpec, 5315 unsigned specifierLen, 5316 const char *csStart, 5317 unsigned csLen) { 5318 bool keepGoing = true; 5319 if (argIndex < NumDataArgs) { 5320 // Consider the argument coverered, even though the specifier doesn't 5321 // make sense. 5322 CoveredArgs.set(argIndex); 5323 } 5324 else { 5325 // If argIndex exceeds the number of data arguments we 5326 // don't issue a warning because that is just a cascade of warnings (and 5327 // they may have intended '%%' anyway). We don't want to continue processing 5328 // the format string after this point, however, as we will like just get 5329 // gibberish when trying to match arguments. 5330 keepGoing = false; 5331 } 5332 5333 StringRef Specifier(csStart, csLen); 5334 5335 // If the specifier in non-printable, it could be the first byte of a UTF-8 5336 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5337 // hex value. 5338 std::string CodePointStr; 5339 if (!llvm::sys::locale::isPrint(*csStart)) { 5340 llvm::UTF32 CodePoint; 5341 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5342 const llvm::UTF8 *E = 5343 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5344 llvm::ConversionResult Result = 5345 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5346 5347 if (Result != llvm::conversionOK) { 5348 unsigned char FirstChar = *csStart; 5349 CodePoint = (llvm::UTF32)FirstChar; 5350 } 5351 5352 llvm::raw_string_ostream OS(CodePointStr); 5353 if (CodePoint < 256) 5354 OS << "\\x" << llvm::format("%02x", CodePoint); 5355 else if (CodePoint <= 0xFFFF) 5356 OS << "\\u" << llvm::format("%04x", CodePoint); 5357 else 5358 OS << "\\U" << llvm::format("%08x", CodePoint); 5359 OS.flush(); 5360 Specifier = CodePointStr; 5361 } 5362 5363 EmitFormatDiagnostic( 5364 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5365 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5366 5367 return keepGoing; 5368 } 5369 5370 void 5371 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5372 const char *startSpec, 5373 unsigned specifierLen) { 5374 EmitFormatDiagnostic( 5375 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5376 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5377 } 5378 5379 bool 5380 CheckFormatHandler::CheckNumArgs( 5381 const analyze_format_string::FormatSpecifier &FS, 5382 const analyze_format_string::ConversionSpecifier &CS, 5383 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5384 5385 if (argIndex >= NumDataArgs) { 5386 PartialDiagnostic PDiag = FS.usesPositionalArg() 5387 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5388 << (argIndex+1) << NumDataArgs) 5389 : S.PDiag(diag::warn_printf_insufficient_data_args); 5390 EmitFormatDiagnostic( 5391 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5392 getSpecifierRange(startSpecifier, specifierLen)); 5393 5394 // Since more arguments than conversion tokens are given, by extension 5395 // all arguments are covered, so mark this as so. 5396 UncoveredArg.setAllCovered(); 5397 return false; 5398 } 5399 return true; 5400 } 5401 5402 template<typename Range> 5403 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5404 SourceLocation Loc, 5405 bool IsStringLocation, 5406 Range StringRange, 5407 ArrayRef<FixItHint> FixIt) { 5408 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5409 Loc, IsStringLocation, StringRange, FixIt); 5410 } 5411 5412 /// \brief If the format string is not within the funcion call, emit a note 5413 /// so that the function call and string are in diagnostic messages. 5414 /// 5415 /// \param InFunctionCall if true, the format string is within the function 5416 /// call and only one diagnostic message will be produced. Otherwise, an 5417 /// extra note will be emitted pointing to location of the format string. 5418 /// 5419 /// \param ArgumentExpr the expression that is passed as the format string 5420 /// argument in the function call. Used for getting locations when two 5421 /// diagnostics are emitted. 5422 /// 5423 /// \param PDiag the callee should already have provided any strings for the 5424 /// diagnostic message. This function only adds locations and fixits 5425 /// to diagnostics. 5426 /// 5427 /// \param Loc primary location for diagnostic. If two diagnostics are 5428 /// required, one will be at Loc and a new SourceLocation will be created for 5429 /// the other one. 5430 /// 5431 /// \param IsStringLocation if true, Loc points to the format string should be 5432 /// used for the note. Otherwise, Loc points to the argument list and will 5433 /// be used with PDiag. 5434 /// 5435 /// \param StringRange some or all of the string to highlight. This is 5436 /// templated so it can accept either a CharSourceRange or a SourceRange. 5437 /// 5438 /// \param FixIt optional fix it hint for the format string. 5439 template <typename Range> 5440 void CheckFormatHandler::EmitFormatDiagnostic( 5441 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5442 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5443 Range StringRange, ArrayRef<FixItHint> FixIt) { 5444 if (InFunctionCall) { 5445 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5446 D << StringRange; 5447 D << FixIt; 5448 } else { 5449 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5450 << ArgumentExpr->getSourceRange(); 5451 5452 const Sema::SemaDiagnosticBuilder &Note = 5453 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5454 diag::note_format_string_defined); 5455 5456 Note << StringRange; 5457 Note << FixIt; 5458 } 5459 } 5460 5461 //===--- CHECK: Printf format string checking ------------------------------===// 5462 5463 namespace { 5464 class CheckPrintfHandler : public CheckFormatHandler { 5465 public: 5466 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5467 const Expr *origFormatExpr, 5468 const Sema::FormatStringType type, unsigned firstDataArg, 5469 unsigned numDataArgs, bool isObjC, const char *beg, 5470 bool hasVAListArg, ArrayRef<const Expr *> Args, 5471 unsigned formatIdx, bool inFunctionCall, 5472 Sema::VariadicCallType CallType, 5473 llvm::SmallBitVector &CheckedVarArgs, 5474 UncoveredArgHandler &UncoveredArg) 5475 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5476 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5477 inFunctionCall, CallType, CheckedVarArgs, 5478 UncoveredArg) {} 5479 5480 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5481 5482 /// Returns true if '%@' specifiers are allowed in the format string. 5483 bool allowsObjCArg() const { 5484 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5485 FSType == Sema::FST_OSTrace; 5486 } 5487 5488 bool HandleInvalidPrintfConversionSpecifier( 5489 const analyze_printf::PrintfSpecifier &FS, 5490 const char *startSpecifier, 5491 unsigned specifierLen) override; 5492 5493 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5494 const char *startSpecifier, 5495 unsigned specifierLen) override; 5496 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5497 const char *StartSpecifier, 5498 unsigned SpecifierLen, 5499 const Expr *E); 5500 5501 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5502 const char *startSpecifier, unsigned specifierLen); 5503 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5504 const analyze_printf::OptionalAmount &Amt, 5505 unsigned type, 5506 const char *startSpecifier, unsigned specifierLen); 5507 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5508 const analyze_printf::OptionalFlag &flag, 5509 const char *startSpecifier, unsigned specifierLen); 5510 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5511 const analyze_printf::OptionalFlag &ignoredFlag, 5512 const analyze_printf::OptionalFlag &flag, 5513 const char *startSpecifier, unsigned specifierLen); 5514 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5515 const Expr *E); 5516 5517 void HandleEmptyObjCModifierFlag(const char *startFlag, 5518 unsigned flagLen) override; 5519 5520 void HandleInvalidObjCModifierFlag(const char *startFlag, 5521 unsigned flagLen) override; 5522 5523 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5524 const char *flagsEnd, 5525 const char *conversionPosition) 5526 override; 5527 }; 5528 } // end anonymous namespace 5529 5530 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5531 const analyze_printf::PrintfSpecifier &FS, 5532 const char *startSpecifier, 5533 unsigned specifierLen) { 5534 const analyze_printf::PrintfConversionSpecifier &CS = 5535 FS.getConversionSpecifier(); 5536 5537 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5538 getLocationOfByte(CS.getStart()), 5539 startSpecifier, specifierLen, 5540 CS.getStart(), CS.getLength()); 5541 } 5542 5543 bool CheckPrintfHandler::HandleAmount( 5544 const analyze_format_string::OptionalAmount &Amt, 5545 unsigned k, const char *startSpecifier, 5546 unsigned specifierLen) { 5547 if (Amt.hasDataArgument()) { 5548 if (!HasVAListArg) { 5549 unsigned argIndex = Amt.getArgIndex(); 5550 if (argIndex >= NumDataArgs) { 5551 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5552 << k, 5553 getLocationOfByte(Amt.getStart()), 5554 /*IsStringLocation*/true, 5555 getSpecifierRange(startSpecifier, specifierLen)); 5556 // Don't do any more checking. We will just emit 5557 // spurious errors. 5558 return false; 5559 } 5560 5561 // Type check the data argument. It should be an 'int'. 5562 // Although not in conformance with C99, we also allow the argument to be 5563 // an 'unsigned int' as that is a reasonably safe case. GCC also 5564 // doesn't emit a warning for that case. 5565 CoveredArgs.set(argIndex); 5566 const Expr *Arg = getDataArg(argIndex); 5567 if (!Arg) 5568 return false; 5569 5570 QualType T = Arg->getType(); 5571 5572 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5573 assert(AT.isValid()); 5574 5575 if (!AT.matchesType(S.Context, T)) { 5576 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5577 << k << AT.getRepresentativeTypeName(S.Context) 5578 << T << Arg->getSourceRange(), 5579 getLocationOfByte(Amt.getStart()), 5580 /*IsStringLocation*/true, 5581 getSpecifierRange(startSpecifier, specifierLen)); 5582 // Don't do any more checking. We will just emit 5583 // spurious errors. 5584 return false; 5585 } 5586 } 5587 } 5588 return true; 5589 } 5590 5591 void CheckPrintfHandler::HandleInvalidAmount( 5592 const analyze_printf::PrintfSpecifier &FS, 5593 const analyze_printf::OptionalAmount &Amt, 5594 unsigned type, 5595 const char *startSpecifier, 5596 unsigned specifierLen) { 5597 const analyze_printf::PrintfConversionSpecifier &CS = 5598 FS.getConversionSpecifier(); 5599 5600 FixItHint fixit = 5601 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5602 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5603 Amt.getConstantLength())) 5604 : FixItHint(); 5605 5606 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5607 << type << CS.toString(), 5608 getLocationOfByte(Amt.getStart()), 5609 /*IsStringLocation*/true, 5610 getSpecifierRange(startSpecifier, specifierLen), 5611 fixit); 5612 } 5613 5614 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5615 const analyze_printf::OptionalFlag &flag, 5616 const char *startSpecifier, 5617 unsigned specifierLen) { 5618 // Warn about pointless flag with a fixit removal. 5619 const analyze_printf::PrintfConversionSpecifier &CS = 5620 FS.getConversionSpecifier(); 5621 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5622 << flag.toString() << CS.toString(), 5623 getLocationOfByte(flag.getPosition()), 5624 /*IsStringLocation*/true, 5625 getSpecifierRange(startSpecifier, specifierLen), 5626 FixItHint::CreateRemoval( 5627 getSpecifierRange(flag.getPosition(), 1))); 5628 } 5629 5630 void CheckPrintfHandler::HandleIgnoredFlag( 5631 const analyze_printf::PrintfSpecifier &FS, 5632 const analyze_printf::OptionalFlag &ignoredFlag, 5633 const analyze_printf::OptionalFlag &flag, 5634 const char *startSpecifier, 5635 unsigned specifierLen) { 5636 // Warn about ignored flag with a fixit removal. 5637 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5638 << ignoredFlag.toString() << flag.toString(), 5639 getLocationOfByte(ignoredFlag.getPosition()), 5640 /*IsStringLocation*/true, 5641 getSpecifierRange(startSpecifier, specifierLen), 5642 FixItHint::CreateRemoval( 5643 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5644 } 5645 5646 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5647 // bool IsStringLocation, Range StringRange, 5648 // ArrayRef<FixItHint> Fixit = None); 5649 5650 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5651 unsigned flagLen) { 5652 // Warn about an empty flag. 5653 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5654 getLocationOfByte(startFlag), 5655 /*IsStringLocation*/true, 5656 getSpecifierRange(startFlag, flagLen)); 5657 } 5658 5659 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5660 unsigned flagLen) { 5661 // Warn about an invalid flag. 5662 auto Range = getSpecifierRange(startFlag, flagLen); 5663 StringRef flag(startFlag, flagLen); 5664 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5665 getLocationOfByte(startFlag), 5666 /*IsStringLocation*/true, 5667 Range, FixItHint::CreateRemoval(Range)); 5668 } 5669 5670 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5671 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5672 // Warn about using '[...]' without a '@' conversion. 5673 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5674 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5675 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5676 getLocationOfByte(conversionPosition), 5677 /*IsStringLocation*/true, 5678 Range, FixItHint::CreateRemoval(Range)); 5679 } 5680 5681 // Determines if the specified is a C++ class or struct containing 5682 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5683 // "c_str()"). 5684 template<typename MemberKind> 5685 static llvm::SmallPtrSet<MemberKind*, 1> 5686 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5687 const RecordType *RT = Ty->getAs<RecordType>(); 5688 llvm::SmallPtrSet<MemberKind*, 1> Results; 5689 5690 if (!RT) 5691 return Results; 5692 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5693 if (!RD || !RD->getDefinition()) 5694 return Results; 5695 5696 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5697 Sema::LookupMemberName); 5698 R.suppressDiagnostics(); 5699 5700 // We just need to include all members of the right kind turned up by the 5701 // filter, at this point. 5702 if (S.LookupQualifiedName(R, RT->getDecl())) 5703 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5704 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5705 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5706 Results.insert(FK); 5707 } 5708 return Results; 5709 } 5710 5711 /// Check if we could call '.c_str()' on an object. 5712 /// 5713 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5714 /// allow the call, or if it would be ambiguous). 5715 bool Sema::hasCStrMethod(const Expr *E) { 5716 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5717 MethodSet Results = 5718 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5719 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5720 MI != ME; ++MI) 5721 if ((*MI)->getMinRequiredArguments() == 0) 5722 return true; 5723 return false; 5724 } 5725 5726 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5727 // better diagnostic if so. AT is assumed to be valid. 5728 // Returns true when a c_str() conversion method is found. 5729 bool CheckPrintfHandler::checkForCStrMembers( 5730 const analyze_printf::ArgType &AT, const Expr *E) { 5731 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5732 5733 MethodSet Results = 5734 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5735 5736 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5737 MI != ME; ++MI) { 5738 const CXXMethodDecl *Method = *MI; 5739 if (Method->getMinRequiredArguments() == 0 && 5740 AT.matchesType(S.Context, Method->getReturnType())) { 5741 // FIXME: Suggest parens if the expression needs them. 5742 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5743 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5744 << "c_str()" 5745 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5746 return true; 5747 } 5748 } 5749 5750 return false; 5751 } 5752 5753 bool 5754 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5755 &FS, 5756 const char *startSpecifier, 5757 unsigned specifierLen) { 5758 using namespace analyze_format_string; 5759 using namespace analyze_printf; 5760 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5761 5762 if (FS.consumesDataArgument()) { 5763 if (atFirstArg) { 5764 atFirstArg = false; 5765 usesPositionalArgs = FS.usesPositionalArg(); 5766 } 5767 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5768 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5769 startSpecifier, specifierLen); 5770 return false; 5771 } 5772 } 5773 5774 // First check if the field width, precision, and conversion specifier 5775 // have matching data arguments. 5776 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5777 startSpecifier, specifierLen)) { 5778 return false; 5779 } 5780 5781 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5782 startSpecifier, specifierLen)) { 5783 return false; 5784 } 5785 5786 if (!CS.consumesDataArgument()) { 5787 // FIXME: Technically specifying a precision or field width here 5788 // makes no sense. Worth issuing a warning at some point. 5789 return true; 5790 } 5791 5792 // Consume the argument. 5793 unsigned argIndex = FS.getArgIndex(); 5794 if (argIndex < NumDataArgs) { 5795 // The check to see if the argIndex is valid will come later. 5796 // We set the bit here because we may exit early from this 5797 // function if we encounter some other error. 5798 CoveredArgs.set(argIndex); 5799 } 5800 5801 // FreeBSD kernel extensions. 5802 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5803 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5804 // We need at least two arguments. 5805 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5806 return false; 5807 5808 // Claim the second argument. 5809 CoveredArgs.set(argIndex + 1); 5810 5811 // Type check the first argument (int for %b, pointer for %D) 5812 const Expr *Ex = getDataArg(argIndex); 5813 const analyze_printf::ArgType &AT = 5814 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5815 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5816 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5817 EmitFormatDiagnostic( 5818 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5819 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5820 << false << Ex->getSourceRange(), 5821 Ex->getLocStart(), /*IsStringLocation*/false, 5822 getSpecifierRange(startSpecifier, specifierLen)); 5823 5824 // Type check the second argument (char * for both %b and %D) 5825 Ex = getDataArg(argIndex + 1); 5826 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5827 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5828 EmitFormatDiagnostic( 5829 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5830 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5831 << false << Ex->getSourceRange(), 5832 Ex->getLocStart(), /*IsStringLocation*/false, 5833 getSpecifierRange(startSpecifier, specifierLen)); 5834 5835 return true; 5836 } 5837 5838 // Check for using an Objective-C specific conversion specifier 5839 // in a non-ObjC literal. 5840 if (!allowsObjCArg() && CS.isObjCArg()) { 5841 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5842 specifierLen); 5843 } 5844 5845 // %P can only be used with os_log. 5846 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 5847 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5848 specifierLen); 5849 } 5850 5851 // %n is not allowed with os_log. 5852 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 5853 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 5854 getLocationOfByte(CS.getStart()), 5855 /*IsStringLocation*/ false, 5856 getSpecifierRange(startSpecifier, specifierLen)); 5857 5858 return true; 5859 } 5860 5861 // Only scalars are allowed for os_trace. 5862 if (FSType == Sema::FST_OSTrace && 5863 (CS.getKind() == ConversionSpecifier::PArg || 5864 CS.getKind() == ConversionSpecifier::sArg || 5865 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 5866 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5867 specifierLen); 5868 } 5869 5870 // Check for use of public/private annotation outside of os_log(). 5871 if (FSType != Sema::FST_OSLog) { 5872 if (FS.isPublic().isSet()) { 5873 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5874 << "public", 5875 getLocationOfByte(FS.isPublic().getPosition()), 5876 /*IsStringLocation*/ false, 5877 getSpecifierRange(startSpecifier, specifierLen)); 5878 } 5879 if (FS.isPrivate().isSet()) { 5880 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5881 << "private", 5882 getLocationOfByte(FS.isPrivate().getPosition()), 5883 /*IsStringLocation*/ false, 5884 getSpecifierRange(startSpecifier, specifierLen)); 5885 } 5886 } 5887 5888 // Check for invalid use of field width 5889 if (!FS.hasValidFieldWidth()) { 5890 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 5891 startSpecifier, specifierLen); 5892 } 5893 5894 // Check for invalid use of precision 5895 if (!FS.hasValidPrecision()) { 5896 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 5897 startSpecifier, specifierLen); 5898 } 5899 5900 // Precision is mandatory for %P specifier. 5901 if (CS.getKind() == ConversionSpecifier::PArg && 5902 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 5903 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 5904 getLocationOfByte(startSpecifier), 5905 /*IsStringLocation*/ false, 5906 getSpecifierRange(startSpecifier, specifierLen)); 5907 } 5908 5909 // Check each flag does not conflict with any other component. 5910 if (!FS.hasValidThousandsGroupingPrefix()) 5911 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 5912 if (!FS.hasValidLeadingZeros()) 5913 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 5914 if (!FS.hasValidPlusPrefix()) 5915 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 5916 if (!FS.hasValidSpacePrefix()) 5917 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 5918 if (!FS.hasValidAlternativeForm()) 5919 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 5920 if (!FS.hasValidLeftJustified()) 5921 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 5922 5923 // Check that flags are not ignored by another flag 5924 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 5925 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 5926 startSpecifier, specifierLen); 5927 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 5928 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 5929 startSpecifier, specifierLen); 5930 5931 // Check the length modifier is valid with the given conversion specifier. 5932 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5933 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5934 diag::warn_format_nonsensical_length); 5935 else if (!FS.hasStandardLengthModifier()) 5936 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5937 else if (!FS.hasStandardLengthConversionCombination()) 5938 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5939 diag::warn_format_non_standard_conversion_spec); 5940 5941 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5942 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5943 5944 // The remaining checks depend on the data arguments. 5945 if (HasVAListArg) 5946 return true; 5947 5948 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5949 return false; 5950 5951 const Expr *Arg = getDataArg(argIndex); 5952 if (!Arg) 5953 return true; 5954 5955 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 5956 } 5957 5958 static bool requiresParensToAddCast(const Expr *E) { 5959 // FIXME: We should have a general way to reason about operator 5960 // precedence and whether parens are actually needed here. 5961 // Take care of a few common cases where they aren't. 5962 const Expr *Inside = E->IgnoreImpCasts(); 5963 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 5964 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 5965 5966 switch (Inside->getStmtClass()) { 5967 case Stmt::ArraySubscriptExprClass: 5968 case Stmt::CallExprClass: 5969 case Stmt::CharacterLiteralClass: 5970 case Stmt::CXXBoolLiteralExprClass: 5971 case Stmt::DeclRefExprClass: 5972 case Stmt::FloatingLiteralClass: 5973 case Stmt::IntegerLiteralClass: 5974 case Stmt::MemberExprClass: 5975 case Stmt::ObjCArrayLiteralClass: 5976 case Stmt::ObjCBoolLiteralExprClass: 5977 case Stmt::ObjCBoxedExprClass: 5978 case Stmt::ObjCDictionaryLiteralClass: 5979 case Stmt::ObjCEncodeExprClass: 5980 case Stmt::ObjCIvarRefExprClass: 5981 case Stmt::ObjCMessageExprClass: 5982 case Stmt::ObjCPropertyRefExprClass: 5983 case Stmt::ObjCStringLiteralClass: 5984 case Stmt::ObjCSubscriptRefExprClass: 5985 case Stmt::ParenExprClass: 5986 case Stmt::StringLiteralClass: 5987 case Stmt::UnaryOperatorClass: 5988 return false; 5989 default: 5990 return true; 5991 } 5992 } 5993 5994 static std::pair<QualType, StringRef> 5995 shouldNotPrintDirectly(const ASTContext &Context, 5996 QualType IntendedTy, 5997 const Expr *E) { 5998 // Use a 'while' to peel off layers of typedefs. 5999 QualType TyTy = IntendedTy; 6000 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6001 StringRef Name = UserTy->getDecl()->getName(); 6002 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6003 .Case("CFIndex", Context.LongTy) 6004 .Case("NSInteger", Context.LongTy) 6005 .Case("NSUInteger", Context.UnsignedLongTy) 6006 .Case("SInt32", Context.IntTy) 6007 .Case("UInt32", Context.UnsignedIntTy) 6008 .Default(QualType()); 6009 6010 if (!CastTy.isNull()) 6011 return std::make_pair(CastTy, Name); 6012 6013 TyTy = UserTy->desugar(); 6014 } 6015 6016 // Strip parens if necessary. 6017 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6018 return shouldNotPrintDirectly(Context, 6019 PE->getSubExpr()->getType(), 6020 PE->getSubExpr()); 6021 6022 // If this is a conditional expression, then its result type is constructed 6023 // via usual arithmetic conversions and thus there might be no necessary 6024 // typedef sugar there. Recurse to operands to check for NSInteger & 6025 // Co. usage condition. 6026 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6027 QualType TrueTy, FalseTy; 6028 StringRef TrueName, FalseName; 6029 6030 std::tie(TrueTy, TrueName) = 6031 shouldNotPrintDirectly(Context, 6032 CO->getTrueExpr()->getType(), 6033 CO->getTrueExpr()); 6034 std::tie(FalseTy, FalseName) = 6035 shouldNotPrintDirectly(Context, 6036 CO->getFalseExpr()->getType(), 6037 CO->getFalseExpr()); 6038 6039 if (TrueTy == FalseTy) 6040 return std::make_pair(TrueTy, TrueName); 6041 else if (TrueTy.isNull()) 6042 return std::make_pair(FalseTy, FalseName); 6043 else if (FalseTy.isNull()) 6044 return std::make_pair(TrueTy, TrueName); 6045 } 6046 6047 return std::make_pair(QualType(), StringRef()); 6048 } 6049 6050 bool 6051 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6052 const char *StartSpecifier, 6053 unsigned SpecifierLen, 6054 const Expr *E) { 6055 using namespace analyze_format_string; 6056 using namespace analyze_printf; 6057 // Now type check the data expression that matches the 6058 // format specifier. 6059 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6060 if (!AT.isValid()) 6061 return true; 6062 6063 QualType ExprTy = E->getType(); 6064 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6065 ExprTy = TET->getUnderlyingExpr()->getType(); 6066 } 6067 6068 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6069 6070 if (match == analyze_printf::ArgType::Match) { 6071 return true; 6072 } 6073 6074 // Look through argument promotions for our error message's reported type. 6075 // This includes the integral and floating promotions, but excludes array 6076 // and function pointer decay; seeing that an argument intended to be a 6077 // string has type 'char [6]' is probably more confusing than 'char *'. 6078 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6079 if (ICE->getCastKind() == CK_IntegralCast || 6080 ICE->getCastKind() == CK_FloatingCast) { 6081 E = ICE->getSubExpr(); 6082 ExprTy = E->getType(); 6083 6084 // Check if we didn't match because of an implicit cast from a 'char' 6085 // or 'short' to an 'int'. This is done because printf is a varargs 6086 // function. 6087 if (ICE->getType() == S.Context.IntTy || 6088 ICE->getType() == S.Context.UnsignedIntTy) { 6089 // All further checking is done on the subexpression. 6090 if (AT.matchesType(S.Context, ExprTy)) 6091 return true; 6092 } 6093 } 6094 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6095 // Special case for 'a', which has type 'int' in C. 6096 // Note, however, that we do /not/ want to treat multibyte constants like 6097 // 'MooV' as characters! This form is deprecated but still exists. 6098 if (ExprTy == S.Context.IntTy) 6099 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6100 ExprTy = S.Context.CharTy; 6101 } 6102 6103 // Look through enums to their underlying type. 6104 bool IsEnum = false; 6105 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6106 ExprTy = EnumTy->getDecl()->getIntegerType(); 6107 IsEnum = true; 6108 } 6109 6110 // %C in an Objective-C context prints a unichar, not a wchar_t. 6111 // If the argument is an integer of some kind, believe the %C and suggest 6112 // a cast instead of changing the conversion specifier. 6113 QualType IntendedTy = ExprTy; 6114 if (isObjCContext() && 6115 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6116 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6117 !ExprTy->isCharType()) { 6118 // 'unichar' is defined as a typedef of unsigned short, but we should 6119 // prefer using the typedef if it is visible. 6120 IntendedTy = S.Context.UnsignedShortTy; 6121 6122 // While we are here, check if the value is an IntegerLiteral that happens 6123 // to be within the valid range. 6124 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6125 const llvm::APInt &V = IL->getValue(); 6126 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6127 return true; 6128 } 6129 6130 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6131 Sema::LookupOrdinaryName); 6132 if (S.LookupName(Result, S.getCurScope())) { 6133 NamedDecl *ND = Result.getFoundDecl(); 6134 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6135 if (TD->getUnderlyingType() == IntendedTy) 6136 IntendedTy = S.Context.getTypedefType(TD); 6137 } 6138 } 6139 } 6140 6141 // Special-case some of Darwin's platform-independence types by suggesting 6142 // casts to primitive types that are known to be large enough. 6143 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6144 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6145 QualType CastTy; 6146 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6147 if (!CastTy.isNull()) { 6148 IntendedTy = CastTy; 6149 ShouldNotPrintDirectly = true; 6150 } 6151 } 6152 6153 // We may be able to offer a FixItHint if it is a supported type. 6154 PrintfSpecifier fixedFS = FS; 6155 bool success = 6156 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6157 6158 if (success) { 6159 // Get the fix string from the fixed format specifier 6160 SmallString<16> buf; 6161 llvm::raw_svector_ostream os(buf); 6162 fixedFS.toString(os); 6163 6164 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6165 6166 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6167 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6168 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6169 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6170 } 6171 // In this case, the specifier is wrong and should be changed to match 6172 // the argument. 6173 EmitFormatDiagnostic(S.PDiag(diag) 6174 << AT.getRepresentativeTypeName(S.Context) 6175 << IntendedTy << IsEnum << E->getSourceRange(), 6176 E->getLocStart(), 6177 /*IsStringLocation*/ false, SpecRange, 6178 FixItHint::CreateReplacement(SpecRange, os.str())); 6179 } else { 6180 // The canonical type for formatting this value is different from the 6181 // actual type of the expression. (This occurs, for example, with Darwin's 6182 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6183 // should be printed as 'long' for 64-bit compatibility.) 6184 // Rather than emitting a normal format/argument mismatch, we want to 6185 // add a cast to the recommended type (and correct the format string 6186 // if necessary). 6187 SmallString<16> CastBuf; 6188 llvm::raw_svector_ostream CastFix(CastBuf); 6189 CastFix << "("; 6190 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6191 CastFix << ")"; 6192 6193 SmallVector<FixItHint,4> Hints; 6194 if (!AT.matchesType(S.Context, IntendedTy)) 6195 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6196 6197 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6198 // If there's already a cast present, just replace it. 6199 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6200 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6201 6202 } else if (!requiresParensToAddCast(E)) { 6203 // If the expression has high enough precedence, 6204 // just write the C-style cast. 6205 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6206 CastFix.str())); 6207 } else { 6208 // Otherwise, add parens around the expression as well as the cast. 6209 CastFix << "("; 6210 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6211 CastFix.str())); 6212 6213 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6214 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6215 } 6216 6217 if (ShouldNotPrintDirectly) { 6218 // The expression has a type that should not be printed directly. 6219 // We extract the name from the typedef because we don't want to show 6220 // the underlying type in the diagnostic. 6221 StringRef Name; 6222 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6223 Name = TypedefTy->getDecl()->getName(); 6224 else 6225 Name = CastTyName; 6226 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6227 << Name << IntendedTy << IsEnum 6228 << E->getSourceRange(), 6229 E->getLocStart(), /*IsStringLocation=*/false, 6230 SpecRange, Hints); 6231 } else { 6232 // In this case, the expression could be printed using a different 6233 // specifier, but we've decided that the specifier is probably correct 6234 // and we should cast instead. Just use the normal warning message. 6235 EmitFormatDiagnostic( 6236 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6237 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6238 << E->getSourceRange(), 6239 E->getLocStart(), /*IsStringLocation*/false, 6240 SpecRange, Hints); 6241 } 6242 } 6243 } else { 6244 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6245 SpecifierLen); 6246 // Since the warning for passing non-POD types to variadic functions 6247 // was deferred until now, we emit a warning for non-POD 6248 // arguments here. 6249 switch (S.isValidVarArgType(ExprTy)) { 6250 case Sema::VAK_Valid: 6251 case Sema::VAK_ValidInCXX11: { 6252 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6253 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6254 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6255 } 6256 6257 EmitFormatDiagnostic( 6258 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6259 << IsEnum << CSR << E->getSourceRange(), 6260 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6261 break; 6262 } 6263 case Sema::VAK_Undefined: 6264 case Sema::VAK_MSVCUndefined: 6265 EmitFormatDiagnostic( 6266 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6267 << S.getLangOpts().CPlusPlus11 6268 << ExprTy 6269 << CallType 6270 << AT.getRepresentativeTypeName(S.Context) 6271 << CSR 6272 << E->getSourceRange(), 6273 E->getLocStart(), /*IsStringLocation*/false, CSR); 6274 checkForCStrMembers(AT, E); 6275 break; 6276 6277 case Sema::VAK_Invalid: 6278 if (ExprTy->isObjCObjectType()) 6279 EmitFormatDiagnostic( 6280 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6281 << S.getLangOpts().CPlusPlus11 6282 << ExprTy 6283 << CallType 6284 << AT.getRepresentativeTypeName(S.Context) 6285 << CSR 6286 << E->getSourceRange(), 6287 E->getLocStart(), /*IsStringLocation*/false, CSR); 6288 else 6289 // FIXME: If this is an initializer list, suggest removing the braces 6290 // or inserting a cast to the target type. 6291 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6292 << isa<InitListExpr>(E) << ExprTy << CallType 6293 << AT.getRepresentativeTypeName(S.Context) 6294 << E->getSourceRange(); 6295 break; 6296 } 6297 6298 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6299 "format string specifier index out of range"); 6300 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6301 } 6302 6303 return true; 6304 } 6305 6306 //===--- CHECK: Scanf format string checking ------------------------------===// 6307 6308 namespace { 6309 class CheckScanfHandler : public CheckFormatHandler { 6310 public: 6311 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6312 const Expr *origFormatExpr, Sema::FormatStringType type, 6313 unsigned firstDataArg, unsigned numDataArgs, 6314 const char *beg, bool hasVAListArg, 6315 ArrayRef<const Expr *> Args, unsigned formatIdx, 6316 bool inFunctionCall, Sema::VariadicCallType CallType, 6317 llvm::SmallBitVector &CheckedVarArgs, 6318 UncoveredArgHandler &UncoveredArg) 6319 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6320 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6321 inFunctionCall, CallType, CheckedVarArgs, 6322 UncoveredArg) {} 6323 6324 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6325 const char *startSpecifier, 6326 unsigned specifierLen) override; 6327 6328 bool HandleInvalidScanfConversionSpecifier( 6329 const analyze_scanf::ScanfSpecifier &FS, 6330 const char *startSpecifier, 6331 unsigned specifierLen) override; 6332 6333 void HandleIncompleteScanList(const char *start, const char *end) override; 6334 }; 6335 } // end anonymous namespace 6336 6337 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6338 const char *end) { 6339 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6340 getLocationOfByte(end), /*IsStringLocation*/true, 6341 getSpecifierRange(start, end - start)); 6342 } 6343 6344 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6345 const analyze_scanf::ScanfSpecifier &FS, 6346 const char *startSpecifier, 6347 unsigned specifierLen) { 6348 6349 const analyze_scanf::ScanfConversionSpecifier &CS = 6350 FS.getConversionSpecifier(); 6351 6352 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6353 getLocationOfByte(CS.getStart()), 6354 startSpecifier, specifierLen, 6355 CS.getStart(), CS.getLength()); 6356 } 6357 6358 bool CheckScanfHandler::HandleScanfSpecifier( 6359 const analyze_scanf::ScanfSpecifier &FS, 6360 const char *startSpecifier, 6361 unsigned specifierLen) { 6362 using namespace analyze_scanf; 6363 using namespace analyze_format_string; 6364 6365 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6366 6367 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6368 // be used to decide if we are using positional arguments consistently. 6369 if (FS.consumesDataArgument()) { 6370 if (atFirstArg) { 6371 atFirstArg = false; 6372 usesPositionalArgs = FS.usesPositionalArg(); 6373 } 6374 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6375 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6376 startSpecifier, specifierLen); 6377 return false; 6378 } 6379 } 6380 6381 // Check if the field with is non-zero. 6382 const OptionalAmount &Amt = FS.getFieldWidth(); 6383 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6384 if (Amt.getConstantAmount() == 0) { 6385 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6386 Amt.getConstantLength()); 6387 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6388 getLocationOfByte(Amt.getStart()), 6389 /*IsStringLocation*/true, R, 6390 FixItHint::CreateRemoval(R)); 6391 } 6392 } 6393 6394 if (!FS.consumesDataArgument()) { 6395 // FIXME: Technically specifying a precision or field width here 6396 // makes no sense. Worth issuing a warning at some point. 6397 return true; 6398 } 6399 6400 // Consume the argument. 6401 unsigned argIndex = FS.getArgIndex(); 6402 if (argIndex < NumDataArgs) { 6403 // The check to see if the argIndex is valid will come later. 6404 // We set the bit here because we may exit early from this 6405 // function if we encounter some other error. 6406 CoveredArgs.set(argIndex); 6407 } 6408 6409 // Check the length modifier is valid with the given conversion specifier. 6410 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6411 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6412 diag::warn_format_nonsensical_length); 6413 else if (!FS.hasStandardLengthModifier()) 6414 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6415 else if (!FS.hasStandardLengthConversionCombination()) 6416 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6417 diag::warn_format_non_standard_conversion_spec); 6418 6419 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6420 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6421 6422 // The remaining checks depend on the data arguments. 6423 if (HasVAListArg) 6424 return true; 6425 6426 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6427 return false; 6428 6429 // Check that the argument type matches the format specifier. 6430 const Expr *Ex = getDataArg(argIndex); 6431 if (!Ex) 6432 return true; 6433 6434 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6435 6436 if (!AT.isValid()) { 6437 return true; 6438 } 6439 6440 analyze_format_string::ArgType::MatchKind match = 6441 AT.matchesType(S.Context, Ex->getType()); 6442 if (match == analyze_format_string::ArgType::Match) { 6443 return true; 6444 } 6445 6446 ScanfSpecifier fixedFS = FS; 6447 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6448 S.getLangOpts(), S.Context); 6449 6450 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6451 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6452 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6453 } 6454 6455 if (success) { 6456 // Get the fix string from the fixed format specifier. 6457 SmallString<128> buf; 6458 llvm::raw_svector_ostream os(buf); 6459 fixedFS.toString(os); 6460 6461 EmitFormatDiagnostic( 6462 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6463 << Ex->getType() << false << Ex->getSourceRange(), 6464 Ex->getLocStart(), 6465 /*IsStringLocation*/ false, 6466 getSpecifierRange(startSpecifier, specifierLen), 6467 FixItHint::CreateReplacement( 6468 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6469 } else { 6470 EmitFormatDiagnostic(S.PDiag(diag) 6471 << AT.getRepresentativeTypeName(S.Context) 6472 << Ex->getType() << false << Ex->getSourceRange(), 6473 Ex->getLocStart(), 6474 /*IsStringLocation*/ false, 6475 getSpecifierRange(startSpecifier, specifierLen)); 6476 } 6477 6478 return true; 6479 } 6480 6481 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6482 const Expr *OrigFormatExpr, 6483 ArrayRef<const Expr *> Args, 6484 bool HasVAListArg, unsigned format_idx, 6485 unsigned firstDataArg, 6486 Sema::FormatStringType Type, 6487 bool inFunctionCall, 6488 Sema::VariadicCallType CallType, 6489 llvm::SmallBitVector &CheckedVarArgs, 6490 UncoveredArgHandler &UncoveredArg) { 6491 // CHECK: is the format string a wide literal? 6492 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6493 CheckFormatHandler::EmitFormatDiagnostic( 6494 S, inFunctionCall, Args[format_idx], 6495 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6496 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6497 return; 6498 } 6499 6500 // Str - The format string. NOTE: this is NOT null-terminated! 6501 StringRef StrRef = FExpr->getString(); 6502 const char *Str = StrRef.data(); 6503 // Account for cases where the string literal is truncated in a declaration. 6504 const ConstantArrayType *T = 6505 S.Context.getAsConstantArrayType(FExpr->getType()); 6506 assert(T && "String literal not of constant array type!"); 6507 size_t TypeSize = T->getSize().getZExtValue(); 6508 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6509 const unsigned numDataArgs = Args.size() - firstDataArg; 6510 6511 // Emit a warning if the string literal is truncated and does not contain an 6512 // embedded null character. 6513 if (TypeSize <= StrRef.size() && 6514 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6515 CheckFormatHandler::EmitFormatDiagnostic( 6516 S, inFunctionCall, Args[format_idx], 6517 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6518 FExpr->getLocStart(), 6519 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6520 return; 6521 } 6522 6523 // CHECK: empty format string? 6524 if (StrLen == 0 && numDataArgs > 0) { 6525 CheckFormatHandler::EmitFormatDiagnostic( 6526 S, inFunctionCall, Args[format_idx], 6527 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6528 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6529 return; 6530 } 6531 6532 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6533 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6534 Type == Sema::FST_OSTrace) { 6535 CheckPrintfHandler H( 6536 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6537 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6538 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6539 CheckedVarArgs, UncoveredArg); 6540 6541 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6542 S.getLangOpts(), 6543 S.Context.getTargetInfo(), 6544 Type == Sema::FST_FreeBSDKPrintf)) 6545 H.DoneProcessing(); 6546 } else if (Type == Sema::FST_Scanf) { 6547 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6548 numDataArgs, Str, HasVAListArg, Args, format_idx, 6549 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6550 6551 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6552 S.getLangOpts(), 6553 S.Context.getTargetInfo())) 6554 H.DoneProcessing(); 6555 } // TODO: handle other formats 6556 } 6557 6558 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6559 // Str - The format string. NOTE: this is NOT null-terminated! 6560 StringRef StrRef = FExpr->getString(); 6561 const char *Str = StrRef.data(); 6562 // Account for cases where the string literal is truncated in a declaration. 6563 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6564 assert(T && "String literal not of constant array type!"); 6565 size_t TypeSize = T->getSize().getZExtValue(); 6566 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6567 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6568 getLangOpts(), 6569 Context.getTargetInfo()); 6570 } 6571 6572 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6573 6574 // Returns the related absolute value function that is larger, of 0 if one 6575 // does not exist. 6576 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6577 switch (AbsFunction) { 6578 default: 6579 return 0; 6580 6581 case Builtin::BI__builtin_abs: 6582 return Builtin::BI__builtin_labs; 6583 case Builtin::BI__builtin_labs: 6584 return Builtin::BI__builtin_llabs; 6585 case Builtin::BI__builtin_llabs: 6586 return 0; 6587 6588 case Builtin::BI__builtin_fabsf: 6589 return Builtin::BI__builtin_fabs; 6590 case Builtin::BI__builtin_fabs: 6591 return Builtin::BI__builtin_fabsl; 6592 case Builtin::BI__builtin_fabsl: 6593 return 0; 6594 6595 case Builtin::BI__builtin_cabsf: 6596 return Builtin::BI__builtin_cabs; 6597 case Builtin::BI__builtin_cabs: 6598 return Builtin::BI__builtin_cabsl; 6599 case Builtin::BI__builtin_cabsl: 6600 return 0; 6601 6602 case Builtin::BIabs: 6603 return Builtin::BIlabs; 6604 case Builtin::BIlabs: 6605 return Builtin::BIllabs; 6606 case Builtin::BIllabs: 6607 return 0; 6608 6609 case Builtin::BIfabsf: 6610 return Builtin::BIfabs; 6611 case Builtin::BIfabs: 6612 return Builtin::BIfabsl; 6613 case Builtin::BIfabsl: 6614 return 0; 6615 6616 case Builtin::BIcabsf: 6617 return Builtin::BIcabs; 6618 case Builtin::BIcabs: 6619 return Builtin::BIcabsl; 6620 case Builtin::BIcabsl: 6621 return 0; 6622 } 6623 } 6624 6625 // Returns the argument type of the absolute value function. 6626 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6627 unsigned AbsType) { 6628 if (AbsType == 0) 6629 return QualType(); 6630 6631 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6632 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6633 if (Error != ASTContext::GE_None) 6634 return QualType(); 6635 6636 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6637 if (!FT) 6638 return QualType(); 6639 6640 if (FT->getNumParams() != 1) 6641 return QualType(); 6642 6643 return FT->getParamType(0); 6644 } 6645 6646 // Returns the best absolute value function, or zero, based on type and 6647 // current absolute value function. 6648 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6649 unsigned AbsFunctionKind) { 6650 unsigned BestKind = 0; 6651 uint64_t ArgSize = Context.getTypeSize(ArgType); 6652 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6653 Kind = getLargerAbsoluteValueFunction(Kind)) { 6654 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6655 if (Context.getTypeSize(ParamType) >= ArgSize) { 6656 if (BestKind == 0) 6657 BestKind = Kind; 6658 else if (Context.hasSameType(ParamType, ArgType)) { 6659 BestKind = Kind; 6660 break; 6661 } 6662 } 6663 } 6664 return BestKind; 6665 } 6666 6667 enum AbsoluteValueKind { 6668 AVK_Integer, 6669 AVK_Floating, 6670 AVK_Complex 6671 }; 6672 6673 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6674 if (T->isIntegralOrEnumerationType()) 6675 return AVK_Integer; 6676 if (T->isRealFloatingType()) 6677 return AVK_Floating; 6678 if (T->isAnyComplexType()) 6679 return AVK_Complex; 6680 6681 llvm_unreachable("Type not integer, floating, or complex"); 6682 } 6683 6684 // Changes the absolute value function to a different type. Preserves whether 6685 // the function is a builtin. 6686 static unsigned changeAbsFunction(unsigned AbsKind, 6687 AbsoluteValueKind ValueKind) { 6688 switch (ValueKind) { 6689 case AVK_Integer: 6690 switch (AbsKind) { 6691 default: 6692 return 0; 6693 case Builtin::BI__builtin_fabsf: 6694 case Builtin::BI__builtin_fabs: 6695 case Builtin::BI__builtin_fabsl: 6696 case Builtin::BI__builtin_cabsf: 6697 case Builtin::BI__builtin_cabs: 6698 case Builtin::BI__builtin_cabsl: 6699 return Builtin::BI__builtin_abs; 6700 case Builtin::BIfabsf: 6701 case Builtin::BIfabs: 6702 case Builtin::BIfabsl: 6703 case Builtin::BIcabsf: 6704 case Builtin::BIcabs: 6705 case Builtin::BIcabsl: 6706 return Builtin::BIabs; 6707 } 6708 case AVK_Floating: 6709 switch (AbsKind) { 6710 default: 6711 return 0; 6712 case Builtin::BI__builtin_abs: 6713 case Builtin::BI__builtin_labs: 6714 case Builtin::BI__builtin_llabs: 6715 case Builtin::BI__builtin_cabsf: 6716 case Builtin::BI__builtin_cabs: 6717 case Builtin::BI__builtin_cabsl: 6718 return Builtin::BI__builtin_fabsf; 6719 case Builtin::BIabs: 6720 case Builtin::BIlabs: 6721 case Builtin::BIllabs: 6722 case Builtin::BIcabsf: 6723 case Builtin::BIcabs: 6724 case Builtin::BIcabsl: 6725 return Builtin::BIfabsf; 6726 } 6727 case AVK_Complex: 6728 switch (AbsKind) { 6729 default: 6730 return 0; 6731 case Builtin::BI__builtin_abs: 6732 case Builtin::BI__builtin_labs: 6733 case Builtin::BI__builtin_llabs: 6734 case Builtin::BI__builtin_fabsf: 6735 case Builtin::BI__builtin_fabs: 6736 case Builtin::BI__builtin_fabsl: 6737 return Builtin::BI__builtin_cabsf; 6738 case Builtin::BIabs: 6739 case Builtin::BIlabs: 6740 case Builtin::BIllabs: 6741 case Builtin::BIfabsf: 6742 case Builtin::BIfabs: 6743 case Builtin::BIfabsl: 6744 return Builtin::BIcabsf; 6745 } 6746 } 6747 llvm_unreachable("Unable to convert function"); 6748 } 6749 6750 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6751 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6752 if (!FnInfo) 6753 return 0; 6754 6755 switch (FDecl->getBuiltinID()) { 6756 default: 6757 return 0; 6758 case Builtin::BI__builtin_abs: 6759 case Builtin::BI__builtin_fabs: 6760 case Builtin::BI__builtin_fabsf: 6761 case Builtin::BI__builtin_fabsl: 6762 case Builtin::BI__builtin_labs: 6763 case Builtin::BI__builtin_llabs: 6764 case Builtin::BI__builtin_cabs: 6765 case Builtin::BI__builtin_cabsf: 6766 case Builtin::BI__builtin_cabsl: 6767 case Builtin::BIabs: 6768 case Builtin::BIlabs: 6769 case Builtin::BIllabs: 6770 case Builtin::BIfabs: 6771 case Builtin::BIfabsf: 6772 case Builtin::BIfabsl: 6773 case Builtin::BIcabs: 6774 case Builtin::BIcabsf: 6775 case Builtin::BIcabsl: 6776 return FDecl->getBuiltinID(); 6777 } 6778 llvm_unreachable("Unknown Builtin type"); 6779 } 6780 6781 // If the replacement is valid, emit a note with replacement function. 6782 // Additionally, suggest including the proper header if not already included. 6783 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6784 unsigned AbsKind, QualType ArgType) { 6785 bool EmitHeaderHint = true; 6786 const char *HeaderName = nullptr; 6787 const char *FunctionName = nullptr; 6788 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6789 FunctionName = "std::abs"; 6790 if (ArgType->isIntegralOrEnumerationType()) { 6791 HeaderName = "cstdlib"; 6792 } else if (ArgType->isRealFloatingType()) { 6793 HeaderName = "cmath"; 6794 } else { 6795 llvm_unreachable("Invalid Type"); 6796 } 6797 6798 // Lookup all std::abs 6799 if (NamespaceDecl *Std = S.getStdNamespace()) { 6800 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6801 R.suppressDiagnostics(); 6802 S.LookupQualifiedName(R, Std); 6803 6804 for (const auto *I : R) { 6805 const FunctionDecl *FDecl = nullptr; 6806 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6807 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6808 } else { 6809 FDecl = dyn_cast<FunctionDecl>(I); 6810 } 6811 if (!FDecl) 6812 continue; 6813 6814 // Found std::abs(), check that they are the right ones. 6815 if (FDecl->getNumParams() != 1) 6816 continue; 6817 6818 // Check that the parameter type can handle the argument. 6819 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6820 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6821 S.Context.getTypeSize(ArgType) <= 6822 S.Context.getTypeSize(ParamType)) { 6823 // Found a function, don't need the header hint. 6824 EmitHeaderHint = false; 6825 break; 6826 } 6827 } 6828 } 6829 } else { 6830 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6831 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6832 6833 if (HeaderName) { 6834 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6835 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6836 R.suppressDiagnostics(); 6837 S.LookupName(R, S.getCurScope()); 6838 6839 if (R.isSingleResult()) { 6840 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6841 if (FD && FD->getBuiltinID() == AbsKind) { 6842 EmitHeaderHint = false; 6843 } else { 6844 return; 6845 } 6846 } else if (!R.empty()) { 6847 return; 6848 } 6849 } 6850 } 6851 6852 S.Diag(Loc, diag::note_replace_abs_function) 6853 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 6854 6855 if (!HeaderName) 6856 return; 6857 6858 if (!EmitHeaderHint) 6859 return; 6860 6861 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 6862 << FunctionName; 6863 } 6864 6865 template <std::size_t StrLen> 6866 static bool IsStdFunction(const FunctionDecl *FDecl, 6867 const char (&Str)[StrLen]) { 6868 if (!FDecl) 6869 return false; 6870 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 6871 return false; 6872 if (!FDecl->isInStdNamespace()) 6873 return false; 6874 6875 return true; 6876 } 6877 6878 // Warn when using the wrong abs() function. 6879 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 6880 const FunctionDecl *FDecl) { 6881 if (Call->getNumArgs() != 1) 6882 return; 6883 6884 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 6885 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 6886 if (AbsKind == 0 && !IsStdAbs) 6887 return; 6888 6889 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6890 QualType ParamType = Call->getArg(0)->getType(); 6891 6892 // Unsigned types cannot be negative. Suggest removing the absolute value 6893 // function call. 6894 if (ArgType->isUnsignedIntegerType()) { 6895 const char *FunctionName = 6896 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 6897 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 6898 Diag(Call->getExprLoc(), diag::note_remove_abs) 6899 << FunctionName 6900 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 6901 return; 6902 } 6903 6904 // Taking the absolute value of a pointer is very suspicious, they probably 6905 // wanted to index into an array, dereference a pointer, call a function, etc. 6906 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 6907 unsigned DiagType = 0; 6908 if (ArgType->isFunctionType()) 6909 DiagType = 1; 6910 else if (ArgType->isArrayType()) 6911 DiagType = 2; 6912 6913 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 6914 return; 6915 } 6916 6917 // std::abs has overloads which prevent most of the absolute value problems 6918 // from occurring. 6919 if (IsStdAbs) 6920 return; 6921 6922 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 6923 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 6924 6925 // The argument and parameter are the same kind. Check if they are the right 6926 // size. 6927 if (ArgValueKind == ParamValueKind) { 6928 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 6929 return; 6930 6931 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 6932 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 6933 << FDecl << ArgType << ParamType; 6934 6935 if (NewAbsKind == 0) 6936 return; 6937 6938 emitReplacement(*this, Call->getExprLoc(), 6939 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6940 return; 6941 } 6942 6943 // ArgValueKind != ParamValueKind 6944 // The wrong type of absolute value function was used. Attempt to find the 6945 // proper one. 6946 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 6947 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 6948 if (NewAbsKind == 0) 6949 return; 6950 6951 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 6952 << FDecl << ParamValueKind << ArgValueKind; 6953 6954 emitReplacement(*this, Call->getExprLoc(), 6955 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6956 } 6957 6958 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 6959 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 6960 const FunctionDecl *FDecl) { 6961 if (!Call || !FDecl) return; 6962 6963 // Ignore template specializations and macros. 6964 if (inTemplateInstantiation()) return; 6965 if (Call->getExprLoc().isMacroID()) return; 6966 6967 // Only care about the one template argument, two function parameter std::max 6968 if (Call->getNumArgs() != 2) return; 6969 if (!IsStdFunction(FDecl, "max")) return; 6970 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 6971 if (!ArgList) return; 6972 if (ArgList->size() != 1) return; 6973 6974 // Check that template type argument is unsigned integer. 6975 const auto& TA = ArgList->get(0); 6976 if (TA.getKind() != TemplateArgument::Type) return; 6977 QualType ArgType = TA.getAsType(); 6978 if (!ArgType->isUnsignedIntegerType()) return; 6979 6980 // See if either argument is a literal zero. 6981 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 6982 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 6983 if (!MTE) return false; 6984 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 6985 if (!Num) return false; 6986 if (Num->getValue() != 0) return false; 6987 return true; 6988 }; 6989 6990 const Expr *FirstArg = Call->getArg(0); 6991 const Expr *SecondArg = Call->getArg(1); 6992 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 6993 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 6994 6995 // Only warn when exactly one argument is zero. 6996 if (IsFirstArgZero == IsSecondArgZero) return; 6997 6998 SourceRange FirstRange = FirstArg->getSourceRange(); 6999 SourceRange SecondRange = SecondArg->getSourceRange(); 7000 7001 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7002 7003 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7004 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7005 7006 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7007 SourceRange RemovalRange; 7008 if (IsFirstArgZero) { 7009 RemovalRange = SourceRange(FirstRange.getBegin(), 7010 SecondRange.getBegin().getLocWithOffset(-1)); 7011 } else { 7012 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7013 SecondRange.getEnd()); 7014 } 7015 7016 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7017 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7018 << FixItHint::CreateRemoval(RemovalRange); 7019 } 7020 7021 //===--- CHECK: Standard memory functions ---------------------------------===// 7022 7023 /// \brief Takes the expression passed to the size_t parameter of functions 7024 /// such as memcmp, strncat, etc and warns if it's a comparison. 7025 /// 7026 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7027 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7028 IdentifierInfo *FnName, 7029 SourceLocation FnLoc, 7030 SourceLocation RParenLoc) { 7031 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7032 if (!Size) 7033 return false; 7034 7035 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 7036 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 7037 return false; 7038 7039 SourceRange SizeRange = Size->getSourceRange(); 7040 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7041 << SizeRange << FnName; 7042 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7043 << FnName << FixItHint::CreateInsertion( 7044 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7045 << FixItHint::CreateRemoval(RParenLoc); 7046 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7047 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7048 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7049 ")"); 7050 7051 return true; 7052 } 7053 7054 /// \brief Determine whether the given type is or contains a dynamic class type 7055 /// (e.g., whether it has a vtable). 7056 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7057 bool &IsContained) { 7058 // Look through array types while ignoring qualifiers. 7059 const Type *Ty = T->getBaseElementTypeUnsafe(); 7060 IsContained = false; 7061 7062 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7063 RD = RD ? RD->getDefinition() : nullptr; 7064 if (!RD || RD->isInvalidDecl()) 7065 return nullptr; 7066 7067 if (RD->isDynamicClass()) 7068 return RD; 7069 7070 // Check all the fields. If any bases were dynamic, the class is dynamic. 7071 // It's impossible for a class to transitively contain itself by value, so 7072 // infinite recursion is impossible. 7073 for (auto *FD : RD->fields()) { 7074 bool SubContained; 7075 if (const CXXRecordDecl *ContainedRD = 7076 getContainedDynamicClass(FD->getType(), SubContained)) { 7077 IsContained = true; 7078 return ContainedRD; 7079 } 7080 } 7081 7082 return nullptr; 7083 } 7084 7085 /// \brief If E is a sizeof expression, returns its argument expression, 7086 /// otherwise returns NULL. 7087 static const Expr *getSizeOfExprArg(const Expr *E) { 7088 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7089 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7090 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 7091 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7092 7093 return nullptr; 7094 } 7095 7096 /// \brief If E is a sizeof expression, returns its argument type. 7097 static QualType getSizeOfArgType(const Expr *E) { 7098 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7099 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7100 if (SizeOf->getKind() == clang::UETT_SizeOf) 7101 return SizeOf->getTypeOfArgument(); 7102 7103 return QualType(); 7104 } 7105 7106 /// \brief Check for dangerous or invalid arguments to memset(). 7107 /// 7108 /// This issues warnings on known problematic, dangerous or unspecified 7109 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7110 /// function calls. 7111 /// 7112 /// \param Call The call expression to diagnose. 7113 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7114 unsigned BId, 7115 IdentifierInfo *FnName) { 7116 assert(BId != 0); 7117 7118 // It is possible to have a non-standard definition of memset. Validate 7119 // we have enough arguments, and if not, abort further checking. 7120 unsigned ExpectedNumArgs = 7121 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7122 if (Call->getNumArgs() < ExpectedNumArgs) 7123 return; 7124 7125 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7126 BId == Builtin::BIstrndup ? 1 : 2); 7127 unsigned LenArg = 7128 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7129 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7130 7131 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7132 Call->getLocStart(), Call->getRParenLoc())) 7133 return; 7134 7135 // We have special checking when the length is a sizeof expression. 7136 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7137 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7138 llvm::FoldingSetNodeID SizeOfArgID; 7139 7140 // Although widely used, 'bzero' is not a standard function. Be more strict 7141 // with the argument types before allowing diagnostics and only allow the 7142 // form bzero(ptr, sizeof(...)). 7143 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7144 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7145 return; 7146 7147 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7148 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7149 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7150 7151 QualType DestTy = Dest->getType(); 7152 QualType PointeeTy; 7153 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7154 PointeeTy = DestPtrTy->getPointeeType(); 7155 7156 // Never warn about void type pointers. This can be used to suppress 7157 // false positives. 7158 if (PointeeTy->isVoidType()) 7159 continue; 7160 7161 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7162 // actually comparing the expressions for equality. Because computing the 7163 // expression IDs can be expensive, we only do this if the diagnostic is 7164 // enabled. 7165 if (SizeOfArg && 7166 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7167 SizeOfArg->getExprLoc())) { 7168 // We only compute IDs for expressions if the warning is enabled, and 7169 // cache the sizeof arg's ID. 7170 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7171 SizeOfArg->Profile(SizeOfArgID, Context, true); 7172 llvm::FoldingSetNodeID DestID; 7173 Dest->Profile(DestID, Context, true); 7174 if (DestID == SizeOfArgID) { 7175 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7176 // over sizeof(src) as well. 7177 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7178 StringRef ReadableName = FnName->getName(); 7179 7180 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7181 if (UnaryOp->getOpcode() == UO_AddrOf) 7182 ActionIdx = 1; // If its an address-of operator, just remove it. 7183 if (!PointeeTy->isIncompleteType() && 7184 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7185 ActionIdx = 2; // If the pointee's size is sizeof(char), 7186 // suggest an explicit length. 7187 7188 // If the function is defined as a builtin macro, do not show macro 7189 // expansion. 7190 SourceLocation SL = SizeOfArg->getExprLoc(); 7191 SourceRange DSR = Dest->getSourceRange(); 7192 SourceRange SSR = SizeOfArg->getSourceRange(); 7193 SourceManager &SM = getSourceManager(); 7194 7195 if (SM.isMacroArgExpansion(SL)) { 7196 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7197 SL = SM.getSpellingLoc(SL); 7198 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7199 SM.getSpellingLoc(DSR.getEnd())); 7200 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7201 SM.getSpellingLoc(SSR.getEnd())); 7202 } 7203 7204 DiagRuntimeBehavior(SL, SizeOfArg, 7205 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7206 << ReadableName 7207 << PointeeTy 7208 << DestTy 7209 << DSR 7210 << SSR); 7211 DiagRuntimeBehavior(SL, SizeOfArg, 7212 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7213 << ActionIdx 7214 << SSR); 7215 7216 break; 7217 } 7218 } 7219 7220 // Also check for cases where the sizeof argument is the exact same 7221 // type as the memory argument, and where it points to a user-defined 7222 // record type. 7223 if (SizeOfArgTy != QualType()) { 7224 if (PointeeTy->isRecordType() && 7225 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7226 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7227 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7228 << FnName << SizeOfArgTy << ArgIdx 7229 << PointeeTy << Dest->getSourceRange() 7230 << LenExpr->getSourceRange()); 7231 break; 7232 } 7233 } 7234 } else if (DestTy->isArrayType()) { 7235 PointeeTy = DestTy; 7236 } 7237 7238 if (PointeeTy == QualType()) 7239 continue; 7240 7241 // Always complain about dynamic classes. 7242 bool IsContained; 7243 if (const CXXRecordDecl *ContainedRD = 7244 getContainedDynamicClass(PointeeTy, IsContained)) { 7245 7246 unsigned OperationType = 0; 7247 // "overwritten" if we're warning about the destination for any call 7248 // but memcmp; otherwise a verb appropriate to the call. 7249 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7250 if (BId == Builtin::BImemcpy) 7251 OperationType = 1; 7252 else if(BId == Builtin::BImemmove) 7253 OperationType = 2; 7254 else if (BId == Builtin::BImemcmp) 7255 OperationType = 3; 7256 } 7257 7258 DiagRuntimeBehavior( 7259 Dest->getExprLoc(), Dest, 7260 PDiag(diag::warn_dyn_class_memaccess) 7261 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7262 << FnName << IsContained << ContainedRD << OperationType 7263 << Call->getCallee()->getSourceRange()); 7264 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7265 BId != Builtin::BImemset) 7266 DiagRuntimeBehavior( 7267 Dest->getExprLoc(), Dest, 7268 PDiag(diag::warn_arc_object_memaccess) 7269 << ArgIdx << FnName << PointeeTy 7270 << Call->getCallee()->getSourceRange()); 7271 else 7272 continue; 7273 7274 DiagRuntimeBehavior( 7275 Dest->getExprLoc(), Dest, 7276 PDiag(diag::note_bad_memaccess_silence) 7277 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7278 break; 7279 } 7280 } 7281 7282 // A little helper routine: ignore addition and subtraction of integer literals. 7283 // This intentionally does not ignore all integer constant expressions because 7284 // we don't want to remove sizeof(). 7285 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7286 Ex = Ex->IgnoreParenCasts(); 7287 7288 for (;;) { 7289 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7290 if (!BO || !BO->isAdditiveOp()) 7291 break; 7292 7293 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7294 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7295 7296 if (isa<IntegerLiteral>(RHS)) 7297 Ex = LHS; 7298 else if (isa<IntegerLiteral>(LHS)) 7299 Ex = RHS; 7300 else 7301 break; 7302 } 7303 7304 return Ex; 7305 } 7306 7307 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7308 ASTContext &Context) { 7309 // Only handle constant-sized or VLAs, but not flexible members. 7310 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7311 // Only issue the FIXIT for arrays of size > 1. 7312 if (CAT->getSize().getSExtValue() <= 1) 7313 return false; 7314 } else if (!Ty->isVariableArrayType()) { 7315 return false; 7316 } 7317 return true; 7318 } 7319 7320 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7321 // be the size of the source, instead of the destination. 7322 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7323 IdentifierInfo *FnName) { 7324 7325 // Don't crash if the user has the wrong number of arguments 7326 unsigned NumArgs = Call->getNumArgs(); 7327 if ((NumArgs != 3) && (NumArgs != 4)) 7328 return; 7329 7330 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7331 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7332 const Expr *CompareWithSrc = nullptr; 7333 7334 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7335 Call->getLocStart(), Call->getRParenLoc())) 7336 return; 7337 7338 // Look for 'strlcpy(dst, x, sizeof(x))' 7339 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7340 CompareWithSrc = Ex; 7341 else { 7342 // Look for 'strlcpy(dst, x, strlen(x))' 7343 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7344 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7345 SizeCall->getNumArgs() == 1) 7346 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7347 } 7348 } 7349 7350 if (!CompareWithSrc) 7351 return; 7352 7353 // Determine if the argument to sizeof/strlen is equal to the source 7354 // argument. In principle there's all kinds of things you could do 7355 // here, for instance creating an == expression and evaluating it with 7356 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7357 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7358 if (!SrcArgDRE) 7359 return; 7360 7361 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7362 if (!CompareWithSrcDRE || 7363 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7364 return; 7365 7366 const Expr *OriginalSizeArg = Call->getArg(2); 7367 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7368 << OriginalSizeArg->getSourceRange() << FnName; 7369 7370 // Output a FIXIT hint if the destination is an array (rather than a 7371 // pointer to an array). This could be enhanced to handle some 7372 // pointers if we know the actual size, like if DstArg is 'array+2' 7373 // we could say 'sizeof(array)-2'. 7374 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7375 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7376 return; 7377 7378 SmallString<128> sizeString; 7379 llvm::raw_svector_ostream OS(sizeString); 7380 OS << "sizeof("; 7381 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7382 OS << ")"; 7383 7384 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7385 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7386 OS.str()); 7387 } 7388 7389 /// Check if two expressions refer to the same declaration. 7390 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7391 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7392 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7393 return D1->getDecl() == D2->getDecl(); 7394 return false; 7395 } 7396 7397 static const Expr *getStrlenExprArg(const Expr *E) { 7398 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7399 const FunctionDecl *FD = CE->getDirectCallee(); 7400 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7401 return nullptr; 7402 return CE->getArg(0)->IgnoreParenCasts(); 7403 } 7404 return nullptr; 7405 } 7406 7407 // Warn on anti-patterns as the 'size' argument to strncat. 7408 // The correct size argument should look like following: 7409 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7410 void Sema::CheckStrncatArguments(const CallExpr *CE, 7411 IdentifierInfo *FnName) { 7412 // Don't crash if the user has the wrong number of arguments. 7413 if (CE->getNumArgs() < 3) 7414 return; 7415 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7416 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7417 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7418 7419 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7420 CE->getRParenLoc())) 7421 return; 7422 7423 // Identify common expressions, which are wrongly used as the size argument 7424 // to strncat and may lead to buffer overflows. 7425 unsigned PatternType = 0; 7426 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7427 // - sizeof(dst) 7428 if (referToTheSameDecl(SizeOfArg, DstArg)) 7429 PatternType = 1; 7430 // - sizeof(src) 7431 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7432 PatternType = 2; 7433 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7434 if (BE->getOpcode() == BO_Sub) { 7435 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7436 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7437 // - sizeof(dst) - strlen(dst) 7438 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7439 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7440 PatternType = 1; 7441 // - sizeof(src) - (anything) 7442 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7443 PatternType = 2; 7444 } 7445 } 7446 7447 if (PatternType == 0) 7448 return; 7449 7450 // Generate the diagnostic. 7451 SourceLocation SL = LenArg->getLocStart(); 7452 SourceRange SR = LenArg->getSourceRange(); 7453 SourceManager &SM = getSourceManager(); 7454 7455 // If the function is defined as a builtin macro, do not show macro expansion. 7456 if (SM.isMacroArgExpansion(SL)) { 7457 SL = SM.getSpellingLoc(SL); 7458 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7459 SM.getSpellingLoc(SR.getEnd())); 7460 } 7461 7462 // Check if the destination is an array (rather than a pointer to an array). 7463 QualType DstTy = DstArg->getType(); 7464 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7465 Context); 7466 if (!isKnownSizeArray) { 7467 if (PatternType == 1) 7468 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7469 else 7470 Diag(SL, diag::warn_strncat_src_size) << SR; 7471 return; 7472 } 7473 7474 if (PatternType == 1) 7475 Diag(SL, diag::warn_strncat_large_size) << SR; 7476 else 7477 Diag(SL, diag::warn_strncat_src_size) << SR; 7478 7479 SmallString<128> sizeString; 7480 llvm::raw_svector_ostream OS(sizeString); 7481 OS << "sizeof("; 7482 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7483 OS << ") - "; 7484 OS << "strlen("; 7485 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7486 OS << ") - 1"; 7487 7488 Diag(SL, diag::note_strncat_wrong_size) 7489 << FixItHint::CreateReplacement(SR, OS.str()); 7490 } 7491 7492 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7493 7494 static const Expr *EvalVal(const Expr *E, 7495 SmallVectorImpl<const DeclRefExpr *> &refVars, 7496 const Decl *ParentDecl); 7497 static const Expr *EvalAddr(const Expr *E, 7498 SmallVectorImpl<const DeclRefExpr *> &refVars, 7499 const Decl *ParentDecl); 7500 7501 /// CheckReturnStackAddr - Check if a return statement returns the address 7502 /// of a stack variable. 7503 static void 7504 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7505 SourceLocation ReturnLoc) { 7506 7507 const Expr *stackE = nullptr; 7508 SmallVector<const DeclRefExpr *, 8> refVars; 7509 7510 // Perform checking for returned stack addresses, local blocks, 7511 // label addresses or references to temporaries. 7512 if (lhsType->isPointerType() || 7513 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7514 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7515 } else if (lhsType->isReferenceType()) { 7516 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7517 } 7518 7519 if (!stackE) 7520 return; // Nothing suspicious was found. 7521 7522 // Parameters are initialized in the calling scope, so taking the address 7523 // of a parameter reference doesn't need a warning. 7524 for (auto *DRE : refVars) 7525 if (isa<ParmVarDecl>(DRE->getDecl())) 7526 return; 7527 7528 SourceLocation diagLoc; 7529 SourceRange diagRange; 7530 if (refVars.empty()) { 7531 diagLoc = stackE->getLocStart(); 7532 diagRange = stackE->getSourceRange(); 7533 } else { 7534 // We followed through a reference variable. 'stackE' contains the 7535 // problematic expression but we will warn at the return statement pointing 7536 // at the reference variable. We will later display the "trail" of 7537 // reference variables using notes. 7538 diagLoc = refVars[0]->getLocStart(); 7539 diagRange = refVars[0]->getSourceRange(); 7540 } 7541 7542 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7543 // address of local var 7544 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7545 << DR->getDecl()->getDeclName() << diagRange; 7546 } else if (isa<BlockExpr>(stackE)) { // local block. 7547 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7548 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7549 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7550 } else { // local temporary. 7551 // If there is an LValue->RValue conversion, then the value of the 7552 // reference type is used, not the reference. 7553 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7554 if (ICE->getCastKind() == CK_LValueToRValue) { 7555 return; 7556 } 7557 } 7558 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7559 << lhsType->isReferenceType() << diagRange; 7560 } 7561 7562 // Display the "trail" of reference variables that we followed until we 7563 // found the problematic expression using notes. 7564 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7565 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7566 // If this var binds to another reference var, show the range of the next 7567 // var, otherwise the var binds to the problematic expression, in which case 7568 // show the range of the expression. 7569 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7570 : stackE->getSourceRange(); 7571 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7572 << VD->getDeclName() << range; 7573 } 7574 } 7575 7576 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7577 /// check if the expression in a return statement evaluates to an address 7578 /// to a location on the stack, a local block, an address of a label, or a 7579 /// reference to local temporary. The recursion is used to traverse the 7580 /// AST of the return expression, with recursion backtracking when we 7581 /// encounter a subexpression that (1) clearly does not lead to one of the 7582 /// above problematic expressions (2) is something we cannot determine leads to 7583 /// a problematic expression based on such local checking. 7584 /// 7585 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7586 /// the expression that they point to. Such variables are added to the 7587 /// 'refVars' vector so that we know what the reference variable "trail" was. 7588 /// 7589 /// EvalAddr processes expressions that are pointers that are used as 7590 /// references (and not L-values). EvalVal handles all other values. 7591 /// At the base case of the recursion is a check for the above problematic 7592 /// expressions. 7593 /// 7594 /// This implementation handles: 7595 /// 7596 /// * pointer-to-pointer casts 7597 /// * implicit conversions from array references to pointers 7598 /// * taking the address of fields 7599 /// * arbitrary interplay between "&" and "*" operators 7600 /// * pointer arithmetic from an address of a stack variable 7601 /// * taking the address of an array element where the array is on the stack 7602 static const Expr *EvalAddr(const Expr *E, 7603 SmallVectorImpl<const DeclRefExpr *> &refVars, 7604 const Decl *ParentDecl) { 7605 if (E->isTypeDependent()) 7606 return nullptr; 7607 7608 // We should only be called for evaluating pointer expressions. 7609 assert((E->getType()->isAnyPointerType() || 7610 E->getType()->isBlockPointerType() || 7611 E->getType()->isObjCQualifiedIdType()) && 7612 "EvalAddr only works on pointers"); 7613 7614 E = E->IgnoreParens(); 7615 7616 // Our "symbolic interpreter" is just a dispatch off the currently 7617 // viewed AST node. We then recursively traverse the AST by calling 7618 // EvalAddr and EvalVal appropriately. 7619 switch (E->getStmtClass()) { 7620 case Stmt::DeclRefExprClass: { 7621 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7622 7623 // If we leave the immediate function, the lifetime isn't about to end. 7624 if (DR->refersToEnclosingVariableOrCapture()) 7625 return nullptr; 7626 7627 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7628 // If this is a reference variable, follow through to the expression that 7629 // it points to. 7630 if (V->hasLocalStorage() && 7631 V->getType()->isReferenceType() && V->hasInit()) { 7632 // Add the reference variable to the "trail". 7633 refVars.push_back(DR); 7634 return EvalAddr(V->getInit(), refVars, ParentDecl); 7635 } 7636 7637 return nullptr; 7638 } 7639 7640 case Stmt::UnaryOperatorClass: { 7641 // The only unary operator that make sense to handle here 7642 // is AddrOf. All others don't make sense as pointers. 7643 const UnaryOperator *U = cast<UnaryOperator>(E); 7644 7645 if (U->getOpcode() == UO_AddrOf) 7646 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7647 return nullptr; 7648 } 7649 7650 case Stmt::BinaryOperatorClass: { 7651 // Handle pointer arithmetic. All other binary operators are not valid 7652 // in this context. 7653 const BinaryOperator *B = cast<BinaryOperator>(E); 7654 BinaryOperatorKind op = B->getOpcode(); 7655 7656 if (op != BO_Add && op != BO_Sub) 7657 return nullptr; 7658 7659 const Expr *Base = B->getLHS(); 7660 7661 // Determine which argument is the real pointer base. It could be 7662 // the RHS argument instead of the LHS. 7663 if (!Base->getType()->isPointerType()) 7664 Base = B->getRHS(); 7665 7666 assert(Base->getType()->isPointerType()); 7667 return EvalAddr(Base, refVars, ParentDecl); 7668 } 7669 7670 // For conditional operators we need to see if either the LHS or RHS are 7671 // valid DeclRefExpr*s. If one of them is valid, we return it. 7672 case Stmt::ConditionalOperatorClass: { 7673 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7674 7675 // Handle the GNU extension for missing LHS. 7676 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7677 if (const Expr *LHSExpr = C->getLHS()) { 7678 // In C++, we can have a throw-expression, which has 'void' type. 7679 if (!LHSExpr->getType()->isVoidType()) 7680 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7681 return LHS; 7682 } 7683 7684 // In C++, we can have a throw-expression, which has 'void' type. 7685 if (C->getRHS()->getType()->isVoidType()) 7686 return nullptr; 7687 7688 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7689 } 7690 7691 case Stmt::BlockExprClass: 7692 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7693 return E; // local block. 7694 return nullptr; 7695 7696 case Stmt::AddrLabelExprClass: 7697 return E; // address of label. 7698 7699 case Stmt::ExprWithCleanupsClass: 7700 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7701 ParentDecl); 7702 7703 // For casts, we need to handle conversions from arrays to 7704 // pointer values, and pointer-to-pointer conversions. 7705 case Stmt::ImplicitCastExprClass: 7706 case Stmt::CStyleCastExprClass: 7707 case Stmt::CXXFunctionalCastExprClass: 7708 case Stmt::ObjCBridgedCastExprClass: 7709 case Stmt::CXXStaticCastExprClass: 7710 case Stmt::CXXDynamicCastExprClass: 7711 case Stmt::CXXConstCastExprClass: 7712 case Stmt::CXXReinterpretCastExprClass: { 7713 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7714 switch (cast<CastExpr>(E)->getCastKind()) { 7715 case CK_LValueToRValue: 7716 case CK_NoOp: 7717 case CK_BaseToDerived: 7718 case CK_DerivedToBase: 7719 case CK_UncheckedDerivedToBase: 7720 case CK_Dynamic: 7721 case CK_CPointerToObjCPointerCast: 7722 case CK_BlockPointerToObjCPointerCast: 7723 case CK_AnyPointerToBlockPointerCast: 7724 return EvalAddr(SubExpr, refVars, ParentDecl); 7725 7726 case CK_ArrayToPointerDecay: 7727 return EvalVal(SubExpr, refVars, ParentDecl); 7728 7729 case CK_BitCast: 7730 if (SubExpr->getType()->isAnyPointerType() || 7731 SubExpr->getType()->isBlockPointerType() || 7732 SubExpr->getType()->isObjCQualifiedIdType()) 7733 return EvalAddr(SubExpr, refVars, ParentDecl); 7734 else 7735 return nullptr; 7736 7737 default: 7738 return nullptr; 7739 } 7740 } 7741 7742 case Stmt::MaterializeTemporaryExprClass: 7743 if (const Expr *Result = 7744 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7745 refVars, ParentDecl)) 7746 return Result; 7747 return E; 7748 7749 // Everything else: we simply don't reason about them. 7750 default: 7751 return nullptr; 7752 } 7753 } 7754 7755 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7756 /// See the comments for EvalAddr for more details. 7757 static const Expr *EvalVal(const Expr *E, 7758 SmallVectorImpl<const DeclRefExpr *> &refVars, 7759 const Decl *ParentDecl) { 7760 do { 7761 // We should only be called for evaluating non-pointer expressions, or 7762 // expressions with a pointer type that are not used as references but 7763 // instead 7764 // are l-values (e.g., DeclRefExpr with a pointer type). 7765 7766 // Our "symbolic interpreter" is just a dispatch off the currently 7767 // viewed AST node. We then recursively traverse the AST by calling 7768 // EvalAddr and EvalVal appropriately. 7769 7770 E = E->IgnoreParens(); 7771 switch (E->getStmtClass()) { 7772 case Stmt::ImplicitCastExprClass: { 7773 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7774 if (IE->getValueKind() == VK_LValue) { 7775 E = IE->getSubExpr(); 7776 continue; 7777 } 7778 return nullptr; 7779 } 7780 7781 case Stmt::ExprWithCleanupsClass: 7782 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7783 ParentDecl); 7784 7785 case Stmt::DeclRefExprClass: { 7786 // When we hit a DeclRefExpr we are looking at code that refers to a 7787 // variable's name. If it's not a reference variable we check if it has 7788 // local storage within the function, and if so, return the expression. 7789 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7790 7791 // If we leave the immediate function, the lifetime isn't about to end. 7792 if (DR->refersToEnclosingVariableOrCapture()) 7793 return nullptr; 7794 7795 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7796 // Check if it refers to itself, e.g. "int& i = i;". 7797 if (V == ParentDecl) 7798 return DR; 7799 7800 if (V->hasLocalStorage()) { 7801 if (!V->getType()->isReferenceType()) 7802 return DR; 7803 7804 // Reference variable, follow through to the expression that 7805 // it points to. 7806 if (V->hasInit()) { 7807 // Add the reference variable to the "trail". 7808 refVars.push_back(DR); 7809 return EvalVal(V->getInit(), refVars, V); 7810 } 7811 } 7812 } 7813 7814 return nullptr; 7815 } 7816 7817 case Stmt::UnaryOperatorClass: { 7818 // The only unary operator that make sense to handle here 7819 // is Deref. All others don't resolve to a "name." This includes 7820 // handling all sorts of rvalues passed to a unary operator. 7821 const UnaryOperator *U = cast<UnaryOperator>(E); 7822 7823 if (U->getOpcode() == UO_Deref) 7824 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7825 7826 return nullptr; 7827 } 7828 7829 case Stmt::ArraySubscriptExprClass: { 7830 // Array subscripts are potential references to data on the stack. We 7831 // retrieve the DeclRefExpr* for the array variable if it indeed 7832 // has local storage. 7833 const auto *ASE = cast<ArraySubscriptExpr>(E); 7834 if (ASE->isTypeDependent()) 7835 return nullptr; 7836 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7837 } 7838 7839 case Stmt::OMPArraySectionExprClass: { 7840 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7841 ParentDecl); 7842 } 7843 7844 case Stmt::ConditionalOperatorClass: { 7845 // For conditional operators we need to see if either the LHS or RHS are 7846 // non-NULL Expr's. If one is non-NULL, we return it. 7847 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7848 7849 // Handle the GNU extension for missing LHS. 7850 if (const Expr *LHSExpr = C->getLHS()) { 7851 // In C++, we can have a throw-expression, which has 'void' type. 7852 if (!LHSExpr->getType()->isVoidType()) 7853 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 7854 return LHS; 7855 } 7856 7857 // In C++, we can have a throw-expression, which has 'void' type. 7858 if (C->getRHS()->getType()->isVoidType()) 7859 return nullptr; 7860 7861 return EvalVal(C->getRHS(), refVars, ParentDecl); 7862 } 7863 7864 // Accesses to members are potential references to data on the stack. 7865 case Stmt::MemberExprClass: { 7866 const MemberExpr *M = cast<MemberExpr>(E); 7867 7868 // Check for indirect access. We only want direct field accesses. 7869 if (M->isArrow()) 7870 return nullptr; 7871 7872 // Check whether the member type is itself a reference, in which case 7873 // we're not going to refer to the member, but to what the member refers 7874 // to. 7875 if (M->getMemberDecl()->getType()->isReferenceType()) 7876 return nullptr; 7877 7878 return EvalVal(M->getBase(), refVars, ParentDecl); 7879 } 7880 7881 case Stmt::MaterializeTemporaryExprClass: 7882 if (const Expr *Result = 7883 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7884 refVars, ParentDecl)) 7885 return Result; 7886 return E; 7887 7888 default: 7889 // Check that we don't return or take the address of a reference to a 7890 // temporary. This is only useful in C++. 7891 if (!E->isTypeDependent() && E->isRValue()) 7892 return E; 7893 7894 // Everything else: we simply don't reason about them. 7895 return nullptr; 7896 } 7897 } while (true); 7898 } 7899 7900 void 7901 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 7902 SourceLocation ReturnLoc, 7903 bool isObjCMethod, 7904 const AttrVec *Attrs, 7905 const FunctionDecl *FD) { 7906 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 7907 7908 // Check if the return value is null but should not be. 7909 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 7910 (!isObjCMethod && isNonNullType(Context, lhsType))) && 7911 CheckNonNullExpr(*this, RetValExp)) 7912 Diag(ReturnLoc, diag::warn_null_ret) 7913 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 7914 7915 // C++11 [basic.stc.dynamic.allocation]p4: 7916 // If an allocation function declared with a non-throwing 7917 // exception-specification fails to allocate storage, it shall return 7918 // a null pointer. Any other allocation function that fails to allocate 7919 // storage shall indicate failure only by throwing an exception [...] 7920 if (FD) { 7921 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 7922 if (Op == OO_New || Op == OO_Array_New) { 7923 const FunctionProtoType *Proto 7924 = FD->getType()->castAs<FunctionProtoType>(); 7925 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 7926 CheckNonNullExpr(*this, RetValExp)) 7927 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 7928 << FD << getLangOpts().CPlusPlus11; 7929 } 7930 } 7931 } 7932 7933 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 7934 7935 /// Check for comparisons of floating point operands using != and ==. 7936 /// Issue a warning if these are no self-comparisons, as they are not likely 7937 /// to do what the programmer intended. 7938 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 7939 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 7940 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 7941 7942 // Special case: check for x == x (which is OK). 7943 // Do not emit warnings for such cases. 7944 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 7945 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 7946 if (DRL->getDecl() == DRR->getDecl()) 7947 return; 7948 7949 // Special case: check for comparisons against literals that can be exactly 7950 // represented by APFloat. In such cases, do not emit a warning. This 7951 // is a heuristic: often comparison against such literals are used to 7952 // detect if a value in a variable has not changed. This clearly can 7953 // lead to false negatives. 7954 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 7955 if (FLL->isExact()) 7956 return; 7957 } else 7958 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 7959 if (FLR->isExact()) 7960 return; 7961 7962 // Check for comparisons with builtin types. 7963 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 7964 if (CL->getBuiltinCallee()) 7965 return; 7966 7967 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 7968 if (CR->getBuiltinCallee()) 7969 return; 7970 7971 // Emit the diagnostic. 7972 Diag(Loc, diag::warn_floatingpoint_eq) 7973 << LHS->getSourceRange() << RHS->getSourceRange(); 7974 } 7975 7976 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 7977 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 7978 7979 namespace { 7980 7981 /// Structure recording the 'active' range of an integer-valued 7982 /// expression. 7983 struct IntRange { 7984 /// The number of bits active in the int. 7985 unsigned Width; 7986 7987 /// True if the int is known not to have negative values. 7988 bool NonNegative; 7989 7990 IntRange(unsigned Width, bool NonNegative) 7991 : Width(Width), NonNegative(NonNegative) 7992 {} 7993 7994 /// Returns the range of the bool type. 7995 static IntRange forBoolType() { 7996 return IntRange(1, true); 7997 } 7998 7999 /// Returns the range of an opaque value of the given integral type. 8000 static IntRange forValueOfType(ASTContext &C, QualType T) { 8001 return forValueOfCanonicalType(C, 8002 T->getCanonicalTypeInternal().getTypePtr()); 8003 } 8004 8005 /// Returns the range of an opaque value of a canonical integral type. 8006 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8007 assert(T->isCanonicalUnqualified()); 8008 8009 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8010 T = VT->getElementType().getTypePtr(); 8011 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8012 T = CT->getElementType().getTypePtr(); 8013 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8014 T = AT->getValueType().getTypePtr(); 8015 8016 // For enum types, use the known bit width of the enumerators. 8017 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8018 EnumDecl *Enum = ET->getDecl(); 8019 if (!Enum->isCompleteDefinition()) 8020 return IntRange(C.getIntWidth(QualType(T, 0)), false); 8021 8022 unsigned NumPositive = Enum->getNumPositiveBits(); 8023 unsigned NumNegative = Enum->getNumNegativeBits(); 8024 8025 if (NumNegative == 0) 8026 return IntRange(NumPositive, true/*NonNegative*/); 8027 else 8028 return IntRange(std::max(NumPositive + 1, NumNegative), 8029 false/*NonNegative*/); 8030 } 8031 8032 const BuiltinType *BT = cast<BuiltinType>(T); 8033 assert(BT->isInteger()); 8034 8035 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8036 } 8037 8038 /// Returns the "target" range of a canonical integral type, i.e. 8039 /// the range of values expressible in the type. 8040 /// 8041 /// This matches forValueOfCanonicalType except that enums have the 8042 /// full range of their type, not the range of their enumerators. 8043 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8044 assert(T->isCanonicalUnqualified()); 8045 8046 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8047 T = VT->getElementType().getTypePtr(); 8048 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8049 T = CT->getElementType().getTypePtr(); 8050 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8051 T = AT->getValueType().getTypePtr(); 8052 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8053 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8054 8055 const BuiltinType *BT = cast<BuiltinType>(T); 8056 assert(BT->isInteger()); 8057 8058 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8059 } 8060 8061 /// Returns the supremum of two ranges: i.e. their conservative merge. 8062 static IntRange join(IntRange L, IntRange R) { 8063 return IntRange(std::max(L.Width, R.Width), 8064 L.NonNegative && R.NonNegative); 8065 } 8066 8067 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8068 static IntRange meet(IntRange L, IntRange R) { 8069 return IntRange(std::min(L.Width, R.Width), 8070 L.NonNegative || R.NonNegative); 8071 } 8072 }; 8073 8074 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 8075 if (value.isSigned() && value.isNegative()) 8076 return IntRange(value.getMinSignedBits(), false); 8077 8078 if (value.getBitWidth() > MaxWidth) 8079 value = value.trunc(MaxWidth); 8080 8081 // isNonNegative() just checks the sign bit without considering 8082 // signedness. 8083 return IntRange(value.getActiveBits(), true); 8084 } 8085 8086 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8087 unsigned MaxWidth) { 8088 if (result.isInt()) 8089 return GetValueRange(C, result.getInt(), MaxWidth); 8090 8091 if (result.isVector()) { 8092 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8093 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8094 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8095 R = IntRange::join(R, El); 8096 } 8097 return R; 8098 } 8099 8100 if (result.isComplexInt()) { 8101 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8102 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8103 return IntRange::join(R, I); 8104 } 8105 8106 // This can happen with lossless casts to intptr_t of "based" lvalues. 8107 // Assume it might use arbitrary bits. 8108 // FIXME: The only reason we need to pass the type in here is to get 8109 // the sign right on this one case. It would be nice if APValue 8110 // preserved this. 8111 assert(result.isLValue() || result.isAddrLabelDiff()); 8112 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8113 } 8114 8115 QualType GetExprType(const Expr *E) { 8116 QualType Ty = E->getType(); 8117 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8118 Ty = AtomicRHS->getValueType(); 8119 return Ty; 8120 } 8121 8122 /// Pseudo-evaluate the given integer expression, estimating the 8123 /// range of values it might take. 8124 /// 8125 /// \param MaxWidth - the width to which the value will be truncated 8126 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8127 E = E->IgnoreParens(); 8128 8129 // Try a full evaluation first. 8130 Expr::EvalResult result; 8131 if (E->EvaluateAsRValue(result, C)) 8132 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8133 8134 // I think we only want to look through implicit casts here; if the 8135 // user has an explicit widening cast, we should treat the value as 8136 // being of the new, wider type. 8137 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8138 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8139 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8140 8141 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8142 8143 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8144 CE->getCastKind() == CK_BooleanToSignedIntegral; 8145 8146 // Assume that non-integer casts can span the full range of the type. 8147 if (!isIntegerCast) 8148 return OutputTypeRange; 8149 8150 IntRange SubRange 8151 = GetExprRange(C, CE->getSubExpr(), 8152 std::min(MaxWidth, OutputTypeRange.Width)); 8153 8154 // Bail out if the subexpr's range is as wide as the cast type. 8155 if (SubRange.Width >= OutputTypeRange.Width) 8156 return OutputTypeRange; 8157 8158 // Otherwise, we take the smaller width, and we're non-negative if 8159 // either the output type or the subexpr is. 8160 return IntRange(SubRange.Width, 8161 SubRange.NonNegative || OutputTypeRange.NonNegative); 8162 } 8163 8164 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8165 // If we can fold the condition, just take that operand. 8166 bool CondResult; 8167 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8168 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8169 : CO->getFalseExpr(), 8170 MaxWidth); 8171 8172 // Otherwise, conservatively merge. 8173 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8174 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8175 return IntRange::join(L, R); 8176 } 8177 8178 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8179 switch (BO->getOpcode()) { 8180 8181 // Boolean-valued operations are single-bit and positive. 8182 case BO_LAnd: 8183 case BO_LOr: 8184 case BO_LT: 8185 case BO_GT: 8186 case BO_LE: 8187 case BO_GE: 8188 case BO_EQ: 8189 case BO_NE: 8190 return IntRange::forBoolType(); 8191 8192 // The type of the assignments is the type of the LHS, so the RHS 8193 // is not necessarily the same type. 8194 case BO_MulAssign: 8195 case BO_DivAssign: 8196 case BO_RemAssign: 8197 case BO_AddAssign: 8198 case BO_SubAssign: 8199 case BO_XorAssign: 8200 case BO_OrAssign: 8201 // TODO: bitfields? 8202 return IntRange::forValueOfType(C, GetExprType(E)); 8203 8204 // Simple assignments just pass through the RHS, which will have 8205 // been coerced to the LHS type. 8206 case BO_Assign: 8207 // TODO: bitfields? 8208 return GetExprRange(C, BO->getRHS(), MaxWidth); 8209 8210 // Operations with opaque sources are black-listed. 8211 case BO_PtrMemD: 8212 case BO_PtrMemI: 8213 return IntRange::forValueOfType(C, GetExprType(E)); 8214 8215 // Bitwise-and uses the *infinum* of the two source ranges. 8216 case BO_And: 8217 case BO_AndAssign: 8218 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8219 GetExprRange(C, BO->getRHS(), MaxWidth)); 8220 8221 // Left shift gets black-listed based on a judgement call. 8222 case BO_Shl: 8223 // ...except that we want to treat '1 << (blah)' as logically 8224 // positive. It's an important idiom. 8225 if (IntegerLiteral *I 8226 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8227 if (I->getValue() == 1) { 8228 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8229 return IntRange(R.Width, /*NonNegative*/ true); 8230 } 8231 } 8232 // fallthrough 8233 8234 case BO_ShlAssign: 8235 return IntRange::forValueOfType(C, GetExprType(E)); 8236 8237 // Right shift by a constant can narrow its left argument. 8238 case BO_Shr: 8239 case BO_ShrAssign: { 8240 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8241 8242 // If the shift amount is a positive constant, drop the width by 8243 // that much. 8244 llvm::APSInt shift; 8245 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8246 shift.isNonNegative()) { 8247 unsigned zext = shift.getZExtValue(); 8248 if (zext >= L.Width) 8249 L.Width = (L.NonNegative ? 0 : 1); 8250 else 8251 L.Width -= zext; 8252 } 8253 8254 return L; 8255 } 8256 8257 // Comma acts as its right operand. 8258 case BO_Comma: 8259 return GetExprRange(C, BO->getRHS(), MaxWidth); 8260 8261 // Black-list pointer subtractions. 8262 case BO_Sub: 8263 if (BO->getLHS()->getType()->isPointerType()) 8264 return IntRange::forValueOfType(C, GetExprType(E)); 8265 break; 8266 8267 // The width of a division result is mostly determined by the size 8268 // of the LHS. 8269 case BO_Div: { 8270 // Don't 'pre-truncate' the operands. 8271 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8272 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8273 8274 // If the divisor is constant, use that. 8275 llvm::APSInt divisor; 8276 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8277 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8278 if (log2 >= L.Width) 8279 L.Width = (L.NonNegative ? 0 : 1); 8280 else 8281 L.Width = std::min(L.Width - log2, MaxWidth); 8282 return L; 8283 } 8284 8285 // Otherwise, just use the LHS's width. 8286 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8287 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8288 } 8289 8290 // The result of a remainder can't be larger than the result of 8291 // either side. 8292 case BO_Rem: { 8293 // Don't 'pre-truncate' the operands. 8294 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8295 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8296 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8297 8298 IntRange meet = IntRange::meet(L, R); 8299 meet.Width = std::min(meet.Width, MaxWidth); 8300 return meet; 8301 } 8302 8303 // The default behavior is okay for these. 8304 case BO_Mul: 8305 case BO_Add: 8306 case BO_Xor: 8307 case BO_Or: 8308 break; 8309 } 8310 8311 // The default case is to treat the operation as if it were closed 8312 // on the narrowest type that encompasses both operands. 8313 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8314 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8315 return IntRange::join(L, R); 8316 } 8317 8318 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8319 switch (UO->getOpcode()) { 8320 // Boolean-valued operations are white-listed. 8321 case UO_LNot: 8322 return IntRange::forBoolType(); 8323 8324 // Operations with opaque sources are black-listed. 8325 case UO_Deref: 8326 case UO_AddrOf: // should be impossible 8327 return IntRange::forValueOfType(C, GetExprType(E)); 8328 8329 default: 8330 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8331 } 8332 } 8333 8334 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8335 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8336 8337 if (const auto *BitField = E->getSourceBitField()) 8338 return IntRange(BitField->getBitWidthValue(C), 8339 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8340 8341 return IntRange::forValueOfType(C, GetExprType(E)); 8342 } 8343 8344 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8345 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8346 } 8347 8348 /// Checks whether the given value, which currently has the given 8349 /// source semantics, has the same value when coerced through the 8350 /// target semantics. 8351 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8352 const llvm::fltSemantics &Src, 8353 const llvm::fltSemantics &Tgt) { 8354 llvm::APFloat truncated = value; 8355 8356 bool ignored; 8357 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8358 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8359 8360 return truncated.bitwiseIsEqual(value); 8361 } 8362 8363 /// Checks whether the given value, which currently has the given 8364 /// source semantics, has the same value when coerced through the 8365 /// target semantics. 8366 /// 8367 /// The value might be a vector of floats (or a complex number). 8368 bool IsSameFloatAfterCast(const APValue &value, 8369 const llvm::fltSemantics &Src, 8370 const llvm::fltSemantics &Tgt) { 8371 if (value.isFloat()) 8372 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8373 8374 if (value.isVector()) { 8375 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8376 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8377 return false; 8378 return true; 8379 } 8380 8381 assert(value.isComplexFloat()); 8382 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8383 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8384 } 8385 8386 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8387 8388 bool IsZero(Sema &S, Expr *E) { 8389 // Suppress cases where we are comparing against an enum constant. 8390 if (const DeclRefExpr *DR = 8391 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8392 if (isa<EnumConstantDecl>(DR->getDecl())) 8393 return false; 8394 8395 // Suppress cases where the '0' value is expanded from a macro. 8396 if (E->getLocStart().isMacroID()) 8397 return false; 8398 8399 llvm::APSInt Value; 8400 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 8401 } 8402 8403 bool HasEnumType(Expr *E) { 8404 // Strip off implicit integral promotions. 8405 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8406 if (ICE->getCastKind() != CK_IntegralCast && 8407 ICE->getCastKind() != CK_NoOp) 8408 break; 8409 E = ICE->getSubExpr(); 8410 } 8411 8412 return E->getType()->isEnumeralType(); 8413 } 8414 8415 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 8416 // Disable warning in template instantiations. 8417 if (S.inTemplateInstantiation()) 8418 return; 8419 8420 BinaryOperatorKind op = E->getOpcode(); 8421 if (E->isValueDependent()) 8422 return; 8423 8424 if (op == BO_LT && IsZero(S, E->getRHS())) { 8425 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8426 << "< 0" << "false" << HasEnumType(E->getLHS()) 8427 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8428 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 8429 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8430 << ">= 0" << "true" << HasEnumType(E->getLHS()) 8431 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8432 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 8433 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8434 << "0 >" << "false" << HasEnumType(E->getRHS()) 8435 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8436 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 8437 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8438 << "0 <=" << "true" << HasEnumType(E->getRHS()) 8439 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8440 } 8441 } 8442 8443 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8444 Expr *Other, const llvm::APSInt &Value, 8445 bool RhsConstant) { 8446 // Disable warning in template instantiations. 8447 if (S.inTemplateInstantiation()) 8448 return; 8449 8450 // TODO: Investigate using GetExprRange() to get tighter bounds 8451 // on the bit ranges. 8452 QualType OtherT = Other->getType(); 8453 if (const auto *AT = OtherT->getAs<AtomicType>()) 8454 OtherT = AT->getValueType(); 8455 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8456 unsigned OtherWidth = OtherRange.Width; 8457 8458 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8459 8460 // 0 values are handled later by CheckTrivialUnsignedComparison(). 8461 if ((Value == 0) && (!OtherIsBooleanType)) 8462 return; 8463 8464 BinaryOperatorKind op = E->getOpcode(); 8465 bool IsTrue = true; 8466 8467 // Used for diagnostic printout. 8468 enum { 8469 LiteralConstant = 0, 8470 CXXBoolLiteralTrue, 8471 CXXBoolLiteralFalse 8472 } LiteralOrBoolConstant = LiteralConstant; 8473 8474 if (!OtherIsBooleanType) { 8475 QualType ConstantT = Constant->getType(); 8476 QualType CommonT = E->getLHS()->getType(); 8477 8478 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8479 return; 8480 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8481 "comparison with non-integer type"); 8482 8483 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8484 bool CommonSigned = CommonT->isSignedIntegerType(); 8485 8486 bool EqualityOnly = false; 8487 8488 if (CommonSigned) { 8489 // The common type is signed, therefore no signed to unsigned conversion. 8490 if (!OtherRange.NonNegative) { 8491 // Check that the constant is representable in type OtherT. 8492 if (ConstantSigned) { 8493 if (OtherWidth >= Value.getMinSignedBits()) 8494 return; 8495 } else { // !ConstantSigned 8496 if (OtherWidth >= Value.getActiveBits() + 1) 8497 return; 8498 } 8499 } else { // !OtherSigned 8500 // Check that the constant is representable in type OtherT. 8501 // Negative values are out of range. 8502 if (ConstantSigned) { 8503 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8504 return; 8505 } else { // !ConstantSigned 8506 if (OtherWidth >= Value.getActiveBits()) 8507 return; 8508 } 8509 } 8510 } else { // !CommonSigned 8511 if (OtherRange.NonNegative) { 8512 if (OtherWidth >= Value.getActiveBits()) 8513 return; 8514 } else { // OtherSigned 8515 assert(!ConstantSigned && 8516 "Two signed types converted to unsigned types."); 8517 // Check to see if the constant is representable in OtherT. 8518 if (OtherWidth > Value.getActiveBits()) 8519 return; 8520 // Check to see if the constant is equivalent to a negative value 8521 // cast to CommonT. 8522 if (S.Context.getIntWidth(ConstantT) == 8523 S.Context.getIntWidth(CommonT) && 8524 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8525 return; 8526 // The constant value rests between values that OtherT can represent 8527 // after conversion. Relational comparison still works, but equality 8528 // comparisons will be tautological. 8529 EqualityOnly = true; 8530 } 8531 } 8532 8533 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8534 8535 if (op == BO_EQ || op == BO_NE) { 8536 IsTrue = op == BO_NE; 8537 } else if (EqualityOnly) { 8538 return; 8539 } else if (RhsConstant) { 8540 if (op == BO_GT || op == BO_GE) 8541 IsTrue = !PositiveConstant; 8542 else // op == BO_LT || op == BO_LE 8543 IsTrue = PositiveConstant; 8544 } else { 8545 if (op == BO_LT || op == BO_LE) 8546 IsTrue = !PositiveConstant; 8547 else // op == BO_GT || op == BO_GE 8548 IsTrue = PositiveConstant; 8549 } 8550 } else { 8551 // Other isKnownToHaveBooleanValue 8552 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8553 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8554 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8555 8556 static const struct LinkedConditions { 8557 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8558 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8559 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8560 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8561 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8562 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8563 8564 } TruthTable = { 8565 // Constant on LHS. | Constant on RHS. | 8566 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8567 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8568 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8569 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8570 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8571 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8572 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8573 }; 8574 8575 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8576 8577 enum ConstantValue ConstVal = Zero; 8578 if (Value.isUnsigned() || Value.isNonNegative()) { 8579 if (Value == 0) { 8580 LiteralOrBoolConstant = 8581 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8582 ConstVal = Zero; 8583 } else if (Value == 1) { 8584 LiteralOrBoolConstant = 8585 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8586 ConstVal = One; 8587 } else { 8588 LiteralOrBoolConstant = LiteralConstant; 8589 ConstVal = GT_One; 8590 } 8591 } else { 8592 ConstVal = LT_Zero; 8593 } 8594 8595 CompareBoolWithConstantResult CmpRes; 8596 8597 switch (op) { 8598 case BO_LT: 8599 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8600 break; 8601 case BO_GT: 8602 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8603 break; 8604 case BO_LE: 8605 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8606 break; 8607 case BO_GE: 8608 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8609 break; 8610 case BO_EQ: 8611 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8612 break; 8613 case BO_NE: 8614 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8615 break; 8616 default: 8617 CmpRes = Unkwn; 8618 break; 8619 } 8620 8621 if (CmpRes == AFals) { 8622 IsTrue = false; 8623 } else if (CmpRes == ATrue) { 8624 IsTrue = true; 8625 } else { 8626 return; 8627 } 8628 } 8629 8630 // If this is a comparison to an enum constant, include that 8631 // constant in the diagnostic. 8632 const EnumConstantDecl *ED = nullptr; 8633 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8634 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8635 8636 SmallString<64> PrettySourceValue; 8637 llvm::raw_svector_ostream OS(PrettySourceValue); 8638 if (ED) 8639 OS << '\'' << *ED << "' (" << Value << ")"; 8640 else 8641 OS << Value; 8642 8643 S.DiagRuntimeBehavior( 8644 E->getOperatorLoc(), E, 8645 S.PDiag(diag::warn_out_of_range_compare) 8646 << OS.str() << LiteralOrBoolConstant 8647 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8648 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8649 } 8650 8651 /// Analyze the operands of the given comparison. Implements the 8652 /// fallback case from AnalyzeComparison. 8653 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8654 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8655 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8656 } 8657 8658 /// \brief Implements -Wsign-compare. 8659 /// 8660 /// \param E the binary operator to check for warnings 8661 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8662 // The type the comparison is being performed in. 8663 QualType T = E->getLHS()->getType(); 8664 8665 // Only analyze comparison operators where both sides have been converted to 8666 // the same type. 8667 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8668 return AnalyzeImpConvsInComparison(S, E); 8669 8670 // Don't analyze value-dependent comparisons directly. 8671 if (E->isValueDependent()) 8672 return AnalyzeImpConvsInComparison(S, E); 8673 8674 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8675 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8676 8677 bool IsComparisonConstant = false; 8678 8679 // Check whether an integer constant comparison results in a value 8680 // of 'true' or 'false'. 8681 if (T->isIntegralType(S.Context)) { 8682 llvm::APSInt RHSValue; 8683 bool IsRHSIntegralLiteral = 8684 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8685 llvm::APSInt LHSValue; 8686 bool IsLHSIntegralLiteral = 8687 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8688 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8689 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8690 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8691 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8692 else 8693 IsComparisonConstant = 8694 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8695 } else if (!T->hasUnsignedIntegerRepresentation()) 8696 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8697 8698 // We don't do anything special if this isn't an unsigned integral 8699 // comparison: we're only interested in integral comparisons, and 8700 // signed comparisons only happen in cases we don't care to warn about. 8701 // 8702 // We also don't care about value-dependent expressions or expressions 8703 // whose result is a constant. 8704 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 8705 return AnalyzeImpConvsInComparison(S, E); 8706 8707 // Check to see if one of the (unmodified) operands is of different 8708 // signedness. 8709 Expr *signedOperand, *unsignedOperand; 8710 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8711 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8712 "unsigned comparison between two signed integer expressions?"); 8713 signedOperand = LHS; 8714 unsignedOperand = RHS; 8715 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8716 signedOperand = RHS; 8717 unsignedOperand = LHS; 8718 } else { 8719 CheckTrivialUnsignedComparison(S, E); 8720 return AnalyzeImpConvsInComparison(S, E); 8721 } 8722 8723 // Otherwise, calculate the effective range of the signed operand. 8724 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8725 8726 // Go ahead and analyze implicit conversions in the operands. Note 8727 // that we skip the implicit conversions on both sides. 8728 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8729 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8730 8731 // If the signed range is non-negative, -Wsign-compare won't fire, 8732 // but we should still check for comparisons which are always true 8733 // or false. 8734 if (signedRange.NonNegative) 8735 return CheckTrivialUnsignedComparison(S, E); 8736 8737 // For (in)equality comparisons, if the unsigned operand is a 8738 // constant which cannot collide with a overflowed signed operand, 8739 // then reinterpreting the signed operand as unsigned will not 8740 // change the result of the comparison. 8741 if (E->isEqualityOp()) { 8742 unsigned comparisonWidth = S.Context.getIntWidth(T); 8743 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8744 8745 // We should never be unable to prove that the unsigned operand is 8746 // non-negative. 8747 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8748 8749 if (unsignedRange.Width < comparisonWidth) 8750 return; 8751 } 8752 8753 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8754 S.PDiag(diag::warn_mixed_sign_comparison) 8755 << LHS->getType() << RHS->getType() 8756 << LHS->getSourceRange() << RHS->getSourceRange()); 8757 } 8758 8759 /// Analyzes an attempt to assign the given value to a bitfield. 8760 /// 8761 /// Returns true if there was something fishy about the attempt. 8762 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8763 SourceLocation InitLoc) { 8764 assert(Bitfield->isBitField()); 8765 if (Bitfield->isInvalidDecl()) 8766 return false; 8767 8768 // White-list bool bitfields. 8769 QualType BitfieldType = Bitfield->getType(); 8770 if (BitfieldType->isBooleanType()) 8771 return false; 8772 8773 if (BitfieldType->isEnumeralType()) { 8774 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 8775 // If the underlying enum type was not explicitly specified as an unsigned 8776 // type and the enum contain only positive values, MSVC++ will cause an 8777 // inconsistency by storing this as a signed type. 8778 if (S.getLangOpts().CPlusPlus11 && 8779 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 8780 BitfieldEnumDecl->getNumPositiveBits() > 0 && 8781 BitfieldEnumDecl->getNumNegativeBits() == 0) { 8782 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 8783 << BitfieldEnumDecl->getNameAsString(); 8784 } 8785 } 8786 8787 if (Bitfield->getType()->isBooleanType()) 8788 return false; 8789 8790 // Ignore value- or type-dependent expressions. 8791 if (Bitfield->getBitWidth()->isValueDependent() || 8792 Bitfield->getBitWidth()->isTypeDependent() || 8793 Init->isValueDependent() || 8794 Init->isTypeDependent()) 8795 return false; 8796 8797 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8798 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8799 8800 llvm::APSInt Value; 8801 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 8802 Expr::SE_AllowSideEffects)) { 8803 // The RHS is not constant. If the RHS has an enum type, make sure the 8804 // bitfield is wide enough to hold all the values of the enum without 8805 // truncation. 8806 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 8807 EnumDecl *ED = EnumTy->getDecl(); 8808 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 8809 8810 // Enum types are implicitly signed on Windows, so check if there are any 8811 // negative enumerators to see if the enum was intended to be signed or 8812 // not. 8813 bool SignedEnum = ED->getNumNegativeBits() > 0; 8814 8815 // Check for surprising sign changes when assigning enum values to a 8816 // bitfield of different signedness. If the bitfield is signed and we 8817 // have exactly the right number of bits to store this unsigned enum, 8818 // suggest changing the enum to an unsigned type. This typically happens 8819 // on Windows where unfixed enums always use an underlying type of 'int'. 8820 unsigned DiagID = 0; 8821 if (SignedEnum && !SignedBitfield) { 8822 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 8823 } else if (SignedBitfield && !SignedEnum && 8824 ED->getNumPositiveBits() == FieldWidth) { 8825 DiagID = diag::warn_signed_bitfield_enum_conversion; 8826 } 8827 8828 if (DiagID) { 8829 S.Diag(InitLoc, DiagID) << Bitfield << ED; 8830 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 8831 SourceRange TypeRange = 8832 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 8833 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 8834 << SignedEnum << TypeRange; 8835 } 8836 8837 // Compute the required bitwidth. If the enum has negative values, we need 8838 // one more bit than the normal number of positive bits to represent the 8839 // sign bit. 8840 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 8841 ED->getNumNegativeBits()) 8842 : ED->getNumPositiveBits(); 8843 8844 // Check the bitwidth. 8845 if (BitsNeeded > FieldWidth) { 8846 Expr *WidthExpr = Bitfield->getBitWidth(); 8847 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 8848 << Bitfield << ED; 8849 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 8850 << BitsNeeded << ED << WidthExpr->getSourceRange(); 8851 } 8852 } 8853 8854 return false; 8855 } 8856 8857 unsigned OriginalWidth = Value.getBitWidth(); 8858 8859 if (!Value.isSigned() || Value.isNegative()) 8860 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 8861 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 8862 OriginalWidth = Value.getMinSignedBits(); 8863 8864 if (OriginalWidth <= FieldWidth) 8865 return false; 8866 8867 // Compute the value which the bitfield will contain. 8868 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 8869 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 8870 8871 // Check whether the stored value is equal to the original value. 8872 TruncatedValue = TruncatedValue.extend(OriginalWidth); 8873 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 8874 return false; 8875 8876 // Special-case bitfields of width 1: booleans are naturally 0/1, and 8877 // therefore don't strictly fit into a signed bitfield of width 1. 8878 if (FieldWidth == 1 && Value == 1) 8879 return false; 8880 8881 std::string PrettyValue = Value.toString(10); 8882 std::string PrettyTrunc = TruncatedValue.toString(10); 8883 8884 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 8885 << PrettyValue << PrettyTrunc << OriginalInit->getType() 8886 << Init->getSourceRange(); 8887 8888 return true; 8889 } 8890 8891 /// Analyze the given simple or compound assignment for warning-worthy 8892 /// operations. 8893 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 8894 // Just recurse on the LHS. 8895 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8896 8897 // We want to recurse on the RHS as normal unless we're assigning to 8898 // a bitfield. 8899 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 8900 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 8901 E->getOperatorLoc())) { 8902 // Recurse, ignoring any implicit conversions on the RHS. 8903 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 8904 E->getOperatorLoc()); 8905 } 8906 } 8907 8908 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8909 } 8910 8911 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8912 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 8913 SourceLocation CContext, unsigned diag, 8914 bool pruneControlFlow = false) { 8915 if (pruneControlFlow) { 8916 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8917 S.PDiag(diag) 8918 << SourceType << T << E->getSourceRange() 8919 << SourceRange(CContext)); 8920 return; 8921 } 8922 S.Diag(E->getExprLoc(), diag) 8923 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 8924 } 8925 8926 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8927 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 8928 unsigned diag, bool pruneControlFlow = false) { 8929 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 8930 } 8931 8932 8933 /// Diagnose an implicit cast from a floating point value to an integer value. 8934 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 8935 8936 SourceLocation CContext) { 8937 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 8938 const bool PruneWarnings = S.inTemplateInstantiation(); 8939 8940 Expr *InnerE = E->IgnoreParenImpCasts(); 8941 // We also want to warn on, e.g., "int i = -1.234" 8942 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 8943 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 8944 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 8945 8946 const bool IsLiteral = 8947 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 8948 8949 llvm::APFloat Value(0.0); 8950 bool IsConstant = 8951 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 8952 if (!IsConstant) { 8953 return DiagnoseImpCast(S, E, T, CContext, 8954 diag::warn_impcast_float_integer, PruneWarnings); 8955 } 8956 8957 bool isExact = false; 8958 8959 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 8960 T->hasUnsignedIntegerRepresentation()); 8961 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 8962 &isExact) == llvm::APFloat::opOK && 8963 isExact) { 8964 if (IsLiteral) return; 8965 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 8966 PruneWarnings); 8967 } 8968 8969 unsigned DiagID = 0; 8970 if (IsLiteral) { 8971 // Warn on floating point literal to integer. 8972 DiagID = diag::warn_impcast_literal_float_to_integer; 8973 } else if (IntegerValue == 0) { 8974 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 8975 return DiagnoseImpCast(S, E, T, CContext, 8976 diag::warn_impcast_float_integer, PruneWarnings); 8977 } 8978 // Warn on non-zero to zero conversion. 8979 DiagID = diag::warn_impcast_float_to_integer_zero; 8980 } else { 8981 if (IntegerValue.isUnsigned()) { 8982 if (!IntegerValue.isMaxValue()) { 8983 return DiagnoseImpCast(S, E, T, CContext, 8984 diag::warn_impcast_float_integer, PruneWarnings); 8985 } 8986 } else { // IntegerValue.isSigned() 8987 if (!IntegerValue.isMaxSignedValue() && 8988 !IntegerValue.isMinSignedValue()) { 8989 return DiagnoseImpCast(S, E, T, CContext, 8990 diag::warn_impcast_float_integer, PruneWarnings); 8991 } 8992 } 8993 // Warn on evaluatable floating point expression to integer conversion. 8994 DiagID = diag::warn_impcast_float_to_integer; 8995 } 8996 8997 // FIXME: Force the precision of the source value down so we don't print 8998 // digits which are usually useless (we don't really care here if we 8999 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9000 // would automatically print the shortest representation, but it's a bit 9001 // tricky to implement. 9002 SmallString<16> PrettySourceValue; 9003 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9004 precision = (precision * 59 + 195) / 196; 9005 Value.toString(PrettySourceValue, precision); 9006 9007 SmallString<16> PrettyTargetValue; 9008 if (IsBool) 9009 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9010 else 9011 IntegerValue.toString(PrettyTargetValue); 9012 9013 if (PruneWarnings) { 9014 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9015 S.PDiag(DiagID) 9016 << E->getType() << T.getUnqualifiedType() 9017 << PrettySourceValue << PrettyTargetValue 9018 << E->getSourceRange() << SourceRange(CContext)); 9019 } else { 9020 S.Diag(E->getExprLoc(), DiagID) 9021 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9022 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9023 } 9024 } 9025 9026 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 9027 if (!Range.Width) return "0"; 9028 9029 llvm::APSInt ValueInRange = Value; 9030 ValueInRange.setIsSigned(!Range.NonNegative); 9031 ValueInRange = ValueInRange.trunc(Range.Width); 9032 return ValueInRange.toString(10); 9033 } 9034 9035 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9036 if (!isa<ImplicitCastExpr>(Ex)) 9037 return false; 9038 9039 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9040 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9041 const Type *Source = 9042 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9043 if (Target->isDependentType()) 9044 return false; 9045 9046 const BuiltinType *FloatCandidateBT = 9047 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9048 const Type *BoolCandidateType = ToBool ? Target : Source; 9049 9050 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9051 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9052 } 9053 9054 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9055 SourceLocation CC) { 9056 unsigned NumArgs = TheCall->getNumArgs(); 9057 for (unsigned i = 0; i < NumArgs; ++i) { 9058 Expr *CurrA = TheCall->getArg(i); 9059 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9060 continue; 9061 9062 bool IsSwapped = ((i > 0) && 9063 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9064 IsSwapped |= ((i < (NumArgs - 1)) && 9065 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9066 if (IsSwapped) { 9067 // Warn on this floating-point to bool conversion. 9068 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9069 CurrA->getType(), CC, 9070 diag::warn_impcast_floating_point_to_bool); 9071 } 9072 } 9073 } 9074 9075 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 9076 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9077 E->getExprLoc())) 9078 return; 9079 9080 // Don't warn on functions which have return type nullptr_t. 9081 if (isa<CallExpr>(E)) 9082 return; 9083 9084 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9085 const Expr::NullPointerConstantKind NullKind = 9086 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9087 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9088 return; 9089 9090 // Return if target type is a safe conversion. 9091 if (T->isAnyPointerType() || T->isBlockPointerType() || 9092 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9093 return; 9094 9095 SourceLocation Loc = E->getSourceRange().getBegin(); 9096 9097 // Venture through the macro stacks to get to the source of macro arguments. 9098 // The new location is a better location than the complete location that was 9099 // passed in. 9100 while (S.SourceMgr.isMacroArgExpansion(Loc)) 9101 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 9102 9103 while (S.SourceMgr.isMacroArgExpansion(CC)) 9104 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 9105 9106 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9107 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9108 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9109 Loc, S.SourceMgr, S.getLangOpts()); 9110 if (MacroName == "NULL") 9111 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 9112 } 9113 9114 // Only warn if the null and context location are in the same macro expansion. 9115 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9116 return; 9117 9118 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9119 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 9120 << FixItHint::CreateReplacement(Loc, 9121 S.getFixItZeroLiteralForType(T, Loc)); 9122 } 9123 9124 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9125 ObjCArrayLiteral *ArrayLiteral); 9126 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9127 ObjCDictionaryLiteral *DictionaryLiteral); 9128 9129 /// Check a single element within a collection literal against the 9130 /// target element type. 9131 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 9132 Expr *Element, unsigned ElementKind) { 9133 // Skip a bitcast to 'id' or qualified 'id'. 9134 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9135 if (ICE->getCastKind() == CK_BitCast && 9136 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9137 Element = ICE->getSubExpr(); 9138 } 9139 9140 QualType ElementType = Element->getType(); 9141 ExprResult ElementResult(Element); 9142 if (ElementType->getAs<ObjCObjectPointerType>() && 9143 S.CheckSingleAssignmentConstraints(TargetElementType, 9144 ElementResult, 9145 false, false) 9146 != Sema::Compatible) { 9147 S.Diag(Element->getLocStart(), 9148 diag::warn_objc_collection_literal_element) 9149 << ElementType << ElementKind << TargetElementType 9150 << Element->getSourceRange(); 9151 } 9152 9153 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9154 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9155 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9156 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9157 } 9158 9159 /// Check an Objective-C array literal being converted to the given 9160 /// target type. 9161 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9162 ObjCArrayLiteral *ArrayLiteral) { 9163 if (!S.NSArrayDecl) 9164 return; 9165 9166 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9167 if (!TargetObjCPtr) 9168 return; 9169 9170 if (TargetObjCPtr->isUnspecialized() || 9171 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9172 != S.NSArrayDecl->getCanonicalDecl()) 9173 return; 9174 9175 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9176 if (TypeArgs.size() != 1) 9177 return; 9178 9179 QualType TargetElementType = TypeArgs[0]; 9180 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9181 checkObjCCollectionLiteralElement(S, TargetElementType, 9182 ArrayLiteral->getElement(I), 9183 0); 9184 } 9185 } 9186 9187 /// Check an Objective-C dictionary literal being converted to the given 9188 /// target type. 9189 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9190 ObjCDictionaryLiteral *DictionaryLiteral) { 9191 if (!S.NSDictionaryDecl) 9192 return; 9193 9194 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9195 if (!TargetObjCPtr) 9196 return; 9197 9198 if (TargetObjCPtr->isUnspecialized() || 9199 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9200 != S.NSDictionaryDecl->getCanonicalDecl()) 9201 return; 9202 9203 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9204 if (TypeArgs.size() != 2) 9205 return; 9206 9207 QualType TargetKeyType = TypeArgs[0]; 9208 QualType TargetObjectType = TypeArgs[1]; 9209 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9210 auto Element = DictionaryLiteral->getKeyValueElement(I); 9211 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9212 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9213 } 9214 } 9215 9216 // Helper function to filter out cases for constant width constant conversion. 9217 // Don't warn on char array initialization or for non-decimal values. 9218 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9219 SourceLocation CC) { 9220 // If initializing from a constant, and the constant starts with '0', 9221 // then it is a binary, octal, or hexadecimal. Allow these constants 9222 // to fill all the bits, even if there is a sign change. 9223 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9224 const char FirstLiteralCharacter = 9225 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9226 if (FirstLiteralCharacter == '0') 9227 return false; 9228 } 9229 9230 // If the CC location points to a '{', and the type is char, then assume 9231 // assume it is an array initialization. 9232 if (CC.isValid() && T->isCharType()) { 9233 const char FirstContextCharacter = 9234 S.getSourceManager().getCharacterData(CC)[0]; 9235 if (FirstContextCharacter == '{') 9236 return false; 9237 } 9238 9239 return true; 9240 } 9241 9242 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 9243 SourceLocation CC, bool *ICContext = nullptr) { 9244 if (E->isTypeDependent() || E->isValueDependent()) return; 9245 9246 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9247 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9248 if (Source == Target) return; 9249 if (Target->isDependentType()) return; 9250 9251 // If the conversion context location is invalid don't complain. We also 9252 // don't want to emit a warning if the issue occurs from the expansion of 9253 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9254 // delay this check as long as possible. Once we detect we are in that 9255 // scenario, we just return. 9256 if (CC.isInvalid()) 9257 return; 9258 9259 // Diagnose implicit casts to bool. 9260 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9261 if (isa<StringLiteral>(E)) 9262 // Warn on string literal to bool. Checks for string literals in logical 9263 // and expressions, for instance, assert(0 && "error here"), are 9264 // prevented by a check in AnalyzeImplicitConversions(). 9265 return DiagnoseImpCast(S, E, T, CC, 9266 diag::warn_impcast_string_literal_to_bool); 9267 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9268 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9269 // This covers the literal expressions that evaluate to Objective-C 9270 // objects. 9271 return DiagnoseImpCast(S, E, T, CC, 9272 diag::warn_impcast_objective_c_literal_to_bool); 9273 } 9274 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9275 // Warn on pointer to bool conversion that is always true. 9276 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9277 SourceRange(CC)); 9278 } 9279 } 9280 9281 // Check implicit casts from Objective-C collection literals to specialized 9282 // collection types, e.g., NSArray<NSString *> *. 9283 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9284 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9285 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9286 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9287 9288 // Strip vector types. 9289 if (isa<VectorType>(Source)) { 9290 if (!isa<VectorType>(Target)) { 9291 if (S.SourceMgr.isInSystemMacro(CC)) 9292 return; 9293 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9294 } 9295 9296 // If the vector cast is cast between two vectors of the same size, it is 9297 // a bitcast, not a conversion. 9298 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9299 return; 9300 9301 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9302 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9303 } 9304 if (auto VecTy = dyn_cast<VectorType>(Target)) 9305 Target = VecTy->getElementType().getTypePtr(); 9306 9307 // Strip complex types. 9308 if (isa<ComplexType>(Source)) { 9309 if (!isa<ComplexType>(Target)) { 9310 if (S.SourceMgr.isInSystemMacro(CC)) 9311 return; 9312 9313 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 9314 } 9315 9316 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9317 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9318 } 9319 9320 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9321 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9322 9323 // If the source is floating point... 9324 if (SourceBT && SourceBT->isFloatingPoint()) { 9325 // ...and the target is floating point... 9326 if (TargetBT && TargetBT->isFloatingPoint()) { 9327 // ...then warn if we're dropping FP rank. 9328 9329 // Builtin FP kinds are ordered by increasing FP rank. 9330 if (SourceBT->getKind() > TargetBT->getKind()) { 9331 // Don't warn about float constants that are precisely 9332 // representable in the target type. 9333 Expr::EvalResult result; 9334 if (E->EvaluateAsRValue(result, S.Context)) { 9335 // Value might be a float, a float vector, or a float complex. 9336 if (IsSameFloatAfterCast(result.Val, 9337 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9338 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9339 return; 9340 } 9341 9342 if (S.SourceMgr.isInSystemMacro(CC)) 9343 return; 9344 9345 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9346 } 9347 // ... or possibly if we're increasing rank, too 9348 else if (TargetBT->getKind() > SourceBT->getKind()) { 9349 if (S.SourceMgr.isInSystemMacro(CC)) 9350 return; 9351 9352 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9353 } 9354 return; 9355 } 9356 9357 // If the target is integral, always warn. 9358 if (TargetBT && TargetBT->isInteger()) { 9359 if (S.SourceMgr.isInSystemMacro(CC)) 9360 return; 9361 9362 DiagnoseFloatingImpCast(S, E, T, CC); 9363 } 9364 9365 // Detect the case where a call result is converted from floating-point to 9366 // to bool, and the final argument to the call is converted from bool, to 9367 // discover this typo: 9368 // 9369 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9370 // 9371 // FIXME: This is an incredibly special case; is there some more general 9372 // way to detect this class of misplaced-parentheses bug? 9373 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9374 // Check last argument of function call to see if it is an 9375 // implicit cast from a type matching the type the result 9376 // is being cast to. 9377 CallExpr *CEx = cast<CallExpr>(E); 9378 if (unsigned NumArgs = CEx->getNumArgs()) { 9379 Expr *LastA = CEx->getArg(NumArgs - 1); 9380 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9381 if (isa<ImplicitCastExpr>(LastA) && 9382 InnerE->getType()->isBooleanType()) { 9383 // Warn on this floating-point to bool conversion 9384 DiagnoseImpCast(S, E, T, CC, 9385 diag::warn_impcast_floating_point_to_bool); 9386 } 9387 } 9388 } 9389 return; 9390 } 9391 9392 DiagnoseNullConversion(S, E, T, CC); 9393 9394 S.DiscardMisalignedMemberAddress(Target, E); 9395 9396 if (!Source->isIntegerType() || !Target->isIntegerType()) 9397 return; 9398 9399 // TODO: remove this early return once the false positives for constant->bool 9400 // in templates, macros, etc, are reduced or removed. 9401 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9402 return; 9403 9404 IntRange SourceRange = GetExprRange(S.Context, E); 9405 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9406 9407 if (SourceRange.Width > TargetRange.Width) { 9408 // If the source is a constant, use a default-on diagnostic. 9409 // TODO: this should happen for bitfield stores, too. 9410 llvm::APSInt Value(32); 9411 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9412 if (S.SourceMgr.isInSystemMacro(CC)) 9413 return; 9414 9415 std::string PrettySourceValue = Value.toString(10); 9416 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9417 9418 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9419 S.PDiag(diag::warn_impcast_integer_precision_constant) 9420 << PrettySourceValue << PrettyTargetValue 9421 << E->getType() << T << E->getSourceRange() 9422 << clang::SourceRange(CC)); 9423 return; 9424 } 9425 9426 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9427 if (S.SourceMgr.isInSystemMacro(CC)) 9428 return; 9429 9430 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9431 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9432 /* pruneControlFlow */ true); 9433 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9434 } 9435 9436 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9437 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9438 // Warn when doing a signed to signed conversion, warn if the positive 9439 // source value is exactly the width of the target type, which will 9440 // cause a negative value to be stored. 9441 9442 llvm::APSInt Value; 9443 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9444 !S.SourceMgr.isInSystemMacro(CC)) { 9445 if (isSameWidthConstantConversion(S, E, T, CC)) { 9446 std::string PrettySourceValue = Value.toString(10); 9447 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9448 9449 S.DiagRuntimeBehavior( 9450 E->getExprLoc(), E, 9451 S.PDiag(diag::warn_impcast_integer_precision_constant) 9452 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9453 << E->getSourceRange() << clang::SourceRange(CC)); 9454 return; 9455 } 9456 } 9457 9458 // Fall through for non-constants to give a sign conversion warning. 9459 } 9460 9461 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9462 (!TargetRange.NonNegative && SourceRange.NonNegative && 9463 SourceRange.Width == TargetRange.Width)) { 9464 if (S.SourceMgr.isInSystemMacro(CC)) 9465 return; 9466 9467 unsigned DiagID = diag::warn_impcast_integer_sign; 9468 9469 // Traditionally, gcc has warned about this under -Wsign-compare. 9470 // We also want to warn about it in -Wconversion. 9471 // So if -Wconversion is off, use a completely identical diagnostic 9472 // in the sign-compare group. 9473 // The conditional-checking code will 9474 if (ICContext) { 9475 DiagID = diag::warn_impcast_integer_sign_conditional; 9476 *ICContext = true; 9477 } 9478 9479 return DiagnoseImpCast(S, E, T, CC, DiagID); 9480 } 9481 9482 // Diagnose conversions between different enumeration types. 9483 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9484 // type, to give us better diagnostics. 9485 QualType SourceType = E->getType(); 9486 if (!S.getLangOpts().CPlusPlus) { 9487 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9488 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9489 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9490 SourceType = S.Context.getTypeDeclType(Enum); 9491 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9492 } 9493 } 9494 9495 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9496 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9497 if (SourceEnum->getDecl()->hasNameForLinkage() && 9498 TargetEnum->getDecl()->hasNameForLinkage() && 9499 SourceEnum != TargetEnum) { 9500 if (S.SourceMgr.isInSystemMacro(CC)) 9501 return; 9502 9503 return DiagnoseImpCast(S, E, SourceType, T, CC, 9504 diag::warn_impcast_different_enum_types); 9505 } 9506 } 9507 9508 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9509 SourceLocation CC, QualType T); 9510 9511 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9512 SourceLocation CC, bool &ICContext) { 9513 E = E->IgnoreParenImpCasts(); 9514 9515 if (isa<ConditionalOperator>(E)) 9516 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9517 9518 AnalyzeImplicitConversions(S, E, CC); 9519 if (E->getType() != T) 9520 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9521 } 9522 9523 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9524 SourceLocation CC, QualType T) { 9525 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9526 9527 bool Suspicious = false; 9528 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9529 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9530 9531 // If -Wconversion would have warned about either of the candidates 9532 // for a signedness conversion to the context type... 9533 if (!Suspicious) return; 9534 9535 // ...but it's currently ignored... 9536 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9537 return; 9538 9539 // ...then check whether it would have warned about either of the 9540 // candidates for a signedness conversion to the condition type. 9541 if (E->getType() == T) return; 9542 9543 Suspicious = false; 9544 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9545 E->getType(), CC, &Suspicious); 9546 if (!Suspicious) 9547 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9548 E->getType(), CC, &Suspicious); 9549 } 9550 9551 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9552 /// Input argument E is a logical expression. 9553 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9554 if (S.getLangOpts().Bool) 9555 return; 9556 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9557 } 9558 9559 /// AnalyzeImplicitConversions - Find and report any interesting 9560 /// implicit conversions in the given expression. There are a couple 9561 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9562 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9563 QualType T = OrigE->getType(); 9564 Expr *E = OrigE->IgnoreParenImpCasts(); 9565 9566 if (E->isTypeDependent() || E->isValueDependent()) 9567 return; 9568 9569 // For conditional operators, we analyze the arguments as if they 9570 // were being fed directly into the output. 9571 if (isa<ConditionalOperator>(E)) { 9572 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9573 CheckConditionalOperator(S, CO, CC, T); 9574 return; 9575 } 9576 9577 // Check implicit argument conversions for function calls. 9578 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9579 CheckImplicitArgumentConversions(S, Call, CC); 9580 9581 // Go ahead and check any implicit conversions we might have skipped. 9582 // The non-canonical typecheck is just an optimization; 9583 // CheckImplicitConversion will filter out dead implicit conversions. 9584 if (E->getType() != T) 9585 CheckImplicitConversion(S, E, T, CC); 9586 9587 // Now continue drilling into this expression. 9588 9589 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9590 // The bound subexpressions in a PseudoObjectExpr are not reachable 9591 // as transitive children. 9592 // FIXME: Use a more uniform representation for this. 9593 for (auto *SE : POE->semantics()) 9594 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9595 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9596 } 9597 9598 // Skip past explicit casts. 9599 if (isa<ExplicitCastExpr>(E)) { 9600 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9601 return AnalyzeImplicitConversions(S, E, CC); 9602 } 9603 9604 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9605 // Do a somewhat different check with comparison operators. 9606 if (BO->isComparisonOp()) 9607 return AnalyzeComparison(S, BO); 9608 9609 // And with simple assignments. 9610 if (BO->getOpcode() == BO_Assign) 9611 return AnalyzeAssignment(S, BO); 9612 } 9613 9614 // These break the otherwise-useful invariant below. Fortunately, 9615 // we don't really need to recurse into them, because any internal 9616 // expressions should have been analyzed already when they were 9617 // built into statements. 9618 if (isa<StmtExpr>(E)) return; 9619 9620 // Don't descend into unevaluated contexts. 9621 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9622 9623 // Now just recurse over the expression's children. 9624 CC = E->getExprLoc(); 9625 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9626 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9627 for (Stmt *SubStmt : E->children()) { 9628 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9629 if (!ChildExpr) 9630 continue; 9631 9632 if (IsLogicalAndOperator && 9633 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9634 // Ignore checking string literals that are in logical and operators. 9635 // This is a common pattern for asserts. 9636 continue; 9637 AnalyzeImplicitConversions(S, ChildExpr, CC); 9638 } 9639 9640 if (BO && BO->isLogicalOp()) { 9641 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9642 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9643 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9644 9645 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9646 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9647 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9648 } 9649 9650 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9651 if (U->getOpcode() == UO_LNot) 9652 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9653 } 9654 9655 } // end anonymous namespace 9656 9657 /// Diagnose integer type and any valid implicit convertion to it. 9658 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 9659 // Taking into account implicit conversions, 9660 // allow any integer. 9661 if (!E->getType()->isIntegerType()) { 9662 S.Diag(E->getLocStart(), 9663 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9664 return true; 9665 } 9666 // Potentially emit standard warnings for implicit conversions if enabled 9667 // using -Wconversion. 9668 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 9669 return false; 9670 } 9671 9672 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9673 // Returns true when emitting a warning about taking the address of a reference. 9674 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9675 const PartialDiagnostic &PD) { 9676 E = E->IgnoreParenImpCasts(); 9677 9678 const FunctionDecl *FD = nullptr; 9679 9680 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9681 if (!DRE->getDecl()->getType()->isReferenceType()) 9682 return false; 9683 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9684 if (!M->getMemberDecl()->getType()->isReferenceType()) 9685 return false; 9686 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9687 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9688 return false; 9689 FD = Call->getDirectCallee(); 9690 } else { 9691 return false; 9692 } 9693 9694 SemaRef.Diag(E->getExprLoc(), PD); 9695 9696 // If possible, point to location of function. 9697 if (FD) { 9698 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9699 } 9700 9701 return true; 9702 } 9703 9704 // Returns true if the SourceLocation is expanded from any macro body. 9705 // Returns false if the SourceLocation is invalid, is from not in a macro 9706 // expansion, or is from expanded from a top-level macro argument. 9707 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9708 if (Loc.isInvalid()) 9709 return false; 9710 9711 while (Loc.isMacroID()) { 9712 if (SM.isMacroBodyExpansion(Loc)) 9713 return true; 9714 Loc = SM.getImmediateMacroCallerLoc(Loc); 9715 } 9716 9717 return false; 9718 } 9719 9720 /// \brief Diagnose pointers that are always non-null. 9721 /// \param E the expression containing the pointer 9722 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9723 /// compared to a null pointer 9724 /// \param IsEqual True when the comparison is equal to a null pointer 9725 /// \param Range Extra SourceRange to highlight in the diagnostic 9726 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9727 Expr::NullPointerConstantKind NullKind, 9728 bool IsEqual, SourceRange Range) { 9729 if (!E) 9730 return; 9731 9732 // Don't warn inside macros. 9733 if (E->getExprLoc().isMacroID()) { 9734 const SourceManager &SM = getSourceManager(); 9735 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9736 IsInAnyMacroBody(SM, Range.getBegin())) 9737 return; 9738 } 9739 E = E->IgnoreImpCasts(); 9740 9741 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9742 9743 if (isa<CXXThisExpr>(E)) { 9744 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9745 : diag::warn_this_bool_conversion; 9746 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9747 return; 9748 } 9749 9750 bool IsAddressOf = false; 9751 9752 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9753 if (UO->getOpcode() != UO_AddrOf) 9754 return; 9755 IsAddressOf = true; 9756 E = UO->getSubExpr(); 9757 } 9758 9759 if (IsAddressOf) { 9760 unsigned DiagID = IsCompare 9761 ? diag::warn_address_of_reference_null_compare 9762 : diag::warn_address_of_reference_bool_conversion; 9763 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 9764 << IsEqual; 9765 if (CheckForReference(*this, E, PD)) { 9766 return; 9767 } 9768 } 9769 9770 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 9771 bool IsParam = isa<NonNullAttr>(NonnullAttr); 9772 std::string Str; 9773 llvm::raw_string_ostream S(Str); 9774 E->printPretty(S, nullptr, getPrintingPolicy()); 9775 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 9776 : diag::warn_cast_nonnull_to_bool; 9777 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 9778 << E->getSourceRange() << Range << IsEqual; 9779 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 9780 }; 9781 9782 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 9783 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 9784 if (auto *Callee = Call->getDirectCallee()) { 9785 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 9786 ComplainAboutNonnullParamOrCall(A); 9787 return; 9788 } 9789 } 9790 } 9791 9792 // Expect to find a single Decl. Skip anything more complicated. 9793 ValueDecl *D = nullptr; 9794 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 9795 D = R->getDecl(); 9796 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9797 D = M->getMemberDecl(); 9798 } 9799 9800 // Weak Decls can be null. 9801 if (!D || D->isWeak()) 9802 return; 9803 9804 // Check for parameter decl with nonnull attribute 9805 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 9806 if (getCurFunction() && 9807 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 9808 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 9809 ComplainAboutNonnullParamOrCall(A); 9810 return; 9811 } 9812 9813 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 9814 auto ParamIter = llvm::find(FD->parameters(), PV); 9815 assert(ParamIter != FD->param_end()); 9816 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 9817 9818 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 9819 if (!NonNull->args_size()) { 9820 ComplainAboutNonnullParamOrCall(NonNull); 9821 return; 9822 } 9823 9824 for (unsigned ArgNo : NonNull->args()) { 9825 if (ArgNo == ParamNo) { 9826 ComplainAboutNonnullParamOrCall(NonNull); 9827 return; 9828 } 9829 } 9830 } 9831 } 9832 } 9833 } 9834 9835 QualType T = D->getType(); 9836 const bool IsArray = T->isArrayType(); 9837 const bool IsFunction = T->isFunctionType(); 9838 9839 // Address of function is used to silence the function warning. 9840 if (IsAddressOf && IsFunction) { 9841 return; 9842 } 9843 9844 // Found nothing. 9845 if (!IsAddressOf && !IsFunction && !IsArray) 9846 return; 9847 9848 // Pretty print the expression for the diagnostic. 9849 std::string Str; 9850 llvm::raw_string_ostream S(Str); 9851 E->printPretty(S, nullptr, getPrintingPolicy()); 9852 9853 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 9854 : diag::warn_impcast_pointer_to_bool; 9855 enum { 9856 AddressOf, 9857 FunctionPointer, 9858 ArrayPointer 9859 } DiagType; 9860 if (IsAddressOf) 9861 DiagType = AddressOf; 9862 else if (IsFunction) 9863 DiagType = FunctionPointer; 9864 else if (IsArray) 9865 DiagType = ArrayPointer; 9866 else 9867 llvm_unreachable("Could not determine diagnostic."); 9868 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 9869 << Range << IsEqual; 9870 9871 if (!IsFunction) 9872 return; 9873 9874 // Suggest '&' to silence the function warning. 9875 Diag(E->getExprLoc(), diag::note_function_warning_silence) 9876 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 9877 9878 // Check to see if '()' fixit should be emitted. 9879 QualType ReturnType; 9880 UnresolvedSet<4> NonTemplateOverloads; 9881 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 9882 if (ReturnType.isNull()) 9883 return; 9884 9885 if (IsCompare) { 9886 // There are two cases here. If there is null constant, the only suggest 9887 // for a pointer return type. If the null is 0, then suggest if the return 9888 // type is a pointer or an integer type. 9889 if (!ReturnType->isPointerType()) { 9890 if (NullKind == Expr::NPCK_ZeroExpression || 9891 NullKind == Expr::NPCK_ZeroLiteral) { 9892 if (!ReturnType->isIntegerType()) 9893 return; 9894 } else { 9895 return; 9896 } 9897 } 9898 } else { // !IsCompare 9899 // For function to bool, only suggest if the function pointer has bool 9900 // return type. 9901 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 9902 return; 9903 } 9904 Diag(E->getExprLoc(), diag::note_function_to_function_call) 9905 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 9906 } 9907 9908 /// Diagnoses "dangerous" implicit conversions within the given 9909 /// expression (which is a full expression). Implements -Wconversion 9910 /// and -Wsign-compare. 9911 /// 9912 /// \param CC the "context" location of the implicit conversion, i.e. 9913 /// the most location of the syntactic entity requiring the implicit 9914 /// conversion 9915 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 9916 // Don't diagnose in unevaluated contexts. 9917 if (isUnevaluatedContext()) 9918 return; 9919 9920 // Don't diagnose for value- or type-dependent expressions. 9921 if (E->isTypeDependent() || E->isValueDependent()) 9922 return; 9923 9924 // Check for array bounds violations in cases where the check isn't triggered 9925 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 9926 // ArraySubscriptExpr is on the RHS of a variable initialization. 9927 CheckArrayAccess(E); 9928 9929 // This is not the right CC for (e.g.) a variable initialization. 9930 AnalyzeImplicitConversions(*this, E, CC); 9931 } 9932 9933 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9934 /// Input argument E is a logical expression. 9935 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 9936 ::CheckBoolLikeConversion(*this, E, CC); 9937 } 9938 9939 /// Diagnose when expression is an integer constant expression and its evaluation 9940 /// results in integer overflow 9941 void Sema::CheckForIntOverflow (Expr *E) { 9942 // Use a work list to deal with nested struct initializers. 9943 SmallVector<Expr *, 2> Exprs(1, E); 9944 9945 do { 9946 Expr *E = Exprs.pop_back_val(); 9947 9948 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 9949 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 9950 continue; 9951 } 9952 9953 if (auto InitList = dyn_cast<InitListExpr>(E)) 9954 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 9955 9956 if (isa<ObjCBoxedExpr>(E)) 9957 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 9958 } while (!Exprs.empty()); 9959 } 9960 9961 namespace { 9962 /// \brief Visitor for expressions which looks for unsequenced operations on the 9963 /// same object. 9964 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 9965 typedef EvaluatedExprVisitor<SequenceChecker> Base; 9966 9967 /// \brief A tree of sequenced regions within an expression. Two regions are 9968 /// unsequenced if one is an ancestor or a descendent of the other. When we 9969 /// finish processing an expression with sequencing, such as a comma 9970 /// expression, we fold its tree nodes into its parent, since they are 9971 /// unsequenced with respect to nodes we will visit later. 9972 class SequenceTree { 9973 struct Value { 9974 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 9975 unsigned Parent : 31; 9976 unsigned Merged : 1; 9977 }; 9978 SmallVector<Value, 8> Values; 9979 9980 public: 9981 /// \brief A region within an expression which may be sequenced with respect 9982 /// to some other region. 9983 class Seq { 9984 explicit Seq(unsigned N) : Index(N) {} 9985 unsigned Index; 9986 friend class SequenceTree; 9987 public: 9988 Seq() : Index(0) {} 9989 }; 9990 9991 SequenceTree() { Values.push_back(Value(0)); } 9992 Seq root() const { return Seq(0); } 9993 9994 /// \brief Create a new sequence of operations, which is an unsequenced 9995 /// subset of \p Parent. This sequence of operations is sequenced with 9996 /// respect to other children of \p Parent. 9997 Seq allocate(Seq Parent) { 9998 Values.push_back(Value(Parent.Index)); 9999 return Seq(Values.size() - 1); 10000 } 10001 10002 /// \brief Merge a sequence of operations into its parent. 10003 void merge(Seq S) { 10004 Values[S.Index].Merged = true; 10005 } 10006 10007 /// \brief Determine whether two operations are unsequenced. This operation 10008 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10009 /// should have been merged into its parent as appropriate. 10010 bool isUnsequenced(Seq Cur, Seq Old) { 10011 unsigned C = representative(Cur.Index); 10012 unsigned Target = representative(Old.Index); 10013 while (C >= Target) { 10014 if (C == Target) 10015 return true; 10016 C = Values[C].Parent; 10017 } 10018 return false; 10019 } 10020 10021 private: 10022 /// \brief Pick a representative for a sequence. 10023 unsigned representative(unsigned K) { 10024 if (Values[K].Merged) 10025 // Perform path compression as we go. 10026 return Values[K].Parent = representative(Values[K].Parent); 10027 return K; 10028 } 10029 }; 10030 10031 /// An object for which we can track unsequenced uses. 10032 typedef NamedDecl *Object; 10033 10034 /// Different flavors of object usage which we track. We only track the 10035 /// least-sequenced usage of each kind. 10036 enum UsageKind { 10037 /// A read of an object. Multiple unsequenced reads are OK. 10038 UK_Use, 10039 /// A modification of an object which is sequenced before the value 10040 /// computation of the expression, such as ++n in C++. 10041 UK_ModAsValue, 10042 /// A modification of an object which is not sequenced before the value 10043 /// computation of the expression, such as n++. 10044 UK_ModAsSideEffect, 10045 10046 UK_Count = UK_ModAsSideEffect + 1 10047 }; 10048 10049 struct Usage { 10050 Usage() : Use(nullptr), Seq() {} 10051 Expr *Use; 10052 SequenceTree::Seq Seq; 10053 }; 10054 10055 struct UsageInfo { 10056 UsageInfo() : Diagnosed(false) {} 10057 Usage Uses[UK_Count]; 10058 /// Have we issued a diagnostic for this variable already? 10059 bool Diagnosed; 10060 }; 10061 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 10062 10063 Sema &SemaRef; 10064 /// Sequenced regions within the expression. 10065 SequenceTree Tree; 10066 /// Declaration modifications and references which we have seen. 10067 UsageInfoMap UsageMap; 10068 /// The region we are currently within. 10069 SequenceTree::Seq Region; 10070 /// Filled in with declarations which were modified as a side-effect 10071 /// (that is, post-increment operations). 10072 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 10073 /// Expressions to check later. We defer checking these to reduce 10074 /// stack usage. 10075 SmallVectorImpl<Expr *> &WorkList; 10076 10077 /// RAII object wrapping the visitation of a sequenced subexpression of an 10078 /// expression. At the end of this process, the side-effects of the evaluation 10079 /// become sequenced with respect to the value computation of the result, so 10080 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10081 /// UK_ModAsValue. 10082 struct SequencedSubexpression { 10083 SequencedSubexpression(SequenceChecker &Self) 10084 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 10085 Self.ModAsSideEffect = &ModAsSideEffect; 10086 } 10087 ~SequencedSubexpression() { 10088 for (auto &M : llvm::reverse(ModAsSideEffect)) { 10089 UsageInfo &U = Self.UsageMap[M.first]; 10090 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 10091 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 10092 SideEffectUsage = M.second; 10093 } 10094 Self.ModAsSideEffect = OldModAsSideEffect; 10095 } 10096 10097 SequenceChecker &Self; 10098 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 10099 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 10100 }; 10101 10102 /// RAII object wrapping the visitation of a subexpression which we might 10103 /// choose to evaluate as a constant. If any subexpression is evaluated and 10104 /// found to be non-constant, this allows us to suppress the evaluation of 10105 /// the outer expression. 10106 class EvaluationTracker { 10107 public: 10108 EvaluationTracker(SequenceChecker &Self) 10109 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 10110 Self.EvalTracker = this; 10111 } 10112 ~EvaluationTracker() { 10113 Self.EvalTracker = Prev; 10114 if (Prev) 10115 Prev->EvalOK &= EvalOK; 10116 } 10117 10118 bool evaluate(const Expr *E, bool &Result) { 10119 if (!EvalOK || E->isValueDependent()) 10120 return false; 10121 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 10122 return EvalOK; 10123 } 10124 10125 private: 10126 SequenceChecker &Self; 10127 EvaluationTracker *Prev; 10128 bool EvalOK; 10129 } *EvalTracker; 10130 10131 /// \brief Find the object which is produced by the specified expression, 10132 /// if any. 10133 Object getObject(Expr *E, bool Mod) const { 10134 E = E->IgnoreParenCasts(); 10135 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10136 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 10137 return getObject(UO->getSubExpr(), Mod); 10138 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10139 if (BO->getOpcode() == BO_Comma) 10140 return getObject(BO->getRHS(), Mod); 10141 if (Mod && BO->isAssignmentOp()) 10142 return getObject(BO->getLHS(), Mod); 10143 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10144 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 10145 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 10146 return ME->getMemberDecl(); 10147 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10148 // FIXME: If this is a reference, map through to its value. 10149 return DRE->getDecl(); 10150 return nullptr; 10151 } 10152 10153 /// \brief Note that an object was modified or used by an expression. 10154 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 10155 Usage &U = UI.Uses[UK]; 10156 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 10157 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 10158 ModAsSideEffect->push_back(std::make_pair(O, U)); 10159 U.Use = Ref; 10160 U.Seq = Region; 10161 } 10162 } 10163 /// \brief Check whether a modification or use conflicts with a prior usage. 10164 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 10165 bool IsModMod) { 10166 if (UI.Diagnosed) 10167 return; 10168 10169 const Usage &U = UI.Uses[OtherKind]; 10170 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 10171 return; 10172 10173 Expr *Mod = U.Use; 10174 Expr *ModOrUse = Ref; 10175 if (OtherKind == UK_Use) 10176 std::swap(Mod, ModOrUse); 10177 10178 SemaRef.Diag(Mod->getExprLoc(), 10179 IsModMod ? diag::warn_unsequenced_mod_mod 10180 : diag::warn_unsequenced_mod_use) 10181 << O << SourceRange(ModOrUse->getExprLoc()); 10182 UI.Diagnosed = true; 10183 } 10184 10185 void notePreUse(Object O, Expr *Use) { 10186 UsageInfo &U = UsageMap[O]; 10187 // Uses conflict with other modifications. 10188 checkUsage(O, U, Use, UK_ModAsValue, false); 10189 } 10190 void notePostUse(Object O, Expr *Use) { 10191 UsageInfo &U = UsageMap[O]; 10192 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 10193 addUsage(U, O, Use, UK_Use); 10194 } 10195 10196 void notePreMod(Object O, Expr *Mod) { 10197 UsageInfo &U = UsageMap[O]; 10198 // Modifications conflict with other modifications and with uses. 10199 checkUsage(O, U, Mod, UK_ModAsValue, true); 10200 checkUsage(O, U, Mod, UK_Use, false); 10201 } 10202 void notePostMod(Object O, Expr *Use, UsageKind UK) { 10203 UsageInfo &U = UsageMap[O]; 10204 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 10205 addUsage(U, O, Use, UK); 10206 } 10207 10208 public: 10209 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 10210 : Base(S.Context), SemaRef(S), Region(Tree.root()), 10211 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 10212 Visit(E); 10213 } 10214 10215 void VisitStmt(Stmt *S) { 10216 // Skip all statements which aren't expressions for now. 10217 } 10218 10219 void VisitExpr(Expr *E) { 10220 // By default, just recurse to evaluated subexpressions. 10221 Base::VisitStmt(E); 10222 } 10223 10224 void VisitCastExpr(CastExpr *E) { 10225 Object O = Object(); 10226 if (E->getCastKind() == CK_LValueToRValue) 10227 O = getObject(E->getSubExpr(), false); 10228 10229 if (O) 10230 notePreUse(O, E); 10231 VisitExpr(E); 10232 if (O) 10233 notePostUse(O, E); 10234 } 10235 10236 void VisitBinComma(BinaryOperator *BO) { 10237 // C++11 [expr.comma]p1: 10238 // Every value computation and side effect associated with the left 10239 // expression is sequenced before every value computation and side 10240 // effect associated with the right expression. 10241 SequenceTree::Seq LHS = Tree.allocate(Region); 10242 SequenceTree::Seq RHS = Tree.allocate(Region); 10243 SequenceTree::Seq OldRegion = Region; 10244 10245 { 10246 SequencedSubexpression SeqLHS(*this); 10247 Region = LHS; 10248 Visit(BO->getLHS()); 10249 } 10250 10251 Region = RHS; 10252 Visit(BO->getRHS()); 10253 10254 Region = OldRegion; 10255 10256 // Forget that LHS and RHS are sequenced. They are both unsequenced 10257 // with respect to other stuff. 10258 Tree.merge(LHS); 10259 Tree.merge(RHS); 10260 } 10261 10262 void VisitBinAssign(BinaryOperator *BO) { 10263 // The modification is sequenced after the value computation of the LHS 10264 // and RHS, so check it before inspecting the operands and update the 10265 // map afterwards. 10266 Object O = getObject(BO->getLHS(), true); 10267 if (!O) 10268 return VisitExpr(BO); 10269 10270 notePreMod(O, BO); 10271 10272 // C++11 [expr.ass]p7: 10273 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 10274 // only once. 10275 // 10276 // Therefore, for a compound assignment operator, O is considered used 10277 // everywhere except within the evaluation of E1 itself. 10278 if (isa<CompoundAssignOperator>(BO)) 10279 notePreUse(O, BO); 10280 10281 Visit(BO->getLHS()); 10282 10283 if (isa<CompoundAssignOperator>(BO)) 10284 notePostUse(O, BO); 10285 10286 Visit(BO->getRHS()); 10287 10288 // C++11 [expr.ass]p1: 10289 // the assignment is sequenced [...] before the value computation of the 10290 // assignment expression. 10291 // C11 6.5.16/3 has no such rule. 10292 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10293 : UK_ModAsSideEffect); 10294 } 10295 10296 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 10297 VisitBinAssign(CAO); 10298 } 10299 10300 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10301 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10302 void VisitUnaryPreIncDec(UnaryOperator *UO) { 10303 Object O = getObject(UO->getSubExpr(), true); 10304 if (!O) 10305 return VisitExpr(UO); 10306 10307 notePreMod(O, UO); 10308 Visit(UO->getSubExpr()); 10309 // C++11 [expr.pre.incr]p1: 10310 // the expression ++x is equivalent to x+=1 10311 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10312 : UK_ModAsSideEffect); 10313 } 10314 10315 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10316 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10317 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10318 Object O = getObject(UO->getSubExpr(), true); 10319 if (!O) 10320 return VisitExpr(UO); 10321 10322 notePreMod(O, UO); 10323 Visit(UO->getSubExpr()); 10324 notePostMod(O, UO, UK_ModAsSideEffect); 10325 } 10326 10327 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10328 void VisitBinLOr(BinaryOperator *BO) { 10329 // The side-effects of the LHS of an '&&' are sequenced before the 10330 // value computation of the RHS, and hence before the value computation 10331 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10332 // as if they were unconditionally sequenced. 10333 EvaluationTracker Eval(*this); 10334 { 10335 SequencedSubexpression Sequenced(*this); 10336 Visit(BO->getLHS()); 10337 } 10338 10339 bool Result; 10340 if (Eval.evaluate(BO->getLHS(), Result)) { 10341 if (!Result) 10342 Visit(BO->getRHS()); 10343 } else { 10344 // Check for unsequenced operations in the RHS, treating it as an 10345 // entirely separate evaluation. 10346 // 10347 // FIXME: If there are operations in the RHS which are unsequenced 10348 // with respect to operations outside the RHS, and those operations 10349 // are unconditionally evaluated, diagnose them. 10350 WorkList.push_back(BO->getRHS()); 10351 } 10352 } 10353 void VisitBinLAnd(BinaryOperator *BO) { 10354 EvaluationTracker Eval(*this); 10355 { 10356 SequencedSubexpression Sequenced(*this); 10357 Visit(BO->getLHS()); 10358 } 10359 10360 bool Result; 10361 if (Eval.evaluate(BO->getLHS(), Result)) { 10362 if (Result) 10363 Visit(BO->getRHS()); 10364 } else { 10365 WorkList.push_back(BO->getRHS()); 10366 } 10367 } 10368 10369 // Only visit the condition, unless we can be sure which subexpression will 10370 // be chosen. 10371 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10372 EvaluationTracker Eval(*this); 10373 { 10374 SequencedSubexpression Sequenced(*this); 10375 Visit(CO->getCond()); 10376 } 10377 10378 bool Result; 10379 if (Eval.evaluate(CO->getCond(), Result)) 10380 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10381 else { 10382 WorkList.push_back(CO->getTrueExpr()); 10383 WorkList.push_back(CO->getFalseExpr()); 10384 } 10385 } 10386 10387 void VisitCallExpr(CallExpr *CE) { 10388 // C++11 [intro.execution]p15: 10389 // When calling a function [...], every value computation and side effect 10390 // associated with any argument expression, or with the postfix expression 10391 // designating the called function, is sequenced before execution of every 10392 // expression or statement in the body of the function [and thus before 10393 // the value computation of its result]. 10394 SequencedSubexpression Sequenced(*this); 10395 Base::VisitCallExpr(CE); 10396 10397 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10398 } 10399 10400 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10401 // This is a call, so all subexpressions are sequenced before the result. 10402 SequencedSubexpression Sequenced(*this); 10403 10404 if (!CCE->isListInitialization()) 10405 return VisitExpr(CCE); 10406 10407 // In C++11, list initializations are sequenced. 10408 SmallVector<SequenceTree::Seq, 32> Elts; 10409 SequenceTree::Seq Parent = Region; 10410 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10411 E = CCE->arg_end(); 10412 I != E; ++I) { 10413 Region = Tree.allocate(Parent); 10414 Elts.push_back(Region); 10415 Visit(*I); 10416 } 10417 10418 // Forget that the initializers are sequenced. 10419 Region = Parent; 10420 for (unsigned I = 0; I < Elts.size(); ++I) 10421 Tree.merge(Elts[I]); 10422 } 10423 10424 void VisitInitListExpr(InitListExpr *ILE) { 10425 if (!SemaRef.getLangOpts().CPlusPlus11) 10426 return VisitExpr(ILE); 10427 10428 // In C++11, list initializations are sequenced. 10429 SmallVector<SequenceTree::Seq, 32> Elts; 10430 SequenceTree::Seq Parent = Region; 10431 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10432 Expr *E = ILE->getInit(I); 10433 if (!E) continue; 10434 Region = Tree.allocate(Parent); 10435 Elts.push_back(Region); 10436 Visit(E); 10437 } 10438 10439 // Forget that the initializers are sequenced. 10440 Region = Parent; 10441 for (unsigned I = 0; I < Elts.size(); ++I) 10442 Tree.merge(Elts[I]); 10443 } 10444 }; 10445 } // end anonymous namespace 10446 10447 void Sema::CheckUnsequencedOperations(Expr *E) { 10448 SmallVector<Expr *, 8> WorkList; 10449 WorkList.push_back(E); 10450 while (!WorkList.empty()) { 10451 Expr *Item = WorkList.pop_back_val(); 10452 SequenceChecker(*this, Item, WorkList); 10453 } 10454 } 10455 10456 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10457 bool IsConstexpr) { 10458 CheckImplicitConversions(E, CheckLoc); 10459 if (!E->isInstantiationDependent()) 10460 CheckUnsequencedOperations(E); 10461 if (!IsConstexpr && !E->isValueDependent()) 10462 CheckForIntOverflow(E); 10463 DiagnoseMisalignedMembers(); 10464 } 10465 10466 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10467 FieldDecl *BitField, 10468 Expr *Init) { 10469 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10470 } 10471 10472 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10473 SourceLocation Loc) { 10474 if (!PType->isVariablyModifiedType()) 10475 return; 10476 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10477 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10478 return; 10479 } 10480 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10481 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10482 return; 10483 } 10484 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10485 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10486 return; 10487 } 10488 10489 const ArrayType *AT = S.Context.getAsArrayType(PType); 10490 if (!AT) 10491 return; 10492 10493 if (AT->getSizeModifier() != ArrayType::Star) { 10494 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10495 return; 10496 } 10497 10498 S.Diag(Loc, diag::err_array_star_in_function_definition); 10499 } 10500 10501 /// CheckParmsForFunctionDef - Check that the parameters of the given 10502 /// function are appropriate for the definition of a function. This 10503 /// takes care of any checks that cannot be performed on the 10504 /// declaration itself, e.g., that the types of each of the function 10505 /// parameters are complete. 10506 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10507 bool CheckParameterNames) { 10508 bool HasInvalidParm = false; 10509 for (ParmVarDecl *Param : Parameters) { 10510 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10511 // function declarator that is part of a function definition of 10512 // that function shall not have incomplete type. 10513 // 10514 // This is also C++ [dcl.fct]p6. 10515 if (!Param->isInvalidDecl() && 10516 RequireCompleteType(Param->getLocation(), Param->getType(), 10517 diag::err_typecheck_decl_incomplete_type)) { 10518 Param->setInvalidDecl(); 10519 HasInvalidParm = true; 10520 } 10521 10522 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10523 // declaration of each parameter shall include an identifier. 10524 if (CheckParameterNames && 10525 Param->getIdentifier() == nullptr && 10526 !Param->isImplicit() && 10527 !getLangOpts().CPlusPlus) 10528 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10529 10530 // C99 6.7.5.3p12: 10531 // If the function declarator is not part of a definition of that 10532 // function, parameters may have incomplete type and may use the [*] 10533 // notation in their sequences of declarator specifiers to specify 10534 // variable length array types. 10535 QualType PType = Param->getOriginalType(); 10536 // FIXME: This diagnostic should point the '[*]' if source-location 10537 // information is added for it. 10538 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10539 10540 // MSVC destroys objects passed by value in the callee. Therefore a 10541 // function definition which takes such a parameter must be able to call the 10542 // object's destructor. However, we don't perform any direct access check 10543 // on the dtor. 10544 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10545 .getCXXABI() 10546 .areArgsDestroyedLeftToRightInCallee()) { 10547 if (!Param->isInvalidDecl()) { 10548 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10549 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10550 if (!ClassDecl->isInvalidDecl() && 10551 !ClassDecl->hasIrrelevantDestructor() && 10552 !ClassDecl->isDependentContext()) { 10553 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10554 MarkFunctionReferenced(Param->getLocation(), Destructor); 10555 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10556 } 10557 } 10558 } 10559 } 10560 10561 // Parameters with the pass_object_size attribute only need to be marked 10562 // constant at function definitions. Because we lack information about 10563 // whether we're on a declaration or definition when we're instantiating the 10564 // attribute, we need to check for constness here. 10565 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10566 if (!Param->getType().isConstQualified()) 10567 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10568 << Attr->getSpelling() << 1; 10569 } 10570 10571 return HasInvalidParm; 10572 } 10573 10574 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 10575 /// or MemberExpr. 10576 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 10577 ASTContext &Context) { 10578 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 10579 return Context.getDeclAlign(DRE->getDecl()); 10580 10581 if (const auto *ME = dyn_cast<MemberExpr>(E)) 10582 return Context.getDeclAlign(ME->getMemberDecl()); 10583 10584 return TypeAlign; 10585 } 10586 10587 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10588 /// pointer cast increases the alignment requirements. 10589 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10590 // This is actually a lot of work to potentially be doing on every 10591 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10592 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10593 return; 10594 10595 // Ignore dependent types. 10596 if (T->isDependentType() || Op->getType()->isDependentType()) 10597 return; 10598 10599 // Require that the destination be a pointer type. 10600 const PointerType *DestPtr = T->getAs<PointerType>(); 10601 if (!DestPtr) return; 10602 10603 // If the destination has alignment 1, we're done. 10604 QualType DestPointee = DestPtr->getPointeeType(); 10605 if (DestPointee->isIncompleteType()) return; 10606 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10607 if (DestAlign.isOne()) return; 10608 10609 // Require that the source be a pointer type. 10610 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10611 if (!SrcPtr) return; 10612 QualType SrcPointee = SrcPtr->getPointeeType(); 10613 10614 // Whitelist casts from cv void*. We already implicitly 10615 // whitelisted casts to cv void*, since they have alignment 1. 10616 // Also whitelist casts involving incomplete types, which implicitly 10617 // includes 'void'. 10618 if (SrcPointee->isIncompleteType()) return; 10619 10620 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10621 10622 if (auto *CE = dyn_cast<CastExpr>(Op)) { 10623 if (CE->getCastKind() == CK_ArrayToPointerDecay) 10624 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 10625 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 10626 if (UO->getOpcode() == UO_AddrOf) 10627 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 10628 } 10629 10630 if (SrcAlign >= DestAlign) return; 10631 10632 Diag(TRange.getBegin(), diag::warn_cast_align) 10633 << Op->getType() << T 10634 << static_cast<unsigned>(SrcAlign.getQuantity()) 10635 << static_cast<unsigned>(DestAlign.getQuantity()) 10636 << TRange << Op->getSourceRange(); 10637 } 10638 10639 /// \brief Check whether this array fits the idiom of a size-one tail padded 10640 /// array member of a struct. 10641 /// 10642 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10643 /// commonly used to emulate flexible arrays in C89 code. 10644 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10645 const NamedDecl *ND) { 10646 if (Size != 1 || !ND) return false; 10647 10648 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10649 if (!FD) return false; 10650 10651 // Don't consider sizes resulting from macro expansions or template argument 10652 // substitution to form C89 tail-padded arrays. 10653 10654 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10655 while (TInfo) { 10656 TypeLoc TL = TInfo->getTypeLoc(); 10657 // Look through typedefs. 10658 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10659 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10660 TInfo = TDL->getTypeSourceInfo(); 10661 continue; 10662 } 10663 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10664 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10665 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10666 return false; 10667 } 10668 break; 10669 } 10670 10671 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10672 if (!RD) return false; 10673 if (RD->isUnion()) return false; 10674 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10675 if (!CRD->isStandardLayout()) return false; 10676 } 10677 10678 // See if this is the last field decl in the record. 10679 const Decl *D = FD; 10680 while ((D = D->getNextDeclInContext())) 10681 if (isa<FieldDecl>(D)) 10682 return false; 10683 return true; 10684 } 10685 10686 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10687 const ArraySubscriptExpr *ASE, 10688 bool AllowOnePastEnd, bool IndexNegated) { 10689 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10690 if (IndexExpr->isValueDependent()) 10691 return; 10692 10693 const Type *EffectiveType = 10694 BaseExpr->getType()->getPointeeOrArrayElementType(); 10695 BaseExpr = BaseExpr->IgnoreParenCasts(); 10696 const ConstantArrayType *ArrayTy = 10697 Context.getAsConstantArrayType(BaseExpr->getType()); 10698 if (!ArrayTy) 10699 return; 10700 10701 llvm::APSInt index; 10702 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10703 return; 10704 if (IndexNegated) 10705 index = -index; 10706 10707 const NamedDecl *ND = nullptr; 10708 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10709 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10710 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10711 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10712 10713 if (index.isUnsigned() || !index.isNegative()) { 10714 llvm::APInt size = ArrayTy->getSize(); 10715 if (!size.isStrictlyPositive()) 10716 return; 10717 10718 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10719 if (BaseType != EffectiveType) { 10720 // Make sure we're comparing apples to apples when comparing index to size 10721 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10722 uint64_t array_typesize = Context.getTypeSize(BaseType); 10723 // Handle ptrarith_typesize being zero, such as when casting to void* 10724 if (!ptrarith_typesize) ptrarith_typesize = 1; 10725 if (ptrarith_typesize != array_typesize) { 10726 // There's a cast to a different size type involved 10727 uint64_t ratio = array_typesize / ptrarith_typesize; 10728 // TODO: Be smarter about handling cases where array_typesize is not a 10729 // multiple of ptrarith_typesize 10730 if (ptrarith_typesize * ratio == array_typesize) 10731 size *= llvm::APInt(size.getBitWidth(), ratio); 10732 } 10733 } 10734 10735 if (size.getBitWidth() > index.getBitWidth()) 10736 index = index.zext(size.getBitWidth()); 10737 else if (size.getBitWidth() < index.getBitWidth()) 10738 size = size.zext(index.getBitWidth()); 10739 10740 // For array subscripting the index must be less than size, but for pointer 10741 // arithmetic also allow the index (offset) to be equal to size since 10742 // computing the next address after the end of the array is legal and 10743 // commonly done e.g. in C++ iterators and range-based for loops. 10744 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10745 return; 10746 10747 // Also don't warn for arrays of size 1 which are members of some 10748 // structure. These are often used to approximate flexible arrays in C89 10749 // code. 10750 if (IsTailPaddedMemberArray(*this, size, ND)) 10751 return; 10752 10753 // Suppress the warning if the subscript expression (as identified by the 10754 // ']' location) and the index expression are both from macro expansions 10755 // within a system header. 10756 if (ASE) { 10757 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 10758 ASE->getRBracketLoc()); 10759 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 10760 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 10761 IndexExpr->getLocStart()); 10762 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 10763 return; 10764 } 10765 } 10766 10767 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 10768 if (ASE) 10769 DiagID = diag::warn_array_index_exceeds_bounds; 10770 10771 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10772 PDiag(DiagID) << index.toString(10, true) 10773 << size.toString(10, true) 10774 << (unsigned)size.getLimitedValue(~0U) 10775 << IndexExpr->getSourceRange()); 10776 } else { 10777 unsigned DiagID = diag::warn_array_index_precedes_bounds; 10778 if (!ASE) { 10779 DiagID = diag::warn_ptr_arith_precedes_bounds; 10780 if (index.isNegative()) index = -index; 10781 } 10782 10783 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10784 PDiag(DiagID) << index.toString(10, true) 10785 << IndexExpr->getSourceRange()); 10786 } 10787 10788 if (!ND) { 10789 // Try harder to find a NamedDecl to point at in the note. 10790 while (const ArraySubscriptExpr *ASE = 10791 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 10792 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 10793 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10794 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10795 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10796 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10797 } 10798 10799 if (ND) 10800 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 10801 PDiag(diag::note_array_index_out_of_bounds) 10802 << ND->getDeclName()); 10803 } 10804 10805 void Sema::CheckArrayAccess(const Expr *expr) { 10806 int AllowOnePastEnd = 0; 10807 while (expr) { 10808 expr = expr->IgnoreParenImpCasts(); 10809 switch (expr->getStmtClass()) { 10810 case Stmt::ArraySubscriptExprClass: { 10811 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 10812 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 10813 AllowOnePastEnd > 0); 10814 return; 10815 } 10816 case Stmt::OMPArraySectionExprClass: { 10817 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 10818 if (ASE->getLowerBound()) 10819 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 10820 /*ASE=*/nullptr, AllowOnePastEnd > 0); 10821 return; 10822 } 10823 case Stmt::UnaryOperatorClass: { 10824 // Only unwrap the * and & unary operators 10825 const UnaryOperator *UO = cast<UnaryOperator>(expr); 10826 expr = UO->getSubExpr(); 10827 switch (UO->getOpcode()) { 10828 case UO_AddrOf: 10829 AllowOnePastEnd++; 10830 break; 10831 case UO_Deref: 10832 AllowOnePastEnd--; 10833 break; 10834 default: 10835 return; 10836 } 10837 break; 10838 } 10839 case Stmt::ConditionalOperatorClass: { 10840 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 10841 if (const Expr *lhs = cond->getLHS()) 10842 CheckArrayAccess(lhs); 10843 if (const Expr *rhs = cond->getRHS()) 10844 CheckArrayAccess(rhs); 10845 return; 10846 } 10847 case Stmt::CXXOperatorCallExprClass: { 10848 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 10849 for (const auto *Arg : OCE->arguments()) 10850 CheckArrayAccess(Arg); 10851 return; 10852 } 10853 default: 10854 return; 10855 } 10856 } 10857 } 10858 10859 //===--- CHECK: Objective-C retain cycles ----------------------------------// 10860 10861 namespace { 10862 struct RetainCycleOwner { 10863 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 10864 VarDecl *Variable; 10865 SourceRange Range; 10866 SourceLocation Loc; 10867 bool Indirect; 10868 10869 void setLocsFrom(Expr *e) { 10870 Loc = e->getExprLoc(); 10871 Range = e->getSourceRange(); 10872 } 10873 }; 10874 } // end anonymous namespace 10875 10876 /// Consider whether capturing the given variable can possibly lead to 10877 /// a retain cycle. 10878 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 10879 // In ARC, it's captured strongly iff the variable has __strong 10880 // lifetime. In MRR, it's captured strongly if the variable is 10881 // __block and has an appropriate type. 10882 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10883 return false; 10884 10885 owner.Variable = var; 10886 if (ref) 10887 owner.setLocsFrom(ref); 10888 return true; 10889 } 10890 10891 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 10892 while (true) { 10893 e = e->IgnoreParens(); 10894 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 10895 switch (cast->getCastKind()) { 10896 case CK_BitCast: 10897 case CK_LValueBitCast: 10898 case CK_LValueToRValue: 10899 case CK_ARCReclaimReturnedObject: 10900 e = cast->getSubExpr(); 10901 continue; 10902 10903 default: 10904 return false; 10905 } 10906 } 10907 10908 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 10909 ObjCIvarDecl *ivar = ref->getDecl(); 10910 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10911 return false; 10912 10913 // Try to find a retain cycle in the base. 10914 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 10915 return false; 10916 10917 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 10918 owner.Indirect = true; 10919 return true; 10920 } 10921 10922 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 10923 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 10924 if (!var) return false; 10925 return considerVariable(var, ref, owner); 10926 } 10927 10928 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 10929 if (member->isArrow()) return false; 10930 10931 // Don't count this as an indirect ownership. 10932 e = member->getBase(); 10933 continue; 10934 } 10935 10936 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 10937 // Only pay attention to pseudo-objects on property references. 10938 ObjCPropertyRefExpr *pre 10939 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 10940 ->IgnoreParens()); 10941 if (!pre) return false; 10942 if (pre->isImplicitProperty()) return false; 10943 ObjCPropertyDecl *property = pre->getExplicitProperty(); 10944 if (!property->isRetaining() && 10945 !(property->getPropertyIvarDecl() && 10946 property->getPropertyIvarDecl()->getType() 10947 .getObjCLifetime() == Qualifiers::OCL_Strong)) 10948 return false; 10949 10950 owner.Indirect = true; 10951 if (pre->isSuperReceiver()) { 10952 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 10953 if (!owner.Variable) 10954 return false; 10955 owner.Loc = pre->getLocation(); 10956 owner.Range = pre->getSourceRange(); 10957 return true; 10958 } 10959 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 10960 ->getSourceExpr()); 10961 continue; 10962 } 10963 10964 // Array ivars? 10965 10966 return false; 10967 } 10968 } 10969 10970 namespace { 10971 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 10972 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 10973 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 10974 Context(Context), Variable(variable), Capturer(nullptr), 10975 VarWillBeReased(false) {} 10976 ASTContext &Context; 10977 VarDecl *Variable; 10978 Expr *Capturer; 10979 bool VarWillBeReased; 10980 10981 void VisitDeclRefExpr(DeclRefExpr *ref) { 10982 if (ref->getDecl() == Variable && !Capturer) 10983 Capturer = ref; 10984 } 10985 10986 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 10987 if (Capturer) return; 10988 Visit(ref->getBase()); 10989 if (Capturer && ref->isFreeIvar()) 10990 Capturer = ref; 10991 } 10992 10993 void VisitBlockExpr(BlockExpr *block) { 10994 // Look inside nested blocks 10995 if (block->getBlockDecl()->capturesVariable(Variable)) 10996 Visit(block->getBlockDecl()->getBody()); 10997 } 10998 10999 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11000 if (Capturer) return; 11001 if (OVE->getSourceExpr()) 11002 Visit(OVE->getSourceExpr()); 11003 } 11004 void VisitBinaryOperator(BinaryOperator *BinOp) { 11005 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11006 return; 11007 Expr *LHS = BinOp->getLHS(); 11008 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11009 if (DRE->getDecl() != Variable) 11010 return; 11011 if (Expr *RHS = BinOp->getRHS()) { 11012 RHS = RHS->IgnoreParenCasts(); 11013 llvm::APSInt Value; 11014 VarWillBeReased = 11015 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11016 } 11017 } 11018 } 11019 }; 11020 } // end anonymous namespace 11021 11022 /// Check whether the given argument is a block which captures a 11023 /// variable. 11024 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11025 assert(owner.Variable && owner.Loc.isValid()); 11026 11027 e = e->IgnoreParenCasts(); 11028 11029 // Look through [^{...} copy] and Block_copy(^{...}). 11030 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11031 Selector Cmd = ME->getSelector(); 11032 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11033 e = ME->getInstanceReceiver(); 11034 if (!e) 11035 return nullptr; 11036 e = e->IgnoreParenCasts(); 11037 } 11038 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11039 if (CE->getNumArgs() == 1) { 11040 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11041 if (Fn) { 11042 const IdentifierInfo *FnI = Fn->getIdentifier(); 11043 if (FnI && FnI->isStr("_Block_copy")) { 11044 e = CE->getArg(0)->IgnoreParenCasts(); 11045 } 11046 } 11047 } 11048 } 11049 11050 BlockExpr *block = dyn_cast<BlockExpr>(e); 11051 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11052 return nullptr; 11053 11054 FindCaptureVisitor visitor(S.Context, owner.Variable); 11055 visitor.Visit(block->getBlockDecl()->getBody()); 11056 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11057 } 11058 11059 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11060 RetainCycleOwner &owner) { 11061 assert(capturer); 11062 assert(owner.Variable && owner.Loc.isValid()); 11063 11064 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11065 << owner.Variable << capturer->getSourceRange(); 11066 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11067 << owner.Indirect << owner.Range; 11068 } 11069 11070 /// Check for a keyword selector that starts with the word 'add' or 11071 /// 'set'. 11072 static bool isSetterLikeSelector(Selector sel) { 11073 if (sel.isUnarySelector()) return false; 11074 11075 StringRef str = sel.getNameForSlot(0); 11076 while (!str.empty() && str.front() == '_') str = str.substr(1); 11077 if (str.startswith("set")) 11078 str = str.substr(3); 11079 else if (str.startswith("add")) { 11080 // Specially whitelist 'addOperationWithBlock:'. 11081 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 11082 return false; 11083 str = str.substr(3); 11084 } 11085 else 11086 return false; 11087 11088 if (str.empty()) return true; 11089 return !isLowercase(str.front()); 11090 } 11091 11092 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 11093 ObjCMessageExpr *Message) { 11094 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 11095 Message->getReceiverInterface(), 11096 NSAPI::ClassId_NSMutableArray); 11097 if (!IsMutableArray) { 11098 return None; 11099 } 11100 11101 Selector Sel = Message->getSelector(); 11102 11103 Optional<NSAPI::NSArrayMethodKind> MKOpt = 11104 S.NSAPIObj->getNSArrayMethodKind(Sel); 11105 if (!MKOpt) { 11106 return None; 11107 } 11108 11109 NSAPI::NSArrayMethodKind MK = *MKOpt; 11110 11111 switch (MK) { 11112 case NSAPI::NSMutableArr_addObject: 11113 case NSAPI::NSMutableArr_insertObjectAtIndex: 11114 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 11115 return 0; 11116 case NSAPI::NSMutableArr_replaceObjectAtIndex: 11117 return 1; 11118 11119 default: 11120 return None; 11121 } 11122 11123 return None; 11124 } 11125 11126 static 11127 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 11128 ObjCMessageExpr *Message) { 11129 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 11130 Message->getReceiverInterface(), 11131 NSAPI::ClassId_NSMutableDictionary); 11132 if (!IsMutableDictionary) { 11133 return None; 11134 } 11135 11136 Selector Sel = Message->getSelector(); 11137 11138 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 11139 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 11140 if (!MKOpt) { 11141 return None; 11142 } 11143 11144 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 11145 11146 switch (MK) { 11147 case NSAPI::NSMutableDict_setObjectForKey: 11148 case NSAPI::NSMutableDict_setValueForKey: 11149 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 11150 return 0; 11151 11152 default: 11153 return None; 11154 } 11155 11156 return None; 11157 } 11158 11159 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 11160 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 11161 Message->getReceiverInterface(), 11162 NSAPI::ClassId_NSMutableSet); 11163 11164 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 11165 Message->getReceiverInterface(), 11166 NSAPI::ClassId_NSMutableOrderedSet); 11167 if (!IsMutableSet && !IsMutableOrderedSet) { 11168 return None; 11169 } 11170 11171 Selector Sel = Message->getSelector(); 11172 11173 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 11174 if (!MKOpt) { 11175 return None; 11176 } 11177 11178 NSAPI::NSSetMethodKind MK = *MKOpt; 11179 11180 switch (MK) { 11181 case NSAPI::NSMutableSet_addObject: 11182 case NSAPI::NSOrderedSet_setObjectAtIndex: 11183 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 11184 case NSAPI::NSOrderedSet_insertObjectAtIndex: 11185 return 0; 11186 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 11187 return 1; 11188 } 11189 11190 return None; 11191 } 11192 11193 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 11194 if (!Message->isInstanceMessage()) { 11195 return; 11196 } 11197 11198 Optional<int> ArgOpt; 11199 11200 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 11201 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 11202 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 11203 return; 11204 } 11205 11206 int ArgIndex = *ArgOpt; 11207 11208 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 11209 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 11210 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 11211 } 11212 11213 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 11214 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11215 if (ArgRE->isObjCSelfExpr()) { 11216 Diag(Message->getSourceRange().getBegin(), 11217 diag::warn_objc_circular_container) 11218 << ArgRE->getDecl()->getName() << StringRef("super"); 11219 } 11220 } 11221 } else { 11222 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 11223 11224 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 11225 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 11226 } 11227 11228 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 11229 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11230 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 11231 ValueDecl *Decl = ReceiverRE->getDecl(); 11232 Diag(Message->getSourceRange().getBegin(), 11233 diag::warn_objc_circular_container) 11234 << Decl->getName() << Decl->getName(); 11235 if (!ArgRE->isObjCSelfExpr()) { 11236 Diag(Decl->getLocation(), 11237 diag::note_objc_circular_container_declared_here) 11238 << Decl->getName(); 11239 } 11240 } 11241 } 11242 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 11243 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 11244 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 11245 ObjCIvarDecl *Decl = IvarRE->getDecl(); 11246 Diag(Message->getSourceRange().getBegin(), 11247 diag::warn_objc_circular_container) 11248 << Decl->getName() << Decl->getName(); 11249 Diag(Decl->getLocation(), 11250 diag::note_objc_circular_container_declared_here) 11251 << Decl->getName(); 11252 } 11253 } 11254 } 11255 } 11256 } 11257 11258 /// Check a message send to see if it's likely to cause a retain cycle. 11259 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11260 // Only check instance methods whose selector looks like a setter. 11261 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 11262 return; 11263 11264 // Try to find a variable that the receiver is strongly owned by. 11265 RetainCycleOwner owner; 11266 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 11267 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 11268 return; 11269 } else { 11270 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 11271 owner.Variable = getCurMethodDecl()->getSelfDecl(); 11272 owner.Loc = msg->getSuperLoc(); 11273 owner.Range = msg->getSuperLoc(); 11274 } 11275 11276 // Check whether the receiver is captured by any of the arguments. 11277 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 11278 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 11279 return diagnoseRetainCycle(*this, capturer, owner); 11280 } 11281 11282 /// Check a property assign to see if it's likely to cause a retain cycle. 11283 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 11284 RetainCycleOwner owner; 11285 if (!findRetainCycleOwner(*this, receiver, owner)) 11286 return; 11287 11288 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 11289 diagnoseRetainCycle(*this, capturer, owner); 11290 } 11291 11292 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 11293 RetainCycleOwner Owner; 11294 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 11295 return; 11296 11297 // Because we don't have an expression for the variable, we have to set the 11298 // location explicitly here. 11299 Owner.Loc = Var->getLocation(); 11300 Owner.Range = Var->getSourceRange(); 11301 11302 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 11303 diagnoseRetainCycle(*this, Capturer, Owner); 11304 } 11305 11306 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 11307 Expr *RHS, bool isProperty) { 11308 // Check if RHS is an Objective-C object literal, which also can get 11309 // immediately zapped in a weak reference. Note that we explicitly 11310 // allow ObjCStringLiterals, since those are designed to never really die. 11311 RHS = RHS->IgnoreParenImpCasts(); 11312 11313 // This enum needs to match with the 'select' in 11314 // warn_objc_arc_literal_assign (off-by-1). 11315 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 11316 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 11317 return false; 11318 11319 S.Diag(Loc, diag::warn_arc_literal_assign) 11320 << (unsigned) Kind 11321 << (isProperty ? 0 : 1) 11322 << RHS->getSourceRange(); 11323 11324 return true; 11325 } 11326 11327 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 11328 Qualifiers::ObjCLifetime LT, 11329 Expr *RHS, bool isProperty) { 11330 // Strip off any implicit cast added to get to the one ARC-specific. 11331 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11332 if (cast->getCastKind() == CK_ARCConsumeObject) { 11333 S.Diag(Loc, diag::warn_arc_retained_assign) 11334 << (LT == Qualifiers::OCL_ExplicitNone) 11335 << (isProperty ? 0 : 1) 11336 << RHS->getSourceRange(); 11337 return true; 11338 } 11339 RHS = cast->getSubExpr(); 11340 } 11341 11342 if (LT == Qualifiers::OCL_Weak && 11343 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11344 return true; 11345 11346 return false; 11347 } 11348 11349 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11350 QualType LHS, Expr *RHS) { 11351 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11352 11353 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11354 return false; 11355 11356 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11357 return true; 11358 11359 return false; 11360 } 11361 11362 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11363 Expr *LHS, Expr *RHS) { 11364 QualType LHSType; 11365 // PropertyRef on LHS type need be directly obtained from 11366 // its declaration as it has a PseudoType. 11367 ObjCPropertyRefExpr *PRE 11368 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11369 if (PRE && !PRE->isImplicitProperty()) { 11370 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11371 if (PD) 11372 LHSType = PD->getType(); 11373 } 11374 11375 if (LHSType.isNull()) 11376 LHSType = LHS->getType(); 11377 11378 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11379 11380 if (LT == Qualifiers::OCL_Weak) { 11381 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11382 getCurFunction()->markSafeWeakUse(LHS); 11383 } 11384 11385 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11386 return; 11387 11388 // FIXME. Check for other life times. 11389 if (LT != Qualifiers::OCL_None) 11390 return; 11391 11392 if (PRE) { 11393 if (PRE->isImplicitProperty()) 11394 return; 11395 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11396 if (!PD) 11397 return; 11398 11399 unsigned Attributes = PD->getPropertyAttributes(); 11400 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11401 // when 'assign' attribute was not explicitly specified 11402 // by user, ignore it and rely on property type itself 11403 // for lifetime info. 11404 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11405 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11406 LHSType->isObjCRetainableType()) 11407 return; 11408 11409 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11410 if (cast->getCastKind() == CK_ARCConsumeObject) { 11411 Diag(Loc, diag::warn_arc_retained_property_assign) 11412 << RHS->getSourceRange(); 11413 return; 11414 } 11415 RHS = cast->getSubExpr(); 11416 } 11417 } 11418 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11419 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11420 return; 11421 } 11422 } 11423 } 11424 11425 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11426 11427 namespace { 11428 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11429 SourceLocation StmtLoc, 11430 const NullStmt *Body) { 11431 // Do not warn if the body is a macro that expands to nothing, e.g: 11432 // 11433 // #define CALL(x) 11434 // if (condition) 11435 // CALL(0); 11436 // 11437 if (Body->hasLeadingEmptyMacro()) 11438 return false; 11439 11440 // Get line numbers of statement and body. 11441 bool StmtLineInvalid; 11442 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11443 &StmtLineInvalid); 11444 if (StmtLineInvalid) 11445 return false; 11446 11447 bool BodyLineInvalid; 11448 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11449 &BodyLineInvalid); 11450 if (BodyLineInvalid) 11451 return false; 11452 11453 // Warn if null statement and body are on the same line. 11454 if (StmtLine != BodyLine) 11455 return false; 11456 11457 return true; 11458 } 11459 } // end anonymous namespace 11460 11461 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11462 const Stmt *Body, 11463 unsigned DiagID) { 11464 // Since this is a syntactic check, don't emit diagnostic for template 11465 // instantiations, this just adds noise. 11466 if (CurrentInstantiationScope) 11467 return; 11468 11469 // The body should be a null statement. 11470 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11471 if (!NBody) 11472 return; 11473 11474 // Do the usual checks. 11475 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11476 return; 11477 11478 Diag(NBody->getSemiLoc(), DiagID); 11479 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11480 } 11481 11482 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11483 const Stmt *PossibleBody) { 11484 assert(!CurrentInstantiationScope); // Ensured by caller 11485 11486 SourceLocation StmtLoc; 11487 const Stmt *Body; 11488 unsigned DiagID; 11489 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11490 StmtLoc = FS->getRParenLoc(); 11491 Body = FS->getBody(); 11492 DiagID = diag::warn_empty_for_body; 11493 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11494 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11495 Body = WS->getBody(); 11496 DiagID = diag::warn_empty_while_body; 11497 } else 11498 return; // Neither `for' nor `while'. 11499 11500 // The body should be a null statement. 11501 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11502 if (!NBody) 11503 return; 11504 11505 // Skip expensive checks if diagnostic is disabled. 11506 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11507 return; 11508 11509 // Do the usual checks. 11510 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11511 return; 11512 11513 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11514 // noise level low, emit diagnostics only if for/while is followed by a 11515 // CompoundStmt, e.g.: 11516 // for (int i = 0; i < n; i++); 11517 // { 11518 // a(i); 11519 // } 11520 // or if for/while is followed by a statement with more indentation 11521 // than for/while itself: 11522 // for (int i = 0; i < n; i++); 11523 // a(i); 11524 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11525 if (!ProbableTypo) { 11526 bool BodyColInvalid; 11527 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11528 PossibleBody->getLocStart(), 11529 &BodyColInvalid); 11530 if (BodyColInvalid) 11531 return; 11532 11533 bool StmtColInvalid; 11534 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11535 S->getLocStart(), 11536 &StmtColInvalid); 11537 if (StmtColInvalid) 11538 return; 11539 11540 if (BodyCol > StmtCol) 11541 ProbableTypo = true; 11542 } 11543 11544 if (ProbableTypo) { 11545 Diag(NBody->getSemiLoc(), DiagID); 11546 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11547 } 11548 } 11549 11550 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11551 11552 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11553 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11554 SourceLocation OpLoc) { 11555 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11556 return; 11557 11558 if (inTemplateInstantiation()) 11559 return; 11560 11561 // Strip parens and casts away. 11562 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11563 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11564 11565 // Check for a call expression 11566 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11567 if (!CE || CE->getNumArgs() != 1) 11568 return; 11569 11570 // Check for a call to std::move 11571 const FunctionDecl *FD = CE->getDirectCallee(); 11572 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 11573 !FD->getIdentifier()->isStr("move")) 11574 return; 11575 11576 // Get argument from std::move 11577 RHSExpr = CE->getArg(0); 11578 11579 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11580 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11581 11582 // Two DeclRefExpr's, check that the decls are the same. 11583 if (LHSDeclRef && RHSDeclRef) { 11584 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11585 return; 11586 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11587 RHSDeclRef->getDecl()->getCanonicalDecl()) 11588 return; 11589 11590 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11591 << LHSExpr->getSourceRange() 11592 << RHSExpr->getSourceRange(); 11593 return; 11594 } 11595 11596 // Member variables require a different approach to check for self moves. 11597 // MemberExpr's are the same if every nested MemberExpr refers to the same 11598 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11599 // the base Expr's are CXXThisExpr's. 11600 const Expr *LHSBase = LHSExpr; 11601 const Expr *RHSBase = RHSExpr; 11602 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11603 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11604 if (!LHSME || !RHSME) 11605 return; 11606 11607 while (LHSME && RHSME) { 11608 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11609 RHSME->getMemberDecl()->getCanonicalDecl()) 11610 return; 11611 11612 LHSBase = LHSME->getBase(); 11613 RHSBase = RHSME->getBase(); 11614 LHSME = dyn_cast<MemberExpr>(LHSBase); 11615 RHSME = dyn_cast<MemberExpr>(RHSBase); 11616 } 11617 11618 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11619 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11620 if (LHSDeclRef && RHSDeclRef) { 11621 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11622 return; 11623 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11624 RHSDeclRef->getDecl()->getCanonicalDecl()) 11625 return; 11626 11627 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11628 << LHSExpr->getSourceRange() 11629 << RHSExpr->getSourceRange(); 11630 return; 11631 } 11632 11633 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11634 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11635 << LHSExpr->getSourceRange() 11636 << RHSExpr->getSourceRange(); 11637 } 11638 11639 //===--- Layout compatibility ----------------------------------------------// 11640 11641 namespace { 11642 11643 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11644 11645 /// \brief Check if two enumeration types are layout-compatible. 11646 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11647 // C++11 [dcl.enum] p8: 11648 // Two enumeration types are layout-compatible if they have the same 11649 // underlying type. 11650 return ED1->isComplete() && ED2->isComplete() && 11651 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11652 } 11653 11654 /// \brief Check if two fields are layout-compatible. 11655 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11656 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11657 return false; 11658 11659 if (Field1->isBitField() != Field2->isBitField()) 11660 return false; 11661 11662 if (Field1->isBitField()) { 11663 // Make sure that the bit-fields are the same length. 11664 unsigned Bits1 = Field1->getBitWidthValue(C); 11665 unsigned Bits2 = Field2->getBitWidthValue(C); 11666 11667 if (Bits1 != Bits2) 11668 return false; 11669 } 11670 11671 return true; 11672 } 11673 11674 /// \brief Check if two standard-layout structs are layout-compatible. 11675 /// (C++11 [class.mem] p17) 11676 bool isLayoutCompatibleStruct(ASTContext &C, 11677 RecordDecl *RD1, 11678 RecordDecl *RD2) { 11679 // If both records are C++ classes, check that base classes match. 11680 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11681 // If one of records is a CXXRecordDecl we are in C++ mode, 11682 // thus the other one is a CXXRecordDecl, too. 11683 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11684 // Check number of base classes. 11685 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11686 return false; 11687 11688 // Check the base classes. 11689 for (CXXRecordDecl::base_class_const_iterator 11690 Base1 = D1CXX->bases_begin(), 11691 BaseEnd1 = D1CXX->bases_end(), 11692 Base2 = D2CXX->bases_begin(); 11693 Base1 != BaseEnd1; 11694 ++Base1, ++Base2) { 11695 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11696 return false; 11697 } 11698 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11699 // If only RD2 is a C++ class, it should have zero base classes. 11700 if (D2CXX->getNumBases() > 0) 11701 return false; 11702 } 11703 11704 // Check the fields. 11705 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11706 Field2End = RD2->field_end(), 11707 Field1 = RD1->field_begin(), 11708 Field1End = RD1->field_end(); 11709 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11710 if (!isLayoutCompatible(C, *Field1, *Field2)) 11711 return false; 11712 } 11713 if (Field1 != Field1End || Field2 != Field2End) 11714 return false; 11715 11716 return true; 11717 } 11718 11719 /// \brief Check if two standard-layout unions are layout-compatible. 11720 /// (C++11 [class.mem] p18) 11721 bool isLayoutCompatibleUnion(ASTContext &C, 11722 RecordDecl *RD1, 11723 RecordDecl *RD2) { 11724 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11725 for (auto *Field2 : RD2->fields()) 11726 UnmatchedFields.insert(Field2); 11727 11728 for (auto *Field1 : RD1->fields()) { 11729 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11730 I = UnmatchedFields.begin(), 11731 E = UnmatchedFields.end(); 11732 11733 for ( ; I != E; ++I) { 11734 if (isLayoutCompatible(C, Field1, *I)) { 11735 bool Result = UnmatchedFields.erase(*I); 11736 (void) Result; 11737 assert(Result); 11738 break; 11739 } 11740 } 11741 if (I == E) 11742 return false; 11743 } 11744 11745 return UnmatchedFields.empty(); 11746 } 11747 11748 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11749 if (RD1->isUnion() != RD2->isUnion()) 11750 return false; 11751 11752 if (RD1->isUnion()) 11753 return isLayoutCompatibleUnion(C, RD1, RD2); 11754 else 11755 return isLayoutCompatibleStruct(C, RD1, RD2); 11756 } 11757 11758 /// \brief Check if two types are layout-compatible in C++11 sense. 11759 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 11760 if (T1.isNull() || T2.isNull()) 11761 return false; 11762 11763 // C++11 [basic.types] p11: 11764 // If two types T1 and T2 are the same type, then T1 and T2 are 11765 // layout-compatible types. 11766 if (C.hasSameType(T1, T2)) 11767 return true; 11768 11769 T1 = T1.getCanonicalType().getUnqualifiedType(); 11770 T2 = T2.getCanonicalType().getUnqualifiedType(); 11771 11772 const Type::TypeClass TC1 = T1->getTypeClass(); 11773 const Type::TypeClass TC2 = T2->getTypeClass(); 11774 11775 if (TC1 != TC2) 11776 return false; 11777 11778 if (TC1 == Type::Enum) { 11779 return isLayoutCompatible(C, 11780 cast<EnumType>(T1)->getDecl(), 11781 cast<EnumType>(T2)->getDecl()); 11782 } else if (TC1 == Type::Record) { 11783 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 11784 return false; 11785 11786 return isLayoutCompatible(C, 11787 cast<RecordType>(T1)->getDecl(), 11788 cast<RecordType>(T2)->getDecl()); 11789 } 11790 11791 return false; 11792 } 11793 } // end anonymous namespace 11794 11795 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 11796 11797 namespace { 11798 /// \brief Given a type tag expression find the type tag itself. 11799 /// 11800 /// \param TypeExpr Type tag expression, as it appears in user's code. 11801 /// 11802 /// \param VD Declaration of an identifier that appears in a type tag. 11803 /// 11804 /// \param MagicValue Type tag magic value. 11805 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 11806 const ValueDecl **VD, uint64_t *MagicValue) { 11807 while(true) { 11808 if (!TypeExpr) 11809 return false; 11810 11811 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 11812 11813 switch (TypeExpr->getStmtClass()) { 11814 case Stmt::UnaryOperatorClass: { 11815 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 11816 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 11817 TypeExpr = UO->getSubExpr(); 11818 continue; 11819 } 11820 return false; 11821 } 11822 11823 case Stmt::DeclRefExprClass: { 11824 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 11825 *VD = DRE->getDecl(); 11826 return true; 11827 } 11828 11829 case Stmt::IntegerLiteralClass: { 11830 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 11831 llvm::APInt MagicValueAPInt = IL->getValue(); 11832 if (MagicValueAPInt.getActiveBits() <= 64) { 11833 *MagicValue = MagicValueAPInt.getZExtValue(); 11834 return true; 11835 } else 11836 return false; 11837 } 11838 11839 case Stmt::BinaryConditionalOperatorClass: 11840 case Stmt::ConditionalOperatorClass: { 11841 const AbstractConditionalOperator *ACO = 11842 cast<AbstractConditionalOperator>(TypeExpr); 11843 bool Result; 11844 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 11845 if (Result) 11846 TypeExpr = ACO->getTrueExpr(); 11847 else 11848 TypeExpr = ACO->getFalseExpr(); 11849 continue; 11850 } 11851 return false; 11852 } 11853 11854 case Stmt::BinaryOperatorClass: { 11855 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 11856 if (BO->getOpcode() == BO_Comma) { 11857 TypeExpr = BO->getRHS(); 11858 continue; 11859 } 11860 return false; 11861 } 11862 11863 default: 11864 return false; 11865 } 11866 } 11867 } 11868 11869 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 11870 /// 11871 /// \param TypeExpr Expression that specifies a type tag. 11872 /// 11873 /// \param MagicValues Registered magic values. 11874 /// 11875 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 11876 /// kind. 11877 /// 11878 /// \param TypeInfo Information about the corresponding C type. 11879 /// 11880 /// \returns true if the corresponding C type was found. 11881 bool GetMatchingCType( 11882 const IdentifierInfo *ArgumentKind, 11883 const Expr *TypeExpr, const ASTContext &Ctx, 11884 const llvm::DenseMap<Sema::TypeTagMagicValue, 11885 Sema::TypeTagData> *MagicValues, 11886 bool &FoundWrongKind, 11887 Sema::TypeTagData &TypeInfo) { 11888 FoundWrongKind = false; 11889 11890 // Variable declaration that has type_tag_for_datatype attribute. 11891 const ValueDecl *VD = nullptr; 11892 11893 uint64_t MagicValue; 11894 11895 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 11896 return false; 11897 11898 if (VD) { 11899 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 11900 if (I->getArgumentKind() != ArgumentKind) { 11901 FoundWrongKind = true; 11902 return false; 11903 } 11904 TypeInfo.Type = I->getMatchingCType(); 11905 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 11906 TypeInfo.MustBeNull = I->getMustBeNull(); 11907 return true; 11908 } 11909 return false; 11910 } 11911 11912 if (!MagicValues) 11913 return false; 11914 11915 llvm::DenseMap<Sema::TypeTagMagicValue, 11916 Sema::TypeTagData>::const_iterator I = 11917 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 11918 if (I == MagicValues->end()) 11919 return false; 11920 11921 TypeInfo = I->second; 11922 return true; 11923 } 11924 } // end anonymous namespace 11925 11926 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 11927 uint64_t MagicValue, QualType Type, 11928 bool LayoutCompatible, 11929 bool MustBeNull) { 11930 if (!TypeTagForDatatypeMagicValues) 11931 TypeTagForDatatypeMagicValues.reset( 11932 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 11933 11934 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 11935 (*TypeTagForDatatypeMagicValues)[Magic] = 11936 TypeTagData(Type, LayoutCompatible, MustBeNull); 11937 } 11938 11939 namespace { 11940 bool IsSameCharType(QualType T1, QualType T2) { 11941 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 11942 if (!BT1) 11943 return false; 11944 11945 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 11946 if (!BT2) 11947 return false; 11948 11949 BuiltinType::Kind T1Kind = BT1->getKind(); 11950 BuiltinType::Kind T2Kind = BT2->getKind(); 11951 11952 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 11953 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 11954 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 11955 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 11956 } 11957 } // end anonymous namespace 11958 11959 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 11960 const Expr * const *ExprArgs) { 11961 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 11962 bool IsPointerAttr = Attr->getIsPointer(); 11963 11964 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 11965 bool FoundWrongKind; 11966 TypeTagData TypeInfo; 11967 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 11968 TypeTagForDatatypeMagicValues.get(), 11969 FoundWrongKind, TypeInfo)) { 11970 if (FoundWrongKind) 11971 Diag(TypeTagExpr->getExprLoc(), 11972 diag::warn_type_tag_for_datatype_wrong_kind) 11973 << TypeTagExpr->getSourceRange(); 11974 return; 11975 } 11976 11977 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 11978 if (IsPointerAttr) { 11979 // Skip implicit cast of pointer to `void *' (as a function argument). 11980 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 11981 if (ICE->getType()->isVoidPointerType() && 11982 ICE->getCastKind() == CK_BitCast) 11983 ArgumentExpr = ICE->getSubExpr(); 11984 } 11985 QualType ArgumentType = ArgumentExpr->getType(); 11986 11987 // Passing a `void*' pointer shouldn't trigger a warning. 11988 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 11989 return; 11990 11991 if (TypeInfo.MustBeNull) { 11992 // Type tag with matching void type requires a null pointer. 11993 if (!ArgumentExpr->isNullPointerConstant(Context, 11994 Expr::NPC_ValueDependentIsNotNull)) { 11995 Diag(ArgumentExpr->getExprLoc(), 11996 diag::warn_type_safety_null_pointer_required) 11997 << ArgumentKind->getName() 11998 << ArgumentExpr->getSourceRange() 11999 << TypeTagExpr->getSourceRange(); 12000 } 12001 return; 12002 } 12003 12004 QualType RequiredType = TypeInfo.Type; 12005 if (IsPointerAttr) 12006 RequiredType = Context.getPointerType(RequiredType); 12007 12008 bool mismatch = false; 12009 if (!TypeInfo.LayoutCompatible) { 12010 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12011 12012 // C++11 [basic.fundamental] p1: 12013 // Plain char, signed char, and unsigned char are three distinct types. 12014 // 12015 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12016 // char' depending on the current char signedness mode. 12017 if (mismatch) 12018 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12019 RequiredType->getPointeeType())) || 12020 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12021 mismatch = false; 12022 } else 12023 if (IsPointerAttr) 12024 mismatch = !isLayoutCompatible(Context, 12025 ArgumentType->getPointeeType(), 12026 RequiredType->getPointeeType()); 12027 else 12028 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12029 12030 if (mismatch) 12031 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12032 << ArgumentType << ArgumentKind 12033 << TypeInfo.LayoutCompatible << RequiredType 12034 << ArgumentExpr->getSourceRange() 12035 << TypeTagExpr->getSourceRange(); 12036 } 12037 12038 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12039 CharUnits Alignment) { 12040 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12041 } 12042 12043 void Sema::DiagnoseMisalignedMembers() { 12044 for (MisalignedMember &m : MisalignedMembers) { 12045 const NamedDecl *ND = m.RD; 12046 if (ND->getName().empty()) { 12047 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12048 ND = TD; 12049 } 12050 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12051 << m.MD << ND << m.E->getSourceRange(); 12052 } 12053 MisalignedMembers.clear(); 12054 } 12055 12056 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12057 E = E->IgnoreParens(); 12058 if (!T->isPointerType() && !T->isIntegerType()) 12059 return; 12060 if (isa<UnaryOperator>(E) && 12061 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 12062 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 12063 if (isa<MemberExpr>(Op)) { 12064 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 12065 MisalignedMember(Op)); 12066 if (MA != MisalignedMembers.end() && 12067 (T->isIntegerType() || 12068 (T->isPointerType() && 12069 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment))) 12070 MisalignedMembers.erase(MA); 12071 } 12072 } 12073 } 12074 12075 void Sema::RefersToMemberWithReducedAlignment( 12076 Expr *E, 12077 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12078 Action) { 12079 const auto *ME = dyn_cast<MemberExpr>(E); 12080 if (!ME) 12081 return; 12082 12083 // No need to check expressions with an __unaligned-qualified type. 12084 if (E->getType().getQualifiers().hasUnaligned()) 12085 return; 12086 12087 // For a chain of MemberExpr like "a.b.c.d" this list 12088 // will keep FieldDecl's like [d, c, b]. 12089 SmallVector<FieldDecl *, 4> ReverseMemberChain; 12090 const MemberExpr *TopME = nullptr; 12091 bool AnyIsPacked = false; 12092 do { 12093 QualType BaseType = ME->getBase()->getType(); 12094 if (ME->isArrow()) 12095 BaseType = BaseType->getPointeeType(); 12096 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 12097 12098 ValueDecl *MD = ME->getMemberDecl(); 12099 auto *FD = dyn_cast<FieldDecl>(MD); 12100 // We do not care about non-data members. 12101 if (!FD || FD->isInvalidDecl()) 12102 return; 12103 12104 AnyIsPacked = 12105 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 12106 ReverseMemberChain.push_back(FD); 12107 12108 TopME = ME; 12109 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 12110 } while (ME); 12111 assert(TopME && "We did not compute a topmost MemberExpr!"); 12112 12113 // Not the scope of this diagnostic. 12114 if (!AnyIsPacked) 12115 return; 12116 12117 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 12118 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 12119 // TODO: The innermost base of the member expression may be too complicated. 12120 // For now, just disregard these cases. This is left for future 12121 // improvement. 12122 if (!DRE && !isa<CXXThisExpr>(TopBase)) 12123 return; 12124 12125 // Alignment expected by the whole expression. 12126 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 12127 12128 // No need to do anything else with this case. 12129 if (ExpectedAlignment.isOne()) 12130 return; 12131 12132 // Synthesize offset of the whole access. 12133 CharUnits Offset; 12134 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 12135 I++) { 12136 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 12137 } 12138 12139 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 12140 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 12141 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 12142 12143 // The base expression of the innermost MemberExpr may give 12144 // stronger guarantees than the class containing the member. 12145 if (DRE && !TopME->isArrow()) { 12146 const ValueDecl *VD = DRE->getDecl(); 12147 if (!VD->getType()->isReferenceType()) 12148 CompleteObjectAlignment = 12149 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 12150 } 12151 12152 // Check if the synthesized offset fulfills the alignment. 12153 if (Offset % ExpectedAlignment != 0 || 12154 // It may fulfill the offset it but the effective alignment may still be 12155 // lower than the expected expression alignment. 12156 CompleteObjectAlignment < ExpectedAlignment) { 12157 // If this happens, we want to determine a sensible culprit of this. 12158 // Intuitively, watching the chain of member expressions from right to 12159 // left, we start with the required alignment (as required by the field 12160 // type) but some packed attribute in that chain has reduced the alignment. 12161 // It may happen that another packed structure increases it again. But if 12162 // we are here such increase has not been enough. So pointing the first 12163 // FieldDecl that either is packed or else its RecordDecl is, 12164 // seems reasonable. 12165 FieldDecl *FD = nullptr; 12166 CharUnits Alignment; 12167 for (FieldDecl *FDI : ReverseMemberChain) { 12168 if (FDI->hasAttr<PackedAttr>() || 12169 FDI->getParent()->hasAttr<PackedAttr>()) { 12170 FD = FDI; 12171 Alignment = std::min( 12172 Context.getTypeAlignInChars(FD->getType()), 12173 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 12174 break; 12175 } 12176 } 12177 assert(FD && "We did not find a packed FieldDecl!"); 12178 Action(E, FD->getParent(), FD, Alignment); 12179 } 12180 } 12181 12182 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 12183 using namespace std::placeholders; 12184 RefersToMemberWithReducedAlignment( 12185 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 12186 _2, _3, _4)); 12187 } 12188 12189