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/APValue.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/AttrIterator.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclBase.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclarationName.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/Expr.h" 27 #include "clang/AST/ExprCXX.h" 28 #include "clang/AST/ExprObjC.h" 29 #include "clang/AST/ExprOpenMP.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/Stmt.h" 34 #include "clang/AST/TemplateBase.h" 35 #include "clang/AST/Type.h" 36 #include "clang/AST/TypeLoc.h" 37 #include "clang/AST/UnresolvedSet.h" 38 #include "clang/Analysis/Analyses/FormatString.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <functional> 94 #include <limits> 95 #include <string> 96 #include <tuple> 97 #include <utility> 98 99 using namespace clang; 100 using namespace sema; 101 102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 103 unsigned ByteNo) const { 104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 105 Context.getTargetInfo()); 106 } 107 108 /// Checks that a call expression's argument count is the desired number. 109 /// This is useful when doing custom type-checking. Returns true on error. 110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 111 unsigned argCount = call->getNumArgs(); 112 if (argCount == desiredArgCount) return false; 113 114 if (argCount < desiredArgCount) 115 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 116 << 0 /*function call*/ << desiredArgCount << argCount 117 << call->getSourceRange(); 118 119 // Highlight all the excess arguments. 120 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 121 call->getArg(argCount - 1)->getLocEnd()); 122 123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 124 << 0 /*function call*/ << desiredArgCount << argCount 125 << call->getArg(1)->getSourceRange(); 126 } 127 128 /// Check that the first argument to __builtin_annotation is an integer 129 /// and the second argument is a non-wide string literal. 130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 131 if (checkArgCount(S, TheCall, 2)) 132 return true; 133 134 // First argument should be an integer. 135 Expr *ValArg = TheCall->getArg(0); 136 QualType Ty = ValArg->getType(); 137 if (!Ty->isIntegerType()) { 138 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 139 << ValArg->getSourceRange(); 140 return true; 141 } 142 143 // Second argument should be a constant string. 144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 146 if (!Literal || !Literal->isAscii()) { 147 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 148 << StrArg->getSourceRange(); 149 return true; 150 } 151 152 TheCall->setType(Ty); 153 return false; 154 } 155 156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 157 // We need at least one argument. 158 if (TheCall->getNumArgs() < 1) { 159 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 160 << 0 << 1 << TheCall->getNumArgs() 161 << TheCall->getCallee()->getSourceRange(); 162 return true; 163 } 164 165 // All arguments should be wide string literals. 166 for (Expr *Arg : TheCall->arguments()) { 167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 168 if (!Literal || !Literal->isWide()) { 169 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str) 170 << Arg->getSourceRange(); 171 return true; 172 } 173 } 174 175 return false; 176 } 177 178 /// Check that the argument to __builtin_addressof is a glvalue, and set the 179 /// result type to the corresponding pointer type. 180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 181 if (checkArgCount(S, TheCall, 1)) 182 return true; 183 184 ExprResult Arg(TheCall->getArg(0)); 185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 186 if (ResultType.isNull()) 187 return true; 188 189 TheCall->setArg(0, Arg.get()); 190 TheCall->setType(ResultType); 191 return false; 192 } 193 194 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 195 if (checkArgCount(S, TheCall, 3)) 196 return true; 197 198 // First two arguments should be integers. 199 for (unsigned I = 0; I < 2; ++I) { 200 Expr *Arg = TheCall->getArg(I); 201 QualType Ty = Arg->getType(); 202 if (!Ty->isIntegerType()) { 203 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 204 << Ty << Arg->getSourceRange(); 205 return true; 206 } 207 } 208 209 // Third argument should be a pointer to a non-const integer. 210 // IRGen correctly handles volatile, restrict, and address spaces, and 211 // the other qualifiers aren't possible. 212 { 213 Expr *Arg = TheCall->getArg(2); 214 QualType Ty = Arg->getType(); 215 const auto *PtrTy = Ty->getAs<PointerType>(); 216 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 217 !PtrTy->getPointeeType().isConstQualified())) { 218 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 219 << Ty << Arg->getSourceRange(); 220 return true; 221 } 222 } 223 224 return false; 225 } 226 227 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 228 CallExpr *TheCall, unsigned SizeIdx, 229 unsigned DstSizeIdx) { 230 if (TheCall->getNumArgs() <= SizeIdx || 231 TheCall->getNumArgs() <= DstSizeIdx) 232 return; 233 234 const Expr *SizeArg = TheCall->getArg(SizeIdx); 235 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 236 237 llvm::APSInt Size, DstSize; 238 239 // find out if both sizes are known at compile time 240 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 241 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 242 return; 243 244 if (Size.ule(DstSize)) 245 return; 246 247 // confirmed overflow so generate the diagnostic. 248 IdentifierInfo *FnName = FDecl->getIdentifier(); 249 SourceLocation SL = TheCall->getLocStart(); 250 SourceRange SR = TheCall->getSourceRange(); 251 252 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 253 } 254 255 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 256 if (checkArgCount(S, BuiltinCall, 2)) 257 return true; 258 259 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 260 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 261 Expr *Call = BuiltinCall->getArg(0); 262 Expr *Chain = BuiltinCall->getArg(1); 263 264 if (Call->getStmtClass() != Stmt::CallExprClass) { 265 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 266 << Call->getSourceRange(); 267 return true; 268 } 269 270 auto CE = cast<CallExpr>(Call); 271 if (CE->getCallee()->getType()->isBlockPointerType()) { 272 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 273 << Call->getSourceRange(); 274 return true; 275 } 276 277 const Decl *TargetDecl = CE->getCalleeDecl(); 278 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 279 if (FD->getBuiltinID()) { 280 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 281 << Call->getSourceRange(); 282 return true; 283 } 284 285 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 286 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 287 << Call->getSourceRange(); 288 return true; 289 } 290 291 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 292 if (ChainResult.isInvalid()) 293 return true; 294 if (!ChainResult.get()->getType()->isPointerType()) { 295 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 296 << Chain->getSourceRange(); 297 return true; 298 } 299 300 QualType ReturnTy = CE->getCallReturnType(S.Context); 301 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 302 QualType BuiltinTy = S.Context.getFunctionType( 303 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 304 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 305 306 Builtin = 307 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 308 309 BuiltinCall->setType(CE->getType()); 310 BuiltinCall->setValueKind(CE->getValueKind()); 311 BuiltinCall->setObjectKind(CE->getObjectKind()); 312 BuiltinCall->setCallee(Builtin); 313 BuiltinCall->setArg(1, ChainResult.get()); 314 315 return false; 316 } 317 318 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 319 Scope::ScopeFlags NeededScopeFlags, 320 unsigned DiagID) { 321 // Scopes aren't available during instantiation. Fortunately, builtin 322 // functions cannot be template args so they cannot be formed through template 323 // instantiation. Therefore checking once during the parse is sufficient. 324 if (SemaRef.inTemplateInstantiation()) 325 return false; 326 327 Scope *S = SemaRef.getCurScope(); 328 while (S && !S->isSEHExceptScope()) 329 S = S->getParent(); 330 if (!S || !(S->getFlags() & NeededScopeFlags)) { 331 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 332 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 333 << DRE->getDecl()->getIdentifier(); 334 return true; 335 } 336 337 return false; 338 } 339 340 static inline bool isBlockPointer(Expr *Arg) { 341 return Arg->getType()->isBlockPointerType(); 342 } 343 344 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 345 /// void*, which is a requirement of device side enqueue. 346 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 347 const BlockPointerType *BPT = 348 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 349 ArrayRef<QualType> Params = 350 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 351 unsigned ArgCounter = 0; 352 bool IllegalParams = false; 353 // Iterate through the block parameters until either one is found that is not 354 // a local void*, or the block is valid. 355 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 356 I != E; ++I, ++ArgCounter) { 357 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 358 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 359 LangAS::opencl_local) { 360 // Get the location of the error. If a block literal has been passed 361 // (BlockExpr) then we can point straight to the offending argument, 362 // else we just point to the variable reference. 363 SourceLocation ErrorLoc; 364 if (isa<BlockExpr>(BlockArg)) { 365 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 366 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 367 } else if (isa<DeclRefExpr>(BlockArg)) { 368 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 369 } 370 S.Diag(ErrorLoc, 371 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 372 IllegalParams = true; 373 } 374 } 375 376 return IllegalParams; 377 } 378 379 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 380 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 381 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension) 382 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 383 return true; 384 } 385 return false; 386 } 387 388 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 389 if (checkArgCount(S, TheCall, 2)) 390 return true; 391 392 if (checkOpenCLSubgroupExt(S, TheCall)) 393 return true; 394 395 // First argument is an ndrange_t type. 396 Expr *NDRangeArg = TheCall->getArg(0); 397 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 398 S.Diag(NDRangeArg->getLocStart(), 399 diag::err_opencl_builtin_expected_type) 400 << TheCall->getDirectCallee() << "'ndrange_t'"; 401 return true; 402 } 403 404 Expr *BlockArg = TheCall->getArg(1); 405 if (!isBlockPointer(BlockArg)) { 406 S.Diag(BlockArg->getLocStart(), 407 diag::err_opencl_builtin_expected_type) 408 << TheCall->getDirectCallee() << "block"; 409 return true; 410 } 411 return checkOpenCLBlockArgs(S, BlockArg); 412 } 413 414 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 415 /// get_kernel_work_group_size 416 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 417 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 418 if (checkArgCount(S, TheCall, 1)) 419 return true; 420 421 Expr *BlockArg = TheCall->getArg(0); 422 if (!isBlockPointer(BlockArg)) { 423 S.Diag(BlockArg->getLocStart(), 424 diag::err_opencl_builtin_expected_type) 425 << TheCall->getDirectCallee() << "block"; 426 return true; 427 } 428 return checkOpenCLBlockArgs(S, BlockArg); 429 } 430 431 /// Diagnose integer type and any valid implicit conversion to it. 432 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 433 const QualType &IntType); 434 435 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 436 unsigned Start, unsigned End) { 437 bool IllegalParams = false; 438 for (unsigned I = Start; I <= End; ++I) 439 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 440 S.Context.getSizeType()); 441 return IllegalParams; 442 } 443 444 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 445 /// 'local void*' parameter of passed block. 446 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 447 Expr *BlockArg, 448 unsigned NumNonVarArgs) { 449 const BlockPointerType *BPT = 450 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 451 unsigned NumBlockParams = 452 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 453 unsigned TotalNumArgs = TheCall->getNumArgs(); 454 455 // For each argument passed to the block, a corresponding uint needs to 456 // be passed to describe the size of the local memory. 457 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 458 S.Diag(TheCall->getLocStart(), 459 diag::err_opencl_enqueue_kernel_local_size_args); 460 return true; 461 } 462 463 // Check that the sizes of the local memory are specified by integers. 464 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 465 TotalNumArgs - 1); 466 } 467 468 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 469 /// overload formats specified in Table 6.13.17.1. 470 /// int enqueue_kernel(queue_t queue, 471 /// kernel_enqueue_flags_t flags, 472 /// const ndrange_t ndrange, 473 /// void (^block)(void)) 474 /// int enqueue_kernel(queue_t queue, 475 /// kernel_enqueue_flags_t flags, 476 /// const ndrange_t ndrange, 477 /// uint num_events_in_wait_list, 478 /// clk_event_t *event_wait_list, 479 /// clk_event_t *event_ret, 480 /// void (^block)(void)) 481 /// int enqueue_kernel(queue_t queue, 482 /// kernel_enqueue_flags_t flags, 483 /// const ndrange_t ndrange, 484 /// void (^block)(local void*, ...), 485 /// uint size0, ...) 486 /// int enqueue_kernel(queue_t queue, 487 /// kernel_enqueue_flags_t flags, 488 /// const ndrange_t ndrange, 489 /// uint num_events_in_wait_list, 490 /// clk_event_t *event_wait_list, 491 /// clk_event_t *event_ret, 492 /// void (^block)(local void*, ...), 493 /// uint size0, ...) 494 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 495 unsigned NumArgs = TheCall->getNumArgs(); 496 497 if (NumArgs < 4) { 498 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 499 return true; 500 } 501 502 Expr *Arg0 = TheCall->getArg(0); 503 Expr *Arg1 = TheCall->getArg(1); 504 Expr *Arg2 = TheCall->getArg(2); 505 Expr *Arg3 = TheCall->getArg(3); 506 507 // First argument always needs to be a queue_t type. 508 if (!Arg0->getType()->isQueueT()) { 509 S.Diag(TheCall->getArg(0)->getLocStart(), 510 diag::err_opencl_builtin_expected_type) 511 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 512 return true; 513 } 514 515 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 516 if (!Arg1->getType()->isIntegerType()) { 517 S.Diag(TheCall->getArg(1)->getLocStart(), 518 diag::err_opencl_builtin_expected_type) 519 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 520 return true; 521 } 522 523 // Third argument is always an ndrange_t type. 524 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 525 S.Diag(TheCall->getArg(2)->getLocStart(), 526 diag::err_opencl_builtin_expected_type) 527 << TheCall->getDirectCallee() << "'ndrange_t'"; 528 return true; 529 } 530 531 // With four arguments, there is only one form that the function could be 532 // called in: no events and no variable arguments. 533 if (NumArgs == 4) { 534 // check that the last argument is the right block type. 535 if (!isBlockPointer(Arg3)) { 536 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type) 537 << TheCall->getDirectCallee() << "block"; 538 return true; 539 } 540 // we have a block type, check the prototype 541 const BlockPointerType *BPT = 542 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 543 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 544 S.Diag(Arg3->getLocStart(), 545 diag::err_opencl_enqueue_kernel_blocks_no_args); 546 return true; 547 } 548 return false; 549 } 550 // we can have block + varargs. 551 if (isBlockPointer(Arg3)) 552 return (checkOpenCLBlockArgs(S, Arg3) || 553 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 554 // last two cases with either exactly 7 args or 7 args and varargs. 555 if (NumArgs >= 7) { 556 // check common block argument. 557 Expr *Arg6 = TheCall->getArg(6); 558 if (!isBlockPointer(Arg6)) { 559 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type) 560 << TheCall->getDirectCallee() << "block"; 561 return true; 562 } 563 if (checkOpenCLBlockArgs(S, Arg6)) 564 return true; 565 566 // Forth argument has to be any integer type. 567 if (!Arg3->getType()->isIntegerType()) { 568 S.Diag(TheCall->getArg(3)->getLocStart(), 569 diag::err_opencl_builtin_expected_type) 570 << TheCall->getDirectCallee() << "integer"; 571 return true; 572 } 573 // check remaining common arguments. 574 Expr *Arg4 = TheCall->getArg(4); 575 Expr *Arg5 = TheCall->getArg(5); 576 577 // Fifth argument is always passed as a pointer to clk_event_t. 578 if (!Arg4->isNullPointerConstant(S.Context, 579 Expr::NPC_ValueDependentIsNotNull) && 580 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 581 S.Diag(TheCall->getArg(4)->getLocStart(), 582 diag::err_opencl_builtin_expected_type) 583 << TheCall->getDirectCallee() 584 << S.Context.getPointerType(S.Context.OCLClkEventTy); 585 return true; 586 } 587 588 // Sixth argument is always passed as a pointer to clk_event_t. 589 if (!Arg5->isNullPointerConstant(S.Context, 590 Expr::NPC_ValueDependentIsNotNull) && 591 !(Arg5->getType()->isPointerType() && 592 Arg5->getType()->getPointeeType()->isClkEventT())) { 593 S.Diag(TheCall->getArg(5)->getLocStart(), 594 diag::err_opencl_builtin_expected_type) 595 << TheCall->getDirectCallee() 596 << S.Context.getPointerType(S.Context.OCLClkEventTy); 597 return true; 598 } 599 600 if (NumArgs == 7) 601 return false; 602 603 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 604 } 605 606 // None of the specific case has been detected, give generic error 607 S.Diag(TheCall->getLocStart(), 608 diag::err_opencl_enqueue_kernel_incorrect_args); 609 return true; 610 } 611 612 /// Returns OpenCL access qual. 613 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 614 return D->getAttr<OpenCLAccessAttr>(); 615 } 616 617 /// Returns true if pipe element type is different from the pointer. 618 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 619 const Expr *Arg0 = Call->getArg(0); 620 // First argument type should always be pipe. 621 if (!Arg0->getType()->isPipeType()) { 622 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 623 << Call->getDirectCallee() << Arg0->getSourceRange(); 624 return true; 625 } 626 OpenCLAccessAttr *AccessQual = 627 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 628 // Validates the access qualifier is compatible with the call. 629 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 630 // read_only and write_only, and assumed to be read_only if no qualifier is 631 // specified. 632 switch (Call->getDirectCallee()->getBuiltinID()) { 633 case Builtin::BIread_pipe: 634 case Builtin::BIreserve_read_pipe: 635 case Builtin::BIcommit_read_pipe: 636 case Builtin::BIwork_group_reserve_read_pipe: 637 case Builtin::BIsub_group_reserve_read_pipe: 638 case Builtin::BIwork_group_commit_read_pipe: 639 case Builtin::BIsub_group_commit_read_pipe: 640 if (!(!AccessQual || AccessQual->isReadOnly())) { 641 S.Diag(Arg0->getLocStart(), 642 diag::err_opencl_builtin_pipe_invalid_access_modifier) 643 << "read_only" << Arg0->getSourceRange(); 644 return true; 645 } 646 break; 647 case Builtin::BIwrite_pipe: 648 case Builtin::BIreserve_write_pipe: 649 case Builtin::BIcommit_write_pipe: 650 case Builtin::BIwork_group_reserve_write_pipe: 651 case Builtin::BIsub_group_reserve_write_pipe: 652 case Builtin::BIwork_group_commit_write_pipe: 653 case Builtin::BIsub_group_commit_write_pipe: 654 if (!(AccessQual && AccessQual->isWriteOnly())) { 655 S.Diag(Arg0->getLocStart(), 656 diag::err_opencl_builtin_pipe_invalid_access_modifier) 657 << "write_only" << Arg0->getSourceRange(); 658 return true; 659 } 660 break; 661 default: 662 break; 663 } 664 return false; 665 } 666 667 /// Returns true if pipe element type is different from the pointer. 668 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 669 const Expr *Arg0 = Call->getArg(0); 670 const Expr *ArgIdx = Call->getArg(Idx); 671 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 672 const QualType EltTy = PipeTy->getElementType(); 673 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 674 // The Idx argument should be a pointer and the type of the pointer and 675 // the type of pipe element should also be the same. 676 if (!ArgTy || 677 !S.Context.hasSameType( 678 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 679 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 680 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 681 << ArgIdx->getType() << ArgIdx->getSourceRange(); 682 return true; 683 } 684 return false; 685 } 686 687 // \brief Performs semantic analysis for the read/write_pipe call. 688 // \param S Reference to the semantic analyzer. 689 // \param Call A pointer to the builtin call. 690 // \return True if a semantic error has been found, false otherwise. 691 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 692 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 693 // functions have two forms. 694 switch (Call->getNumArgs()) { 695 case 2: 696 if (checkOpenCLPipeArg(S, Call)) 697 return true; 698 // The call with 2 arguments should be 699 // read/write_pipe(pipe T, T*). 700 // Check packet type T. 701 if (checkOpenCLPipePacketType(S, Call, 1)) 702 return true; 703 break; 704 705 case 4: { 706 if (checkOpenCLPipeArg(S, Call)) 707 return true; 708 // The call with 4 arguments should be 709 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 710 // Check reserve_id_t. 711 if (!Call->getArg(1)->getType()->isReserveIDT()) { 712 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 713 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 714 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 715 return true; 716 } 717 718 // Check the index. 719 const Expr *Arg2 = Call->getArg(2); 720 if (!Arg2->getType()->isIntegerType() && 721 !Arg2->getType()->isUnsignedIntegerType()) { 722 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 723 << Call->getDirectCallee() << S.Context.UnsignedIntTy 724 << Arg2->getType() << Arg2->getSourceRange(); 725 return true; 726 } 727 728 // Check packet type T. 729 if (checkOpenCLPipePacketType(S, Call, 3)) 730 return true; 731 } break; 732 default: 733 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 734 << Call->getDirectCallee() << Call->getSourceRange(); 735 return true; 736 } 737 738 return false; 739 } 740 741 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 742 // /_}reserve_{read/write}_pipe 743 // \param S Reference to the semantic analyzer. 744 // \param Call The call to the builtin function to be analyzed. 745 // \return True if a semantic error was found, false otherwise. 746 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 747 if (checkArgCount(S, Call, 2)) 748 return true; 749 750 if (checkOpenCLPipeArg(S, Call)) 751 return true; 752 753 // Check the reserve size. 754 if (!Call->getArg(1)->getType()->isIntegerType() && 755 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 756 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 757 << Call->getDirectCallee() << S.Context.UnsignedIntTy 758 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 759 return true; 760 } 761 762 // Since return type of reserve_read/write_pipe built-in function is 763 // reserve_id_t, which is not defined in the builtin def file , we used int 764 // as return type and need to override the return type of these functions. 765 Call->setType(S.Context.OCLReserveIDTy); 766 767 return false; 768 } 769 770 // \brief Performs a semantic analysis on {work_group_/sub_group_ 771 // /_}commit_{read/write}_pipe 772 // \param S Reference to the semantic analyzer. 773 // \param Call The call to the builtin function to be analyzed. 774 // \return True if a semantic error was found, false otherwise. 775 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 776 if (checkArgCount(S, Call, 2)) 777 return true; 778 779 if (checkOpenCLPipeArg(S, Call)) 780 return true; 781 782 // Check reserve_id_t. 783 if (!Call->getArg(1)->getType()->isReserveIDT()) { 784 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 785 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 786 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 787 return true; 788 } 789 790 return false; 791 } 792 793 // \brief Performs a semantic analysis on the call to built-in Pipe 794 // Query Functions. 795 // \param S Reference to the semantic analyzer. 796 // \param Call The call to the builtin function to be analyzed. 797 // \return True if a semantic error was found, false otherwise. 798 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 799 if (checkArgCount(S, Call, 1)) 800 return true; 801 802 if (!Call->getArg(0)->getType()->isPipeType()) { 803 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 804 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 805 return true; 806 } 807 808 return false; 809 } 810 811 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 812 // \brief Performs semantic analysis for the to_global/local/private call. 813 // \param S Reference to the semantic analyzer. 814 // \param BuiltinID ID of the builtin function. 815 // \param Call A pointer to the builtin call. 816 // \return True if a semantic error has been found, false otherwise. 817 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 818 CallExpr *Call) { 819 if (Call->getNumArgs() != 1) { 820 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 821 << Call->getDirectCallee() << Call->getSourceRange(); 822 return true; 823 } 824 825 auto RT = Call->getArg(0)->getType(); 826 if (!RT->isPointerType() || RT->getPointeeType() 827 .getAddressSpace() == LangAS::opencl_constant) { 828 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 829 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 830 return true; 831 } 832 833 RT = RT->getPointeeType(); 834 auto Qual = RT.getQualifiers(); 835 switch (BuiltinID) { 836 case Builtin::BIto_global: 837 Qual.setAddressSpace(LangAS::opencl_global); 838 break; 839 case Builtin::BIto_local: 840 Qual.setAddressSpace(LangAS::opencl_local); 841 break; 842 case Builtin::BIto_private: 843 Qual.setAddressSpace(LangAS::opencl_private); 844 break; 845 default: 846 llvm_unreachable("Invalid builtin function"); 847 } 848 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 849 RT.getUnqualifiedType(), Qual))); 850 851 return false; 852 } 853 854 ExprResult 855 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 856 CallExpr *TheCall) { 857 ExprResult TheCallResult(TheCall); 858 859 // Find out if any arguments are required to be integer constant expressions. 860 unsigned ICEArguments = 0; 861 ASTContext::GetBuiltinTypeError Error; 862 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 863 if (Error != ASTContext::GE_None) 864 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 865 866 // If any arguments are required to be ICE's, check and diagnose. 867 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 868 // Skip arguments not required to be ICE's. 869 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 870 871 llvm::APSInt Result; 872 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 873 return true; 874 ICEArguments &= ~(1 << ArgNo); 875 } 876 877 switch (BuiltinID) { 878 case Builtin::BI__builtin___CFStringMakeConstantString: 879 assert(TheCall->getNumArgs() == 1 && 880 "Wrong # arguments to builtin CFStringMakeConstantString"); 881 if (CheckObjCString(TheCall->getArg(0))) 882 return ExprError(); 883 break; 884 case Builtin::BI__builtin_ms_va_start: 885 case Builtin::BI__builtin_stdarg_start: 886 case Builtin::BI__builtin_va_start: 887 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 888 return ExprError(); 889 break; 890 case Builtin::BI__va_start: { 891 switch (Context.getTargetInfo().getTriple().getArch()) { 892 case llvm::Triple::arm: 893 case llvm::Triple::thumb: 894 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 895 return ExprError(); 896 break; 897 default: 898 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 899 return ExprError(); 900 break; 901 } 902 break; 903 } 904 case Builtin::BI__builtin_isgreater: 905 case Builtin::BI__builtin_isgreaterequal: 906 case Builtin::BI__builtin_isless: 907 case Builtin::BI__builtin_islessequal: 908 case Builtin::BI__builtin_islessgreater: 909 case Builtin::BI__builtin_isunordered: 910 if (SemaBuiltinUnorderedCompare(TheCall)) 911 return ExprError(); 912 break; 913 case Builtin::BI__builtin_fpclassify: 914 if (SemaBuiltinFPClassification(TheCall, 6)) 915 return ExprError(); 916 break; 917 case Builtin::BI__builtin_isfinite: 918 case Builtin::BI__builtin_isinf: 919 case Builtin::BI__builtin_isinf_sign: 920 case Builtin::BI__builtin_isnan: 921 case Builtin::BI__builtin_isnormal: 922 if (SemaBuiltinFPClassification(TheCall, 1)) 923 return ExprError(); 924 break; 925 case Builtin::BI__builtin_shufflevector: 926 return SemaBuiltinShuffleVector(TheCall); 927 // TheCall will be freed by the smart pointer here, but that's fine, since 928 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 929 case Builtin::BI__builtin_prefetch: 930 if (SemaBuiltinPrefetch(TheCall)) 931 return ExprError(); 932 break; 933 case Builtin::BI__builtin_alloca_with_align: 934 if (SemaBuiltinAllocaWithAlign(TheCall)) 935 return ExprError(); 936 break; 937 case Builtin::BI__assume: 938 case Builtin::BI__builtin_assume: 939 if (SemaBuiltinAssume(TheCall)) 940 return ExprError(); 941 break; 942 case Builtin::BI__builtin_assume_aligned: 943 if (SemaBuiltinAssumeAligned(TheCall)) 944 return ExprError(); 945 break; 946 case Builtin::BI__builtin_object_size: 947 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 948 return ExprError(); 949 break; 950 case Builtin::BI__builtin_longjmp: 951 if (SemaBuiltinLongjmp(TheCall)) 952 return ExprError(); 953 break; 954 case Builtin::BI__builtin_setjmp: 955 if (SemaBuiltinSetjmp(TheCall)) 956 return ExprError(); 957 break; 958 case Builtin::BI_setjmp: 959 case Builtin::BI_setjmpex: 960 if (checkArgCount(*this, TheCall, 1)) 961 return true; 962 break; 963 case Builtin::BI__builtin_classify_type: 964 if (checkArgCount(*this, TheCall, 1)) return true; 965 TheCall->setType(Context.IntTy); 966 break; 967 case Builtin::BI__builtin_constant_p: 968 if (checkArgCount(*this, TheCall, 1)) return true; 969 TheCall->setType(Context.IntTy); 970 break; 971 case Builtin::BI__sync_fetch_and_add: 972 case Builtin::BI__sync_fetch_and_add_1: 973 case Builtin::BI__sync_fetch_and_add_2: 974 case Builtin::BI__sync_fetch_and_add_4: 975 case Builtin::BI__sync_fetch_and_add_8: 976 case Builtin::BI__sync_fetch_and_add_16: 977 case Builtin::BI__sync_fetch_and_sub: 978 case Builtin::BI__sync_fetch_and_sub_1: 979 case Builtin::BI__sync_fetch_and_sub_2: 980 case Builtin::BI__sync_fetch_and_sub_4: 981 case Builtin::BI__sync_fetch_and_sub_8: 982 case Builtin::BI__sync_fetch_and_sub_16: 983 case Builtin::BI__sync_fetch_and_or: 984 case Builtin::BI__sync_fetch_and_or_1: 985 case Builtin::BI__sync_fetch_and_or_2: 986 case Builtin::BI__sync_fetch_and_or_4: 987 case Builtin::BI__sync_fetch_and_or_8: 988 case Builtin::BI__sync_fetch_and_or_16: 989 case Builtin::BI__sync_fetch_and_and: 990 case Builtin::BI__sync_fetch_and_and_1: 991 case Builtin::BI__sync_fetch_and_and_2: 992 case Builtin::BI__sync_fetch_and_and_4: 993 case Builtin::BI__sync_fetch_and_and_8: 994 case Builtin::BI__sync_fetch_and_and_16: 995 case Builtin::BI__sync_fetch_and_xor: 996 case Builtin::BI__sync_fetch_and_xor_1: 997 case Builtin::BI__sync_fetch_and_xor_2: 998 case Builtin::BI__sync_fetch_and_xor_4: 999 case Builtin::BI__sync_fetch_and_xor_8: 1000 case Builtin::BI__sync_fetch_and_xor_16: 1001 case Builtin::BI__sync_fetch_and_nand: 1002 case Builtin::BI__sync_fetch_and_nand_1: 1003 case Builtin::BI__sync_fetch_and_nand_2: 1004 case Builtin::BI__sync_fetch_and_nand_4: 1005 case Builtin::BI__sync_fetch_and_nand_8: 1006 case Builtin::BI__sync_fetch_and_nand_16: 1007 case Builtin::BI__sync_add_and_fetch: 1008 case Builtin::BI__sync_add_and_fetch_1: 1009 case Builtin::BI__sync_add_and_fetch_2: 1010 case Builtin::BI__sync_add_and_fetch_4: 1011 case Builtin::BI__sync_add_and_fetch_8: 1012 case Builtin::BI__sync_add_and_fetch_16: 1013 case Builtin::BI__sync_sub_and_fetch: 1014 case Builtin::BI__sync_sub_and_fetch_1: 1015 case Builtin::BI__sync_sub_and_fetch_2: 1016 case Builtin::BI__sync_sub_and_fetch_4: 1017 case Builtin::BI__sync_sub_and_fetch_8: 1018 case Builtin::BI__sync_sub_and_fetch_16: 1019 case Builtin::BI__sync_and_and_fetch: 1020 case Builtin::BI__sync_and_and_fetch_1: 1021 case Builtin::BI__sync_and_and_fetch_2: 1022 case Builtin::BI__sync_and_and_fetch_4: 1023 case Builtin::BI__sync_and_and_fetch_8: 1024 case Builtin::BI__sync_and_and_fetch_16: 1025 case Builtin::BI__sync_or_and_fetch: 1026 case Builtin::BI__sync_or_and_fetch_1: 1027 case Builtin::BI__sync_or_and_fetch_2: 1028 case Builtin::BI__sync_or_and_fetch_4: 1029 case Builtin::BI__sync_or_and_fetch_8: 1030 case Builtin::BI__sync_or_and_fetch_16: 1031 case Builtin::BI__sync_xor_and_fetch: 1032 case Builtin::BI__sync_xor_and_fetch_1: 1033 case Builtin::BI__sync_xor_and_fetch_2: 1034 case Builtin::BI__sync_xor_and_fetch_4: 1035 case Builtin::BI__sync_xor_and_fetch_8: 1036 case Builtin::BI__sync_xor_and_fetch_16: 1037 case Builtin::BI__sync_nand_and_fetch: 1038 case Builtin::BI__sync_nand_and_fetch_1: 1039 case Builtin::BI__sync_nand_and_fetch_2: 1040 case Builtin::BI__sync_nand_and_fetch_4: 1041 case Builtin::BI__sync_nand_and_fetch_8: 1042 case Builtin::BI__sync_nand_and_fetch_16: 1043 case Builtin::BI__sync_val_compare_and_swap: 1044 case Builtin::BI__sync_val_compare_and_swap_1: 1045 case Builtin::BI__sync_val_compare_and_swap_2: 1046 case Builtin::BI__sync_val_compare_and_swap_4: 1047 case Builtin::BI__sync_val_compare_and_swap_8: 1048 case Builtin::BI__sync_val_compare_and_swap_16: 1049 case Builtin::BI__sync_bool_compare_and_swap: 1050 case Builtin::BI__sync_bool_compare_and_swap_1: 1051 case Builtin::BI__sync_bool_compare_and_swap_2: 1052 case Builtin::BI__sync_bool_compare_and_swap_4: 1053 case Builtin::BI__sync_bool_compare_and_swap_8: 1054 case Builtin::BI__sync_bool_compare_and_swap_16: 1055 case Builtin::BI__sync_lock_test_and_set: 1056 case Builtin::BI__sync_lock_test_and_set_1: 1057 case Builtin::BI__sync_lock_test_and_set_2: 1058 case Builtin::BI__sync_lock_test_and_set_4: 1059 case Builtin::BI__sync_lock_test_and_set_8: 1060 case Builtin::BI__sync_lock_test_and_set_16: 1061 case Builtin::BI__sync_lock_release: 1062 case Builtin::BI__sync_lock_release_1: 1063 case Builtin::BI__sync_lock_release_2: 1064 case Builtin::BI__sync_lock_release_4: 1065 case Builtin::BI__sync_lock_release_8: 1066 case Builtin::BI__sync_lock_release_16: 1067 case Builtin::BI__sync_swap: 1068 case Builtin::BI__sync_swap_1: 1069 case Builtin::BI__sync_swap_2: 1070 case Builtin::BI__sync_swap_4: 1071 case Builtin::BI__sync_swap_8: 1072 case Builtin::BI__sync_swap_16: 1073 return SemaBuiltinAtomicOverloaded(TheCallResult); 1074 case Builtin::BI__builtin_nontemporal_load: 1075 case Builtin::BI__builtin_nontemporal_store: 1076 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1077 #define BUILTIN(ID, TYPE, ATTRS) 1078 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1079 case Builtin::BI##ID: \ 1080 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1081 #include "clang/Basic/Builtins.def" 1082 case Builtin::BI__annotation: 1083 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1084 return ExprError(); 1085 break; 1086 case Builtin::BI__builtin_annotation: 1087 if (SemaBuiltinAnnotation(*this, TheCall)) 1088 return ExprError(); 1089 break; 1090 case Builtin::BI__builtin_addressof: 1091 if (SemaBuiltinAddressof(*this, TheCall)) 1092 return ExprError(); 1093 break; 1094 case Builtin::BI__builtin_add_overflow: 1095 case Builtin::BI__builtin_sub_overflow: 1096 case Builtin::BI__builtin_mul_overflow: 1097 if (SemaBuiltinOverflow(*this, TheCall)) 1098 return ExprError(); 1099 break; 1100 case Builtin::BI__builtin_operator_new: 1101 case Builtin::BI__builtin_operator_delete: { 1102 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1103 ExprResult Res = 1104 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1105 if (Res.isInvalid()) 1106 CorrectDelayedTyposInExpr(TheCallResult.get()); 1107 return Res; 1108 } 1109 case Builtin::BI__builtin_dump_struct: { 1110 // We first want to ensure we are called with 2 arguments 1111 if (checkArgCount(*this, TheCall, 2)) 1112 return ExprError(); 1113 // Ensure that the first argument is of type 'struct XX *' 1114 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1115 const QualType PtrArgType = PtrArg->getType(); 1116 if (!PtrArgType->isPointerType() || 1117 !PtrArgType->getPointeeType()->isRecordType()) { 1118 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1119 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1120 << "structure pointer"; 1121 return ExprError(); 1122 } 1123 1124 // Ensure that the second argument is of type 'FunctionType' 1125 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1126 const QualType FnPtrArgType = FnPtrArg->getType(); 1127 if (!FnPtrArgType->isPointerType()) { 1128 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1129 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1130 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1131 return ExprError(); 1132 } 1133 1134 const auto *FuncType = 1135 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1136 1137 if (!FuncType) { 1138 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1139 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1140 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1141 return ExprError(); 1142 } 1143 1144 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1145 if (!FT->getNumParams()) { 1146 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1147 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1148 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1149 return ExprError(); 1150 } 1151 QualType PT = FT->getParamType(0); 1152 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1153 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1154 !PT->getPointeeType().isConstQualified()) { 1155 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1156 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1157 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1158 return ExprError(); 1159 } 1160 } 1161 1162 TheCall->setType(Context.IntTy); 1163 break; 1164 } 1165 1166 // check secure string manipulation functions where overflows 1167 // are detectable at compile time 1168 case Builtin::BI__builtin___memcpy_chk: 1169 case Builtin::BI__builtin___memmove_chk: 1170 case Builtin::BI__builtin___memset_chk: 1171 case Builtin::BI__builtin___strlcat_chk: 1172 case Builtin::BI__builtin___strlcpy_chk: 1173 case Builtin::BI__builtin___strncat_chk: 1174 case Builtin::BI__builtin___strncpy_chk: 1175 case Builtin::BI__builtin___stpncpy_chk: 1176 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1177 break; 1178 case Builtin::BI__builtin___memccpy_chk: 1179 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1180 break; 1181 case Builtin::BI__builtin___snprintf_chk: 1182 case Builtin::BI__builtin___vsnprintf_chk: 1183 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1184 break; 1185 case Builtin::BI__builtin_call_with_static_chain: 1186 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1187 return ExprError(); 1188 break; 1189 case Builtin::BI__exception_code: 1190 case Builtin::BI_exception_code: 1191 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1192 diag::err_seh___except_block)) 1193 return ExprError(); 1194 break; 1195 case Builtin::BI__exception_info: 1196 case Builtin::BI_exception_info: 1197 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1198 diag::err_seh___except_filter)) 1199 return ExprError(); 1200 break; 1201 case Builtin::BI__GetExceptionInfo: 1202 if (checkArgCount(*this, TheCall, 1)) 1203 return ExprError(); 1204 1205 if (CheckCXXThrowOperand( 1206 TheCall->getLocStart(), 1207 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1208 TheCall)) 1209 return ExprError(); 1210 1211 TheCall->setType(Context.VoidPtrTy); 1212 break; 1213 // OpenCL v2.0, s6.13.16 - Pipe functions 1214 case Builtin::BIread_pipe: 1215 case Builtin::BIwrite_pipe: 1216 // Since those two functions are declared with var args, we need a semantic 1217 // check for the argument. 1218 if (SemaBuiltinRWPipe(*this, TheCall)) 1219 return ExprError(); 1220 TheCall->setType(Context.IntTy); 1221 break; 1222 case Builtin::BIreserve_read_pipe: 1223 case Builtin::BIreserve_write_pipe: 1224 case Builtin::BIwork_group_reserve_read_pipe: 1225 case Builtin::BIwork_group_reserve_write_pipe: 1226 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1227 return ExprError(); 1228 break; 1229 case Builtin::BIsub_group_reserve_read_pipe: 1230 case Builtin::BIsub_group_reserve_write_pipe: 1231 if (checkOpenCLSubgroupExt(*this, TheCall) || 1232 SemaBuiltinReserveRWPipe(*this, TheCall)) 1233 return ExprError(); 1234 break; 1235 case Builtin::BIcommit_read_pipe: 1236 case Builtin::BIcommit_write_pipe: 1237 case Builtin::BIwork_group_commit_read_pipe: 1238 case Builtin::BIwork_group_commit_write_pipe: 1239 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1240 return ExprError(); 1241 break; 1242 case Builtin::BIsub_group_commit_read_pipe: 1243 case Builtin::BIsub_group_commit_write_pipe: 1244 if (checkOpenCLSubgroupExt(*this, TheCall) || 1245 SemaBuiltinCommitRWPipe(*this, TheCall)) 1246 return ExprError(); 1247 break; 1248 case Builtin::BIget_pipe_num_packets: 1249 case Builtin::BIget_pipe_max_packets: 1250 if (SemaBuiltinPipePackets(*this, TheCall)) 1251 return ExprError(); 1252 TheCall->setType(Context.UnsignedIntTy); 1253 break; 1254 case Builtin::BIto_global: 1255 case Builtin::BIto_local: 1256 case Builtin::BIto_private: 1257 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1258 return ExprError(); 1259 break; 1260 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1261 case Builtin::BIenqueue_kernel: 1262 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1263 return ExprError(); 1264 break; 1265 case Builtin::BIget_kernel_work_group_size: 1266 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1267 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1268 return ExprError(); 1269 break; 1270 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1271 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1272 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1273 return ExprError(); 1274 break; 1275 case Builtin::BI__builtin_os_log_format: 1276 case Builtin::BI__builtin_os_log_format_buffer_size: 1277 if (SemaBuiltinOSLogFormat(TheCall)) 1278 return ExprError(); 1279 break; 1280 } 1281 1282 // Since the target specific builtins for each arch overlap, only check those 1283 // of the arch we are compiling for. 1284 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1285 switch (Context.getTargetInfo().getTriple().getArch()) { 1286 case llvm::Triple::arm: 1287 case llvm::Triple::armeb: 1288 case llvm::Triple::thumb: 1289 case llvm::Triple::thumbeb: 1290 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1291 return ExprError(); 1292 break; 1293 case llvm::Triple::aarch64: 1294 case llvm::Triple::aarch64_be: 1295 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1296 return ExprError(); 1297 break; 1298 case llvm::Triple::mips: 1299 case llvm::Triple::mipsel: 1300 case llvm::Triple::mips64: 1301 case llvm::Triple::mips64el: 1302 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1303 return ExprError(); 1304 break; 1305 case llvm::Triple::systemz: 1306 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1307 return ExprError(); 1308 break; 1309 case llvm::Triple::x86: 1310 case llvm::Triple::x86_64: 1311 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1312 return ExprError(); 1313 break; 1314 case llvm::Triple::ppc: 1315 case llvm::Triple::ppc64: 1316 case llvm::Triple::ppc64le: 1317 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1318 return ExprError(); 1319 break; 1320 default: 1321 break; 1322 } 1323 } 1324 1325 return TheCallResult; 1326 } 1327 1328 // Get the valid immediate range for the specified NEON type code. 1329 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1330 NeonTypeFlags Type(t); 1331 int IsQuad = ForceQuad ? true : Type.isQuad(); 1332 switch (Type.getEltType()) { 1333 case NeonTypeFlags::Int8: 1334 case NeonTypeFlags::Poly8: 1335 return shift ? 7 : (8 << IsQuad) - 1; 1336 case NeonTypeFlags::Int16: 1337 case NeonTypeFlags::Poly16: 1338 return shift ? 15 : (4 << IsQuad) - 1; 1339 case NeonTypeFlags::Int32: 1340 return shift ? 31 : (2 << IsQuad) - 1; 1341 case NeonTypeFlags::Int64: 1342 case NeonTypeFlags::Poly64: 1343 return shift ? 63 : (1 << IsQuad) - 1; 1344 case NeonTypeFlags::Poly128: 1345 return shift ? 127 : (1 << IsQuad) - 1; 1346 case NeonTypeFlags::Float16: 1347 assert(!shift && "cannot shift float types!"); 1348 return (4 << IsQuad) - 1; 1349 case NeonTypeFlags::Float32: 1350 assert(!shift && "cannot shift float types!"); 1351 return (2 << IsQuad) - 1; 1352 case NeonTypeFlags::Float64: 1353 assert(!shift && "cannot shift float types!"); 1354 return (1 << IsQuad) - 1; 1355 } 1356 llvm_unreachable("Invalid NeonTypeFlag!"); 1357 } 1358 1359 /// getNeonEltType - Return the QualType corresponding to the elements of 1360 /// the vector type specified by the NeonTypeFlags. This is used to check 1361 /// the pointer arguments for Neon load/store intrinsics. 1362 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1363 bool IsPolyUnsigned, bool IsInt64Long) { 1364 switch (Flags.getEltType()) { 1365 case NeonTypeFlags::Int8: 1366 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1367 case NeonTypeFlags::Int16: 1368 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1369 case NeonTypeFlags::Int32: 1370 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1371 case NeonTypeFlags::Int64: 1372 if (IsInt64Long) 1373 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1374 else 1375 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1376 : Context.LongLongTy; 1377 case NeonTypeFlags::Poly8: 1378 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1379 case NeonTypeFlags::Poly16: 1380 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1381 case NeonTypeFlags::Poly64: 1382 if (IsInt64Long) 1383 return Context.UnsignedLongTy; 1384 else 1385 return Context.UnsignedLongLongTy; 1386 case NeonTypeFlags::Poly128: 1387 break; 1388 case NeonTypeFlags::Float16: 1389 return Context.HalfTy; 1390 case NeonTypeFlags::Float32: 1391 return Context.FloatTy; 1392 case NeonTypeFlags::Float64: 1393 return Context.DoubleTy; 1394 } 1395 llvm_unreachable("Invalid NeonTypeFlag!"); 1396 } 1397 1398 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1399 llvm::APSInt Result; 1400 uint64_t mask = 0; 1401 unsigned TV = 0; 1402 int PtrArgNum = -1; 1403 bool HasConstPtr = false; 1404 switch (BuiltinID) { 1405 #define GET_NEON_OVERLOAD_CHECK 1406 #include "clang/Basic/arm_neon.inc" 1407 #include "clang/Basic/arm_fp16.inc" 1408 #undef GET_NEON_OVERLOAD_CHECK 1409 } 1410 1411 // For NEON intrinsics which are overloaded on vector element type, validate 1412 // the immediate which specifies which variant to emit. 1413 unsigned ImmArg = TheCall->getNumArgs()-1; 1414 if (mask) { 1415 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1416 return true; 1417 1418 TV = Result.getLimitedValue(64); 1419 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1420 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1421 << TheCall->getArg(ImmArg)->getSourceRange(); 1422 } 1423 1424 if (PtrArgNum >= 0) { 1425 // Check that pointer arguments have the specified type. 1426 Expr *Arg = TheCall->getArg(PtrArgNum); 1427 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1428 Arg = ICE->getSubExpr(); 1429 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1430 QualType RHSTy = RHS.get()->getType(); 1431 1432 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1433 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1434 Arch == llvm::Triple::aarch64_be; 1435 bool IsInt64Long = 1436 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1437 QualType EltTy = 1438 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1439 if (HasConstPtr) 1440 EltTy = EltTy.withConst(); 1441 QualType LHSTy = Context.getPointerType(EltTy); 1442 AssignConvertType ConvTy; 1443 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1444 if (RHS.isInvalid()) 1445 return true; 1446 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1447 RHS.get(), AA_Assigning)) 1448 return true; 1449 } 1450 1451 // For NEON intrinsics which take an immediate value as part of the 1452 // instruction, range check them here. 1453 unsigned i = 0, l = 0, u = 0; 1454 switch (BuiltinID) { 1455 default: 1456 return false; 1457 #define GET_NEON_IMMEDIATE_CHECK 1458 #include "clang/Basic/arm_neon.inc" 1459 #include "clang/Basic/arm_fp16.inc" 1460 #undef GET_NEON_IMMEDIATE_CHECK 1461 } 1462 1463 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1464 } 1465 1466 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1467 unsigned MaxWidth) { 1468 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1469 BuiltinID == ARM::BI__builtin_arm_ldaex || 1470 BuiltinID == ARM::BI__builtin_arm_strex || 1471 BuiltinID == ARM::BI__builtin_arm_stlex || 1472 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1473 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1474 BuiltinID == AArch64::BI__builtin_arm_strex || 1475 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1476 "unexpected ARM builtin"); 1477 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1478 BuiltinID == ARM::BI__builtin_arm_ldaex || 1479 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1480 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1481 1482 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1483 1484 // Ensure that we have the proper number of arguments. 1485 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1486 return true; 1487 1488 // Inspect the pointer argument of the atomic builtin. This should always be 1489 // a pointer type, whose element is an integral scalar or pointer type. 1490 // Because it is a pointer type, we don't have to worry about any implicit 1491 // casts here. 1492 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1493 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1494 if (PointerArgRes.isInvalid()) 1495 return true; 1496 PointerArg = PointerArgRes.get(); 1497 1498 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1499 if (!pointerType) { 1500 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1501 << PointerArg->getType() << PointerArg->getSourceRange(); 1502 return true; 1503 } 1504 1505 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1506 // task is to insert the appropriate casts into the AST. First work out just 1507 // what the appropriate type is. 1508 QualType ValType = pointerType->getPointeeType(); 1509 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1510 if (IsLdrex) 1511 AddrType.addConst(); 1512 1513 // Issue a warning if the cast is dodgy. 1514 CastKind CastNeeded = CK_NoOp; 1515 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1516 CastNeeded = CK_BitCast; 1517 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1518 << PointerArg->getType() 1519 << Context.getPointerType(AddrType) 1520 << AA_Passing << PointerArg->getSourceRange(); 1521 } 1522 1523 // Finally, do the cast and replace the argument with the corrected version. 1524 AddrType = Context.getPointerType(AddrType); 1525 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1526 if (PointerArgRes.isInvalid()) 1527 return true; 1528 PointerArg = PointerArgRes.get(); 1529 1530 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1531 1532 // In general, we allow ints, floats and pointers to be loaded and stored. 1533 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1534 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1535 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1536 << PointerArg->getType() << PointerArg->getSourceRange(); 1537 return true; 1538 } 1539 1540 // But ARM doesn't have instructions to deal with 128-bit versions. 1541 if (Context.getTypeSize(ValType) > MaxWidth) { 1542 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1543 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1544 << PointerArg->getType() << PointerArg->getSourceRange(); 1545 return true; 1546 } 1547 1548 switch (ValType.getObjCLifetime()) { 1549 case Qualifiers::OCL_None: 1550 case Qualifiers::OCL_ExplicitNone: 1551 // okay 1552 break; 1553 1554 case Qualifiers::OCL_Weak: 1555 case Qualifiers::OCL_Strong: 1556 case Qualifiers::OCL_Autoreleasing: 1557 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1558 << ValType << PointerArg->getSourceRange(); 1559 return true; 1560 } 1561 1562 if (IsLdrex) { 1563 TheCall->setType(ValType); 1564 return false; 1565 } 1566 1567 // Initialize the argument to be stored. 1568 ExprResult ValArg = TheCall->getArg(0); 1569 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1570 Context, ValType, /*consume*/ false); 1571 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1572 if (ValArg.isInvalid()) 1573 return true; 1574 TheCall->setArg(0, ValArg.get()); 1575 1576 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1577 // but the custom checker bypasses all default analysis. 1578 TheCall->setType(Context.IntTy); 1579 return false; 1580 } 1581 1582 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1583 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1584 BuiltinID == ARM::BI__builtin_arm_ldaex || 1585 BuiltinID == ARM::BI__builtin_arm_strex || 1586 BuiltinID == ARM::BI__builtin_arm_stlex) { 1587 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1588 } 1589 1590 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1591 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1592 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1593 } 1594 1595 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1596 BuiltinID == ARM::BI__builtin_arm_wsr64) 1597 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1598 1599 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1600 BuiltinID == ARM::BI__builtin_arm_rsrp || 1601 BuiltinID == ARM::BI__builtin_arm_wsr || 1602 BuiltinID == ARM::BI__builtin_arm_wsrp) 1603 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1604 1605 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1606 return true; 1607 1608 // For intrinsics which take an immediate value as part of the instruction, 1609 // range check them here. 1610 // FIXME: VFP Intrinsics should error if VFP not present. 1611 switch (BuiltinID) { 1612 default: return false; 1613 case ARM::BI__builtin_arm_ssat: 1614 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1615 case ARM::BI__builtin_arm_usat: 1616 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1617 case ARM::BI__builtin_arm_ssat16: 1618 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1619 case ARM::BI__builtin_arm_usat16: 1620 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1621 case ARM::BI__builtin_arm_vcvtr_f: 1622 case ARM::BI__builtin_arm_vcvtr_d: 1623 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1624 case ARM::BI__builtin_arm_dmb: 1625 case ARM::BI__builtin_arm_dsb: 1626 case ARM::BI__builtin_arm_isb: 1627 case ARM::BI__builtin_arm_dbg: 1628 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1629 } 1630 } 1631 1632 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1633 CallExpr *TheCall) { 1634 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1635 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1636 BuiltinID == AArch64::BI__builtin_arm_strex || 1637 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1638 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1639 } 1640 1641 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1642 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1643 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1644 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1645 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1646 } 1647 1648 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1649 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1650 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1651 1652 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1653 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1654 BuiltinID == AArch64::BI__builtin_arm_wsr || 1655 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1656 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1657 1658 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1659 return true; 1660 1661 // For intrinsics which take an immediate value as part of the instruction, 1662 // range check them here. 1663 unsigned i = 0, l = 0, u = 0; 1664 switch (BuiltinID) { 1665 default: return false; 1666 case AArch64::BI__builtin_arm_dmb: 1667 case AArch64::BI__builtin_arm_dsb: 1668 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1669 } 1670 1671 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1672 } 1673 1674 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1675 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1676 // ordering for DSP is unspecified. MSA is ordered by the data format used 1677 // by the underlying instruction i.e., df/m, df/n and then by size. 1678 // 1679 // FIXME: The size tests here should instead be tablegen'd along with the 1680 // definitions from include/clang/Basic/BuiltinsMips.def. 1681 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1682 // be too. 1683 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1684 unsigned i = 0, l = 0, u = 0, m = 0; 1685 switch (BuiltinID) { 1686 default: return false; 1687 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1688 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1689 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1690 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1691 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1692 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1693 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1694 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1695 // df/m field. 1696 // These intrinsics take an unsigned 3 bit immediate. 1697 case Mips::BI__builtin_msa_bclri_b: 1698 case Mips::BI__builtin_msa_bnegi_b: 1699 case Mips::BI__builtin_msa_bseti_b: 1700 case Mips::BI__builtin_msa_sat_s_b: 1701 case Mips::BI__builtin_msa_sat_u_b: 1702 case Mips::BI__builtin_msa_slli_b: 1703 case Mips::BI__builtin_msa_srai_b: 1704 case Mips::BI__builtin_msa_srari_b: 1705 case Mips::BI__builtin_msa_srli_b: 1706 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1707 case Mips::BI__builtin_msa_binsli_b: 1708 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1709 // These intrinsics take an unsigned 4 bit immediate. 1710 case Mips::BI__builtin_msa_bclri_h: 1711 case Mips::BI__builtin_msa_bnegi_h: 1712 case Mips::BI__builtin_msa_bseti_h: 1713 case Mips::BI__builtin_msa_sat_s_h: 1714 case Mips::BI__builtin_msa_sat_u_h: 1715 case Mips::BI__builtin_msa_slli_h: 1716 case Mips::BI__builtin_msa_srai_h: 1717 case Mips::BI__builtin_msa_srari_h: 1718 case Mips::BI__builtin_msa_srli_h: 1719 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1720 case Mips::BI__builtin_msa_binsli_h: 1721 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1722 // These intrinsics take an unsigned 5 bit immediate. 1723 // The first block of intrinsics actually have an unsigned 5 bit field, 1724 // not a df/n field. 1725 case Mips::BI__builtin_msa_clei_u_b: 1726 case Mips::BI__builtin_msa_clei_u_h: 1727 case Mips::BI__builtin_msa_clei_u_w: 1728 case Mips::BI__builtin_msa_clei_u_d: 1729 case Mips::BI__builtin_msa_clti_u_b: 1730 case Mips::BI__builtin_msa_clti_u_h: 1731 case Mips::BI__builtin_msa_clti_u_w: 1732 case Mips::BI__builtin_msa_clti_u_d: 1733 case Mips::BI__builtin_msa_maxi_u_b: 1734 case Mips::BI__builtin_msa_maxi_u_h: 1735 case Mips::BI__builtin_msa_maxi_u_w: 1736 case Mips::BI__builtin_msa_maxi_u_d: 1737 case Mips::BI__builtin_msa_mini_u_b: 1738 case Mips::BI__builtin_msa_mini_u_h: 1739 case Mips::BI__builtin_msa_mini_u_w: 1740 case Mips::BI__builtin_msa_mini_u_d: 1741 case Mips::BI__builtin_msa_addvi_b: 1742 case Mips::BI__builtin_msa_addvi_h: 1743 case Mips::BI__builtin_msa_addvi_w: 1744 case Mips::BI__builtin_msa_addvi_d: 1745 case Mips::BI__builtin_msa_bclri_w: 1746 case Mips::BI__builtin_msa_bnegi_w: 1747 case Mips::BI__builtin_msa_bseti_w: 1748 case Mips::BI__builtin_msa_sat_s_w: 1749 case Mips::BI__builtin_msa_sat_u_w: 1750 case Mips::BI__builtin_msa_slli_w: 1751 case Mips::BI__builtin_msa_srai_w: 1752 case Mips::BI__builtin_msa_srari_w: 1753 case Mips::BI__builtin_msa_srli_w: 1754 case Mips::BI__builtin_msa_srlri_w: 1755 case Mips::BI__builtin_msa_subvi_b: 1756 case Mips::BI__builtin_msa_subvi_h: 1757 case Mips::BI__builtin_msa_subvi_w: 1758 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1759 case Mips::BI__builtin_msa_binsli_w: 1760 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1761 // These intrinsics take an unsigned 6 bit immediate. 1762 case Mips::BI__builtin_msa_bclri_d: 1763 case Mips::BI__builtin_msa_bnegi_d: 1764 case Mips::BI__builtin_msa_bseti_d: 1765 case Mips::BI__builtin_msa_sat_s_d: 1766 case Mips::BI__builtin_msa_sat_u_d: 1767 case Mips::BI__builtin_msa_slli_d: 1768 case Mips::BI__builtin_msa_srai_d: 1769 case Mips::BI__builtin_msa_srari_d: 1770 case Mips::BI__builtin_msa_srli_d: 1771 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1772 case Mips::BI__builtin_msa_binsli_d: 1773 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1774 // These intrinsics take a signed 5 bit immediate. 1775 case Mips::BI__builtin_msa_ceqi_b: 1776 case Mips::BI__builtin_msa_ceqi_h: 1777 case Mips::BI__builtin_msa_ceqi_w: 1778 case Mips::BI__builtin_msa_ceqi_d: 1779 case Mips::BI__builtin_msa_clti_s_b: 1780 case Mips::BI__builtin_msa_clti_s_h: 1781 case Mips::BI__builtin_msa_clti_s_w: 1782 case Mips::BI__builtin_msa_clti_s_d: 1783 case Mips::BI__builtin_msa_clei_s_b: 1784 case Mips::BI__builtin_msa_clei_s_h: 1785 case Mips::BI__builtin_msa_clei_s_w: 1786 case Mips::BI__builtin_msa_clei_s_d: 1787 case Mips::BI__builtin_msa_maxi_s_b: 1788 case Mips::BI__builtin_msa_maxi_s_h: 1789 case Mips::BI__builtin_msa_maxi_s_w: 1790 case Mips::BI__builtin_msa_maxi_s_d: 1791 case Mips::BI__builtin_msa_mini_s_b: 1792 case Mips::BI__builtin_msa_mini_s_h: 1793 case Mips::BI__builtin_msa_mini_s_w: 1794 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1795 // These intrinsics take an unsigned 8 bit immediate. 1796 case Mips::BI__builtin_msa_andi_b: 1797 case Mips::BI__builtin_msa_nori_b: 1798 case Mips::BI__builtin_msa_ori_b: 1799 case Mips::BI__builtin_msa_shf_b: 1800 case Mips::BI__builtin_msa_shf_h: 1801 case Mips::BI__builtin_msa_shf_w: 1802 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1803 case Mips::BI__builtin_msa_bseli_b: 1804 case Mips::BI__builtin_msa_bmnzi_b: 1805 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1806 // df/n format 1807 // These intrinsics take an unsigned 4 bit immediate. 1808 case Mips::BI__builtin_msa_copy_s_b: 1809 case Mips::BI__builtin_msa_copy_u_b: 1810 case Mips::BI__builtin_msa_insve_b: 1811 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1812 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1813 // These intrinsics take an unsigned 3 bit immediate. 1814 case Mips::BI__builtin_msa_copy_s_h: 1815 case Mips::BI__builtin_msa_copy_u_h: 1816 case Mips::BI__builtin_msa_insve_h: 1817 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1818 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1819 // These intrinsics take an unsigned 2 bit immediate. 1820 case Mips::BI__builtin_msa_copy_s_w: 1821 case Mips::BI__builtin_msa_copy_u_w: 1822 case Mips::BI__builtin_msa_insve_w: 1823 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1824 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1825 // These intrinsics take an unsigned 1 bit immediate. 1826 case Mips::BI__builtin_msa_copy_s_d: 1827 case Mips::BI__builtin_msa_copy_u_d: 1828 case Mips::BI__builtin_msa_insve_d: 1829 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1830 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1831 // Memory offsets and immediate loads. 1832 // These intrinsics take a signed 10 bit immediate. 1833 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 1834 case Mips::BI__builtin_msa_ldi_h: 1835 case Mips::BI__builtin_msa_ldi_w: 1836 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1837 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1838 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1839 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1840 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1841 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1842 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1843 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1844 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1845 } 1846 1847 if (!m) 1848 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1849 1850 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1851 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1852 } 1853 1854 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1855 unsigned i = 0, l = 0, u = 0; 1856 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1857 BuiltinID == PPC::BI__builtin_divdeu || 1858 BuiltinID == PPC::BI__builtin_bpermd; 1859 bool IsTarget64Bit = Context.getTargetInfo() 1860 .getTypeWidth(Context 1861 .getTargetInfo() 1862 .getIntPtrType()) == 64; 1863 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1864 BuiltinID == PPC::BI__builtin_divweu || 1865 BuiltinID == PPC::BI__builtin_divde || 1866 BuiltinID == PPC::BI__builtin_divdeu; 1867 1868 if (Is64BitBltin && !IsTarget64Bit) 1869 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1870 << TheCall->getSourceRange(); 1871 1872 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1873 (BuiltinID == PPC::BI__builtin_bpermd && 1874 !Context.getTargetInfo().hasFeature("bpermd"))) 1875 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1876 << TheCall->getSourceRange(); 1877 1878 switch (BuiltinID) { 1879 default: return false; 1880 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1881 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1882 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1883 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1884 case PPC::BI__builtin_tbegin: 1885 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1886 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1887 case PPC::BI__builtin_tabortwc: 1888 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1889 case PPC::BI__builtin_tabortwci: 1890 case PPC::BI__builtin_tabortdci: 1891 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1892 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1893 case PPC::BI__builtin_vsx_xxpermdi: 1894 case PPC::BI__builtin_vsx_xxsldwi: 1895 return SemaBuiltinVSX(TheCall); 1896 } 1897 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1898 } 1899 1900 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1901 CallExpr *TheCall) { 1902 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1903 Expr *Arg = TheCall->getArg(0); 1904 llvm::APSInt AbortCode(32); 1905 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1906 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1907 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1908 << Arg->getSourceRange(); 1909 } 1910 1911 // For intrinsics which take an immediate value as part of the instruction, 1912 // range check them here. 1913 unsigned i = 0, l = 0, u = 0; 1914 switch (BuiltinID) { 1915 default: return false; 1916 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1917 case SystemZ::BI__builtin_s390_verimb: 1918 case SystemZ::BI__builtin_s390_verimh: 1919 case SystemZ::BI__builtin_s390_verimf: 1920 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1921 case SystemZ::BI__builtin_s390_vfaeb: 1922 case SystemZ::BI__builtin_s390_vfaeh: 1923 case SystemZ::BI__builtin_s390_vfaef: 1924 case SystemZ::BI__builtin_s390_vfaebs: 1925 case SystemZ::BI__builtin_s390_vfaehs: 1926 case SystemZ::BI__builtin_s390_vfaefs: 1927 case SystemZ::BI__builtin_s390_vfaezb: 1928 case SystemZ::BI__builtin_s390_vfaezh: 1929 case SystemZ::BI__builtin_s390_vfaezf: 1930 case SystemZ::BI__builtin_s390_vfaezbs: 1931 case SystemZ::BI__builtin_s390_vfaezhs: 1932 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1933 case SystemZ::BI__builtin_s390_vfisb: 1934 case SystemZ::BI__builtin_s390_vfidb: 1935 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1936 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1937 case SystemZ::BI__builtin_s390_vftcisb: 1938 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1939 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1940 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1941 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1942 case SystemZ::BI__builtin_s390_vstrcb: 1943 case SystemZ::BI__builtin_s390_vstrch: 1944 case SystemZ::BI__builtin_s390_vstrcf: 1945 case SystemZ::BI__builtin_s390_vstrczb: 1946 case SystemZ::BI__builtin_s390_vstrczh: 1947 case SystemZ::BI__builtin_s390_vstrczf: 1948 case SystemZ::BI__builtin_s390_vstrcbs: 1949 case SystemZ::BI__builtin_s390_vstrchs: 1950 case SystemZ::BI__builtin_s390_vstrcfs: 1951 case SystemZ::BI__builtin_s390_vstrczbs: 1952 case SystemZ::BI__builtin_s390_vstrczhs: 1953 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1954 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 1955 case SystemZ::BI__builtin_s390_vfminsb: 1956 case SystemZ::BI__builtin_s390_vfmaxsb: 1957 case SystemZ::BI__builtin_s390_vfmindb: 1958 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 1959 } 1960 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1961 } 1962 1963 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1964 /// This checks that the target supports __builtin_cpu_supports and 1965 /// that the string argument is constant and valid. 1966 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1967 Expr *Arg = TheCall->getArg(0); 1968 1969 // Check if the argument is a string literal. 1970 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1971 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1972 << Arg->getSourceRange(); 1973 1974 // Check the contents of the string. 1975 StringRef Feature = 1976 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1977 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1978 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1979 << Arg->getSourceRange(); 1980 return false; 1981 } 1982 1983 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 1984 /// This checks that the target supports __builtin_cpu_is and 1985 /// that the string argument is constant and valid. 1986 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 1987 Expr *Arg = TheCall->getArg(0); 1988 1989 // Check if the argument is a string literal. 1990 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1991 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1992 << Arg->getSourceRange(); 1993 1994 // Check the contents of the string. 1995 StringRef Feature = 1996 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1997 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 1998 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is) 1999 << Arg->getSourceRange(); 2000 return false; 2001 } 2002 2003 // Check if the rounding mode is legal. 2004 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 2005 // Indicates if this instruction has rounding control or just SAE. 2006 bool HasRC = false; 2007 2008 unsigned ArgNum = 0; 2009 switch (BuiltinID) { 2010 default: 2011 return false; 2012 case X86::BI__builtin_ia32_vcvttsd2si32: 2013 case X86::BI__builtin_ia32_vcvttsd2si64: 2014 case X86::BI__builtin_ia32_vcvttsd2usi32: 2015 case X86::BI__builtin_ia32_vcvttsd2usi64: 2016 case X86::BI__builtin_ia32_vcvttss2si32: 2017 case X86::BI__builtin_ia32_vcvttss2si64: 2018 case X86::BI__builtin_ia32_vcvttss2usi32: 2019 case X86::BI__builtin_ia32_vcvttss2usi64: 2020 ArgNum = 1; 2021 break; 2022 case X86::BI__builtin_ia32_cvtps2pd512_mask: 2023 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 2024 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 2025 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 2026 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 2027 case X86::BI__builtin_ia32_cvttps2dq512_mask: 2028 case X86::BI__builtin_ia32_cvttps2qq512_mask: 2029 case X86::BI__builtin_ia32_cvttps2udq512_mask: 2030 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 2031 case X86::BI__builtin_ia32_exp2pd_mask: 2032 case X86::BI__builtin_ia32_exp2ps_mask: 2033 case X86::BI__builtin_ia32_getexppd512_mask: 2034 case X86::BI__builtin_ia32_getexpps512_mask: 2035 case X86::BI__builtin_ia32_rcp28pd_mask: 2036 case X86::BI__builtin_ia32_rcp28ps_mask: 2037 case X86::BI__builtin_ia32_rsqrt28pd_mask: 2038 case X86::BI__builtin_ia32_rsqrt28ps_mask: 2039 case X86::BI__builtin_ia32_vcomisd: 2040 case X86::BI__builtin_ia32_vcomiss: 2041 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 2042 ArgNum = 3; 2043 break; 2044 case X86::BI__builtin_ia32_cmppd512_mask: 2045 case X86::BI__builtin_ia32_cmpps512_mask: 2046 case X86::BI__builtin_ia32_cmpsd_mask: 2047 case X86::BI__builtin_ia32_cmpss_mask: 2048 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 2049 case X86::BI__builtin_ia32_getexpsd128_round_mask: 2050 case X86::BI__builtin_ia32_getexpss128_round_mask: 2051 case X86::BI__builtin_ia32_maxpd512_mask: 2052 case X86::BI__builtin_ia32_maxps512_mask: 2053 case X86::BI__builtin_ia32_maxsd_round_mask: 2054 case X86::BI__builtin_ia32_maxss_round_mask: 2055 case X86::BI__builtin_ia32_minpd512_mask: 2056 case X86::BI__builtin_ia32_minps512_mask: 2057 case X86::BI__builtin_ia32_minsd_round_mask: 2058 case X86::BI__builtin_ia32_minss_round_mask: 2059 case X86::BI__builtin_ia32_rcp28sd_round_mask: 2060 case X86::BI__builtin_ia32_rcp28ss_round_mask: 2061 case X86::BI__builtin_ia32_reducepd512_mask: 2062 case X86::BI__builtin_ia32_reduceps512_mask: 2063 case X86::BI__builtin_ia32_rndscalepd_mask: 2064 case X86::BI__builtin_ia32_rndscaleps_mask: 2065 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 2066 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 2067 ArgNum = 4; 2068 break; 2069 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2070 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2071 case X86::BI__builtin_ia32_fixupimmps512_mask: 2072 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2073 case X86::BI__builtin_ia32_fixupimmsd_mask: 2074 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2075 case X86::BI__builtin_ia32_fixupimmss_mask: 2076 case X86::BI__builtin_ia32_fixupimmss_maskz: 2077 case X86::BI__builtin_ia32_rangepd512_mask: 2078 case X86::BI__builtin_ia32_rangeps512_mask: 2079 case X86::BI__builtin_ia32_rangesd128_round_mask: 2080 case X86::BI__builtin_ia32_rangess128_round_mask: 2081 case X86::BI__builtin_ia32_reducesd_mask: 2082 case X86::BI__builtin_ia32_reducess_mask: 2083 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2084 case X86::BI__builtin_ia32_rndscaless_round_mask: 2085 ArgNum = 5; 2086 break; 2087 case X86::BI__builtin_ia32_vcvtsd2si64: 2088 case X86::BI__builtin_ia32_vcvtsd2si32: 2089 case X86::BI__builtin_ia32_vcvtsd2usi32: 2090 case X86::BI__builtin_ia32_vcvtsd2usi64: 2091 case X86::BI__builtin_ia32_vcvtss2si32: 2092 case X86::BI__builtin_ia32_vcvtss2si64: 2093 case X86::BI__builtin_ia32_vcvtss2usi32: 2094 case X86::BI__builtin_ia32_vcvtss2usi64: 2095 ArgNum = 1; 2096 HasRC = true; 2097 break; 2098 case X86::BI__builtin_ia32_cvtsi2sd64: 2099 case X86::BI__builtin_ia32_cvtsi2ss32: 2100 case X86::BI__builtin_ia32_cvtsi2ss64: 2101 case X86::BI__builtin_ia32_cvtusi2sd64: 2102 case X86::BI__builtin_ia32_cvtusi2ss32: 2103 case X86::BI__builtin_ia32_cvtusi2ss64: 2104 ArgNum = 2; 2105 HasRC = true; 2106 break; 2107 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 2108 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 2109 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 2110 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 2111 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 2112 case X86::BI__builtin_ia32_cvtps2qq512_mask: 2113 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 2114 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 2115 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 2116 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 2117 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 2118 case X86::BI__builtin_ia32_sqrtpd512_mask: 2119 case X86::BI__builtin_ia32_sqrtps512_mask: 2120 ArgNum = 3; 2121 HasRC = true; 2122 break; 2123 case X86::BI__builtin_ia32_addpd512_mask: 2124 case X86::BI__builtin_ia32_addps512_mask: 2125 case X86::BI__builtin_ia32_divpd512_mask: 2126 case X86::BI__builtin_ia32_divps512_mask: 2127 case X86::BI__builtin_ia32_mulpd512_mask: 2128 case X86::BI__builtin_ia32_mulps512_mask: 2129 case X86::BI__builtin_ia32_subpd512_mask: 2130 case X86::BI__builtin_ia32_subps512_mask: 2131 case X86::BI__builtin_ia32_addss_round_mask: 2132 case X86::BI__builtin_ia32_addsd_round_mask: 2133 case X86::BI__builtin_ia32_divss_round_mask: 2134 case X86::BI__builtin_ia32_divsd_round_mask: 2135 case X86::BI__builtin_ia32_mulss_round_mask: 2136 case X86::BI__builtin_ia32_mulsd_round_mask: 2137 case X86::BI__builtin_ia32_subss_round_mask: 2138 case X86::BI__builtin_ia32_subsd_round_mask: 2139 case X86::BI__builtin_ia32_scalefpd512_mask: 2140 case X86::BI__builtin_ia32_scalefps512_mask: 2141 case X86::BI__builtin_ia32_scalefsd_round_mask: 2142 case X86::BI__builtin_ia32_scalefss_round_mask: 2143 case X86::BI__builtin_ia32_getmantpd512_mask: 2144 case X86::BI__builtin_ia32_getmantps512_mask: 2145 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 2146 case X86::BI__builtin_ia32_sqrtsd_round_mask: 2147 case X86::BI__builtin_ia32_sqrtss_round_mask: 2148 case X86::BI__builtin_ia32_vfmaddpd512_mask: 2149 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 2150 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 2151 case X86::BI__builtin_ia32_vfmaddps512_mask: 2152 case X86::BI__builtin_ia32_vfmaddps512_mask3: 2153 case X86::BI__builtin_ia32_vfmaddps512_maskz: 2154 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 2155 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 2156 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 2157 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 2158 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2159 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2160 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2161 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2162 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2163 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2164 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 2165 case X86::BI__builtin_ia32_vfnmaddps512_mask: 2166 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 2167 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 2168 case X86::BI__builtin_ia32_vfnmsubps512_mask: 2169 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 2170 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2171 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2172 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2173 case X86::BI__builtin_ia32_vfmaddss3_mask: 2174 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2175 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2176 ArgNum = 4; 2177 HasRC = true; 2178 break; 2179 case X86::BI__builtin_ia32_getmantsd_round_mask: 2180 case X86::BI__builtin_ia32_getmantss_round_mask: 2181 ArgNum = 5; 2182 HasRC = true; 2183 break; 2184 } 2185 2186 llvm::APSInt Result; 2187 2188 // We can't check the value of a dependent argument. 2189 Expr *Arg = TheCall->getArg(ArgNum); 2190 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2191 return false; 2192 2193 // Check constant-ness first. 2194 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2195 return true; 2196 2197 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2198 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2199 // combined with ROUND_NO_EXC. 2200 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2201 Result == 8/*ROUND_NO_EXC*/ || 2202 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2203 return false; 2204 2205 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2206 << Arg->getSourceRange(); 2207 } 2208 2209 // Check if the gather/scatter scale is legal. 2210 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2211 CallExpr *TheCall) { 2212 unsigned ArgNum = 0; 2213 switch (BuiltinID) { 2214 default: 2215 return false; 2216 case X86::BI__builtin_ia32_gatherpfdpd: 2217 case X86::BI__builtin_ia32_gatherpfdps: 2218 case X86::BI__builtin_ia32_gatherpfqpd: 2219 case X86::BI__builtin_ia32_gatherpfqps: 2220 case X86::BI__builtin_ia32_scatterpfdpd: 2221 case X86::BI__builtin_ia32_scatterpfdps: 2222 case X86::BI__builtin_ia32_scatterpfqpd: 2223 case X86::BI__builtin_ia32_scatterpfqps: 2224 ArgNum = 3; 2225 break; 2226 case X86::BI__builtin_ia32_gatherd_pd: 2227 case X86::BI__builtin_ia32_gatherd_pd256: 2228 case X86::BI__builtin_ia32_gatherq_pd: 2229 case X86::BI__builtin_ia32_gatherq_pd256: 2230 case X86::BI__builtin_ia32_gatherd_ps: 2231 case X86::BI__builtin_ia32_gatherd_ps256: 2232 case X86::BI__builtin_ia32_gatherq_ps: 2233 case X86::BI__builtin_ia32_gatherq_ps256: 2234 case X86::BI__builtin_ia32_gatherd_q: 2235 case X86::BI__builtin_ia32_gatherd_q256: 2236 case X86::BI__builtin_ia32_gatherq_q: 2237 case X86::BI__builtin_ia32_gatherq_q256: 2238 case X86::BI__builtin_ia32_gatherd_d: 2239 case X86::BI__builtin_ia32_gatherd_d256: 2240 case X86::BI__builtin_ia32_gatherq_d: 2241 case X86::BI__builtin_ia32_gatherq_d256: 2242 case X86::BI__builtin_ia32_gather3div2df: 2243 case X86::BI__builtin_ia32_gather3div2di: 2244 case X86::BI__builtin_ia32_gather3div4df: 2245 case X86::BI__builtin_ia32_gather3div4di: 2246 case X86::BI__builtin_ia32_gather3div4sf: 2247 case X86::BI__builtin_ia32_gather3div4si: 2248 case X86::BI__builtin_ia32_gather3div8sf: 2249 case X86::BI__builtin_ia32_gather3div8si: 2250 case X86::BI__builtin_ia32_gather3siv2df: 2251 case X86::BI__builtin_ia32_gather3siv2di: 2252 case X86::BI__builtin_ia32_gather3siv4df: 2253 case X86::BI__builtin_ia32_gather3siv4di: 2254 case X86::BI__builtin_ia32_gather3siv4sf: 2255 case X86::BI__builtin_ia32_gather3siv4si: 2256 case X86::BI__builtin_ia32_gather3siv8sf: 2257 case X86::BI__builtin_ia32_gather3siv8si: 2258 case X86::BI__builtin_ia32_gathersiv8df: 2259 case X86::BI__builtin_ia32_gathersiv16sf: 2260 case X86::BI__builtin_ia32_gatherdiv8df: 2261 case X86::BI__builtin_ia32_gatherdiv16sf: 2262 case X86::BI__builtin_ia32_gathersiv8di: 2263 case X86::BI__builtin_ia32_gathersiv16si: 2264 case X86::BI__builtin_ia32_gatherdiv8di: 2265 case X86::BI__builtin_ia32_gatherdiv16si: 2266 case X86::BI__builtin_ia32_scatterdiv2df: 2267 case X86::BI__builtin_ia32_scatterdiv2di: 2268 case X86::BI__builtin_ia32_scatterdiv4df: 2269 case X86::BI__builtin_ia32_scatterdiv4di: 2270 case X86::BI__builtin_ia32_scatterdiv4sf: 2271 case X86::BI__builtin_ia32_scatterdiv4si: 2272 case X86::BI__builtin_ia32_scatterdiv8sf: 2273 case X86::BI__builtin_ia32_scatterdiv8si: 2274 case X86::BI__builtin_ia32_scattersiv2df: 2275 case X86::BI__builtin_ia32_scattersiv2di: 2276 case X86::BI__builtin_ia32_scattersiv4df: 2277 case X86::BI__builtin_ia32_scattersiv4di: 2278 case X86::BI__builtin_ia32_scattersiv4sf: 2279 case X86::BI__builtin_ia32_scattersiv4si: 2280 case X86::BI__builtin_ia32_scattersiv8sf: 2281 case X86::BI__builtin_ia32_scattersiv8si: 2282 case X86::BI__builtin_ia32_scattersiv8df: 2283 case X86::BI__builtin_ia32_scattersiv16sf: 2284 case X86::BI__builtin_ia32_scatterdiv8df: 2285 case X86::BI__builtin_ia32_scatterdiv16sf: 2286 case X86::BI__builtin_ia32_scattersiv8di: 2287 case X86::BI__builtin_ia32_scattersiv16si: 2288 case X86::BI__builtin_ia32_scatterdiv8di: 2289 case X86::BI__builtin_ia32_scatterdiv16si: 2290 ArgNum = 4; 2291 break; 2292 } 2293 2294 llvm::APSInt Result; 2295 2296 // We can't check the value of a dependent argument. 2297 Expr *Arg = TheCall->getArg(ArgNum); 2298 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2299 return false; 2300 2301 // Check constant-ness first. 2302 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2303 return true; 2304 2305 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2306 return false; 2307 2308 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2309 << Arg->getSourceRange(); 2310 } 2311 2312 static bool isX86_32Builtin(unsigned BuiltinID) { 2313 // These builtins only work on x86-32 targets. 2314 switch (BuiltinID) { 2315 case X86::BI__builtin_ia32_readeflags_u32: 2316 case X86::BI__builtin_ia32_writeeflags_u32: 2317 return true; 2318 } 2319 2320 return false; 2321 } 2322 2323 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2324 if (BuiltinID == X86::BI__builtin_cpu_supports) 2325 return SemaBuiltinCpuSupports(*this, TheCall); 2326 2327 if (BuiltinID == X86::BI__builtin_cpu_is) 2328 return SemaBuiltinCpuIs(*this, TheCall); 2329 2330 // Check for 32-bit only builtins on a 64-bit target. 2331 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 2332 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 2333 return Diag(TheCall->getCallee()->getLocStart(), 2334 diag::err_32_bit_builtin_64_bit_tgt); 2335 2336 // If the intrinsic has rounding or SAE make sure its valid. 2337 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2338 return true; 2339 2340 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2341 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2342 return true; 2343 2344 // For intrinsics which take an immediate value as part of the instruction, 2345 // range check them here. 2346 int i = 0, l = 0, u = 0; 2347 switch (BuiltinID) { 2348 default: 2349 return false; 2350 case X86::BI_mm_prefetch: 2351 i = 1; l = 0; u = 7; 2352 break; 2353 case X86::BI__builtin_ia32_sha1rnds4: 2354 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2355 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2356 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2357 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2358 i = 2; l = 0; u = 3; 2359 break; 2360 case X86::BI__builtin_ia32_vpermil2pd: 2361 case X86::BI__builtin_ia32_vpermil2pd256: 2362 case X86::BI__builtin_ia32_vpermil2ps: 2363 case X86::BI__builtin_ia32_vpermil2ps256: 2364 i = 3; l = 0; u = 3; 2365 break; 2366 case X86::BI__builtin_ia32_cmpb128_mask: 2367 case X86::BI__builtin_ia32_cmpw128_mask: 2368 case X86::BI__builtin_ia32_cmpd128_mask: 2369 case X86::BI__builtin_ia32_cmpq128_mask: 2370 case X86::BI__builtin_ia32_cmpb256_mask: 2371 case X86::BI__builtin_ia32_cmpw256_mask: 2372 case X86::BI__builtin_ia32_cmpd256_mask: 2373 case X86::BI__builtin_ia32_cmpq256_mask: 2374 case X86::BI__builtin_ia32_cmpb512_mask: 2375 case X86::BI__builtin_ia32_cmpw512_mask: 2376 case X86::BI__builtin_ia32_cmpd512_mask: 2377 case X86::BI__builtin_ia32_cmpq512_mask: 2378 case X86::BI__builtin_ia32_ucmpb128_mask: 2379 case X86::BI__builtin_ia32_ucmpw128_mask: 2380 case X86::BI__builtin_ia32_ucmpd128_mask: 2381 case X86::BI__builtin_ia32_ucmpq128_mask: 2382 case X86::BI__builtin_ia32_ucmpb256_mask: 2383 case X86::BI__builtin_ia32_ucmpw256_mask: 2384 case X86::BI__builtin_ia32_ucmpd256_mask: 2385 case X86::BI__builtin_ia32_ucmpq256_mask: 2386 case X86::BI__builtin_ia32_ucmpb512_mask: 2387 case X86::BI__builtin_ia32_ucmpw512_mask: 2388 case X86::BI__builtin_ia32_ucmpd512_mask: 2389 case X86::BI__builtin_ia32_ucmpq512_mask: 2390 case X86::BI__builtin_ia32_vpcomub: 2391 case X86::BI__builtin_ia32_vpcomuw: 2392 case X86::BI__builtin_ia32_vpcomud: 2393 case X86::BI__builtin_ia32_vpcomuq: 2394 case X86::BI__builtin_ia32_vpcomb: 2395 case X86::BI__builtin_ia32_vpcomw: 2396 case X86::BI__builtin_ia32_vpcomd: 2397 case X86::BI__builtin_ia32_vpcomq: 2398 i = 2; l = 0; u = 7; 2399 break; 2400 case X86::BI__builtin_ia32_roundps: 2401 case X86::BI__builtin_ia32_roundpd: 2402 case X86::BI__builtin_ia32_roundps256: 2403 case X86::BI__builtin_ia32_roundpd256: 2404 i = 1; l = 0; u = 15; 2405 break; 2406 case X86::BI__builtin_ia32_roundss: 2407 case X86::BI__builtin_ia32_roundsd: 2408 case X86::BI__builtin_ia32_rangepd128_mask: 2409 case X86::BI__builtin_ia32_rangepd256_mask: 2410 case X86::BI__builtin_ia32_rangepd512_mask: 2411 case X86::BI__builtin_ia32_rangeps128_mask: 2412 case X86::BI__builtin_ia32_rangeps256_mask: 2413 case X86::BI__builtin_ia32_rangeps512_mask: 2414 case X86::BI__builtin_ia32_getmantsd_round_mask: 2415 case X86::BI__builtin_ia32_getmantss_round_mask: 2416 i = 2; l = 0; u = 15; 2417 break; 2418 case X86::BI__builtin_ia32_cmpps: 2419 case X86::BI__builtin_ia32_cmpss: 2420 case X86::BI__builtin_ia32_cmppd: 2421 case X86::BI__builtin_ia32_cmpsd: 2422 case X86::BI__builtin_ia32_cmpps256: 2423 case X86::BI__builtin_ia32_cmppd256: 2424 case X86::BI__builtin_ia32_cmpps128_mask: 2425 case X86::BI__builtin_ia32_cmppd128_mask: 2426 case X86::BI__builtin_ia32_cmpps256_mask: 2427 case X86::BI__builtin_ia32_cmppd256_mask: 2428 case X86::BI__builtin_ia32_cmpps512_mask: 2429 case X86::BI__builtin_ia32_cmppd512_mask: 2430 case X86::BI__builtin_ia32_cmpsd_mask: 2431 case X86::BI__builtin_ia32_cmpss_mask: 2432 i = 2; l = 0; u = 31; 2433 break; 2434 case X86::BI__builtin_ia32_vcvtps2ph: 2435 case X86::BI__builtin_ia32_vcvtps2ph_mask: 2436 case X86::BI__builtin_ia32_vcvtps2ph256: 2437 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 2438 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 2439 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2440 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2441 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2442 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2443 case X86::BI__builtin_ia32_rndscaleps_mask: 2444 case X86::BI__builtin_ia32_rndscalepd_mask: 2445 case X86::BI__builtin_ia32_reducepd128_mask: 2446 case X86::BI__builtin_ia32_reducepd256_mask: 2447 case X86::BI__builtin_ia32_reducepd512_mask: 2448 case X86::BI__builtin_ia32_reduceps128_mask: 2449 case X86::BI__builtin_ia32_reduceps256_mask: 2450 case X86::BI__builtin_ia32_reduceps512_mask: 2451 case X86::BI__builtin_ia32_prold512_mask: 2452 case X86::BI__builtin_ia32_prolq512_mask: 2453 case X86::BI__builtin_ia32_prold128_mask: 2454 case X86::BI__builtin_ia32_prold256_mask: 2455 case X86::BI__builtin_ia32_prolq128_mask: 2456 case X86::BI__builtin_ia32_prolq256_mask: 2457 case X86::BI__builtin_ia32_prord128_mask: 2458 case X86::BI__builtin_ia32_prord256_mask: 2459 case X86::BI__builtin_ia32_prorq128_mask: 2460 case X86::BI__builtin_ia32_prorq256_mask: 2461 case X86::BI__builtin_ia32_fpclasspd128_mask: 2462 case X86::BI__builtin_ia32_fpclasspd256_mask: 2463 case X86::BI__builtin_ia32_fpclassps128_mask: 2464 case X86::BI__builtin_ia32_fpclassps256_mask: 2465 case X86::BI__builtin_ia32_fpclassps512_mask: 2466 case X86::BI__builtin_ia32_fpclasspd512_mask: 2467 case X86::BI__builtin_ia32_fpclasssd_mask: 2468 case X86::BI__builtin_ia32_fpclassss_mask: 2469 i = 1; l = 0; u = 255; 2470 break; 2471 case X86::BI__builtin_ia32_palignr128: 2472 case X86::BI__builtin_ia32_palignr256: 2473 case X86::BI__builtin_ia32_palignr512_mask: 2474 case X86::BI__builtin_ia32_vcomisd: 2475 case X86::BI__builtin_ia32_vcomiss: 2476 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2477 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2478 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2479 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2480 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2481 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2482 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2483 case X86::BI__builtin_ia32_vpshldd128_mask: 2484 case X86::BI__builtin_ia32_vpshldd256_mask: 2485 case X86::BI__builtin_ia32_vpshldd512_mask: 2486 case X86::BI__builtin_ia32_vpshldq128_mask: 2487 case X86::BI__builtin_ia32_vpshldq256_mask: 2488 case X86::BI__builtin_ia32_vpshldq512_mask: 2489 case X86::BI__builtin_ia32_vpshldw128_mask: 2490 case X86::BI__builtin_ia32_vpshldw256_mask: 2491 case X86::BI__builtin_ia32_vpshldw512_mask: 2492 case X86::BI__builtin_ia32_vpshrdd128_mask: 2493 case X86::BI__builtin_ia32_vpshrdd256_mask: 2494 case X86::BI__builtin_ia32_vpshrdd512_mask: 2495 case X86::BI__builtin_ia32_vpshrdq128_mask: 2496 case X86::BI__builtin_ia32_vpshrdq256_mask: 2497 case X86::BI__builtin_ia32_vpshrdq512_mask: 2498 case X86::BI__builtin_ia32_vpshrdw128_mask: 2499 case X86::BI__builtin_ia32_vpshrdw256_mask: 2500 case X86::BI__builtin_ia32_vpshrdw512_mask: 2501 i = 2; l = 0; u = 255; 2502 break; 2503 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2504 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2505 case X86::BI__builtin_ia32_fixupimmps512_mask: 2506 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2507 case X86::BI__builtin_ia32_fixupimmsd_mask: 2508 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2509 case X86::BI__builtin_ia32_fixupimmss_mask: 2510 case X86::BI__builtin_ia32_fixupimmss_maskz: 2511 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2512 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2513 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2514 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2515 case X86::BI__builtin_ia32_fixupimmps128_mask: 2516 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2517 case X86::BI__builtin_ia32_fixupimmps256_mask: 2518 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2519 case X86::BI__builtin_ia32_pternlogd512_mask: 2520 case X86::BI__builtin_ia32_pternlogd512_maskz: 2521 case X86::BI__builtin_ia32_pternlogq512_mask: 2522 case X86::BI__builtin_ia32_pternlogq512_maskz: 2523 case X86::BI__builtin_ia32_pternlogd128_mask: 2524 case X86::BI__builtin_ia32_pternlogd128_maskz: 2525 case X86::BI__builtin_ia32_pternlogd256_mask: 2526 case X86::BI__builtin_ia32_pternlogd256_maskz: 2527 case X86::BI__builtin_ia32_pternlogq128_mask: 2528 case X86::BI__builtin_ia32_pternlogq128_maskz: 2529 case X86::BI__builtin_ia32_pternlogq256_mask: 2530 case X86::BI__builtin_ia32_pternlogq256_maskz: 2531 i = 3; l = 0; u = 255; 2532 break; 2533 case X86::BI__builtin_ia32_gatherpfdpd: 2534 case X86::BI__builtin_ia32_gatherpfdps: 2535 case X86::BI__builtin_ia32_gatherpfqpd: 2536 case X86::BI__builtin_ia32_gatherpfqps: 2537 case X86::BI__builtin_ia32_scatterpfdpd: 2538 case X86::BI__builtin_ia32_scatterpfdps: 2539 case X86::BI__builtin_ia32_scatterpfqpd: 2540 case X86::BI__builtin_ia32_scatterpfqps: 2541 i = 4; l = 2; u = 3; 2542 break; 2543 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2544 case X86::BI__builtin_ia32_rndscaless_round_mask: 2545 i = 4; l = 0; u = 255; 2546 break; 2547 } 2548 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2549 } 2550 2551 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2552 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2553 /// Returns true when the format fits the function and the FormatStringInfo has 2554 /// been populated. 2555 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2556 FormatStringInfo *FSI) { 2557 FSI->HasVAListArg = Format->getFirstArg() == 0; 2558 FSI->FormatIdx = Format->getFormatIdx() - 1; 2559 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2560 2561 // The way the format attribute works in GCC, the implicit this argument 2562 // of member functions is counted. However, it doesn't appear in our own 2563 // lists, so decrement format_idx in that case. 2564 if (IsCXXMember) { 2565 if(FSI->FormatIdx == 0) 2566 return false; 2567 --FSI->FormatIdx; 2568 if (FSI->FirstDataArg != 0) 2569 --FSI->FirstDataArg; 2570 } 2571 return true; 2572 } 2573 2574 /// Checks if a the given expression evaluates to null. 2575 /// 2576 /// \brief Returns true if the value evaluates to null. 2577 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2578 // If the expression has non-null type, it doesn't evaluate to null. 2579 if (auto nullability 2580 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2581 if (*nullability == NullabilityKind::NonNull) 2582 return false; 2583 } 2584 2585 // As a special case, transparent unions initialized with zero are 2586 // considered null for the purposes of the nonnull attribute. 2587 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2588 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2589 if (const CompoundLiteralExpr *CLE = 2590 dyn_cast<CompoundLiteralExpr>(Expr)) 2591 if (const InitListExpr *ILE = 2592 dyn_cast<InitListExpr>(CLE->getInitializer())) 2593 Expr = ILE->getInit(0); 2594 } 2595 2596 bool Result; 2597 return (!Expr->isValueDependent() && 2598 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2599 !Result); 2600 } 2601 2602 static void CheckNonNullArgument(Sema &S, 2603 const Expr *ArgExpr, 2604 SourceLocation CallSiteLoc) { 2605 if (CheckNonNullExpr(S, ArgExpr)) 2606 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2607 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2608 } 2609 2610 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2611 FormatStringInfo FSI; 2612 if ((GetFormatStringType(Format) == FST_NSString) && 2613 getFormatStringInfo(Format, false, &FSI)) { 2614 Idx = FSI.FormatIdx; 2615 return true; 2616 } 2617 return false; 2618 } 2619 2620 /// \brief Diagnose use of %s directive in an NSString which is being passed 2621 /// as formatting string to formatting method. 2622 static void 2623 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2624 const NamedDecl *FDecl, 2625 Expr **Args, 2626 unsigned NumArgs) { 2627 unsigned Idx = 0; 2628 bool Format = false; 2629 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2630 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2631 Idx = 2; 2632 Format = true; 2633 } 2634 else 2635 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2636 if (S.GetFormatNSStringIdx(I, Idx)) { 2637 Format = true; 2638 break; 2639 } 2640 } 2641 if (!Format || NumArgs <= Idx) 2642 return; 2643 const Expr *FormatExpr = Args[Idx]; 2644 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2645 FormatExpr = CSCE->getSubExpr(); 2646 const StringLiteral *FormatString; 2647 if (const ObjCStringLiteral *OSL = 2648 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2649 FormatString = OSL->getString(); 2650 else 2651 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2652 if (!FormatString) 2653 return; 2654 if (S.FormatStringHasSArg(FormatString)) { 2655 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2656 << "%s" << 1 << 1; 2657 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2658 << FDecl->getDeclName(); 2659 } 2660 } 2661 2662 /// Determine whether the given type has a non-null nullability annotation. 2663 static bool isNonNullType(ASTContext &ctx, QualType type) { 2664 if (auto nullability = type->getNullability(ctx)) 2665 return *nullability == NullabilityKind::NonNull; 2666 2667 return false; 2668 } 2669 2670 static void CheckNonNullArguments(Sema &S, 2671 const NamedDecl *FDecl, 2672 const FunctionProtoType *Proto, 2673 ArrayRef<const Expr *> Args, 2674 SourceLocation CallSiteLoc) { 2675 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2676 2677 // Check the attributes attached to the method/function itself. 2678 llvm::SmallBitVector NonNullArgs; 2679 if (FDecl) { 2680 // Handle the nonnull attribute on the function/method declaration itself. 2681 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2682 if (!NonNull->args_size()) { 2683 // Easy case: all pointer arguments are nonnull. 2684 for (const auto *Arg : Args) 2685 if (S.isValidPointerAttrType(Arg->getType())) 2686 CheckNonNullArgument(S, Arg, CallSiteLoc); 2687 return; 2688 } 2689 2690 for (const ParamIdx &Idx : NonNull->args()) { 2691 unsigned IdxAST = Idx.getASTIndex(); 2692 if (IdxAST >= Args.size()) 2693 continue; 2694 if (NonNullArgs.empty()) 2695 NonNullArgs.resize(Args.size()); 2696 NonNullArgs.set(IdxAST); 2697 } 2698 } 2699 } 2700 2701 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2702 // Handle the nonnull attribute on the parameters of the 2703 // function/method. 2704 ArrayRef<ParmVarDecl*> parms; 2705 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2706 parms = FD->parameters(); 2707 else 2708 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2709 2710 unsigned ParamIndex = 0; 2711 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2712 I != E; ++I, ++ParamIndex) { 2713 const ParmVarDecl *PVD = *I; 2714 if (PVD->hasAttr<NonNullAttr>() || 2715 isNonNullType(S.Context, PVD->getType())) { 2716 if (NonNullArgs.empty()) 2717 NonNullArgs.resize(Args.size()); 2718 2719 NonNullArgs.set(ParamIndex); 2720 } 2721 } 2722 } else { 2723 // If we have a non-function, non-method declaration but no 2724 // function prototype, try to dig out the function prototype. 2725 if (!Proto) { 2726 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2727 QualType type = VD->getType().getNonReferenceType(); 2728 if (auto pointerType = type->getAs<PointerType>()) 2729 type = pointerType->getPointeeType(); 2730 else if (auto blockType = type->getAs<BlockPointerType>()) 2731 type = blockType->getPointeeType(); 2732 // FIXME: data member pointers? 2733 2734 // Dig out the function prototype, if there is one. 2735 Proto = type->getAs<FunctionProtoType>(); 2736 } 2737 } 2738 2739 // Fill in non-null argument information from the nullability 2740 // information on the parameter types (if we have them). 2741 if (Proto) { 2742 unsigned Index = 0; 2743 for (auto paramType : Proto->getParamTypes()) { 2744 if (isNonNullType(S.Context, paramType)) { 2745 if (NonNullArgs.empty()) 2746 NonNullArgs.resize(Args.size()); 2747 2748 NonNullArgs.set(Index); 2749 } 2750 2751 ++Index; 2752 } 2753 } 2754 } 2755 2756 // Check for non-null arguments. 2757 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2758 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2759 if (NonNullArgs[ArgIndex]) 2760 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2761 } 2762 } 2763 2764 /// Handles the checks for format strings, non-POD arguments to vararg 2765 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2766 /// attributes. 2767 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2768 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2769 bool IsMemberFunction, SourceLocation Loc, 2770 SourceRange Range, VariadicCallType CallType) { 2771 // FIXME: We should check as much as we can in the template definition. 2772 if (CurContext->isDependentContext()) 2773 return; 2774 2775 // Printf and scanf checking. 2776 llvm::SmallBitVector CheckedVarArgs; 2777 if (FDecl) { 2778 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2779 // Only create vector if there are format attributes. 2780 CheckedVarArgs.resize(Args.size()); 2781 2782 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2783 CheckedVarArgs); 2784 } 2785 } 2786 2787 // Refuse POD arguments that weren't caught by the format string 2788 // checks above. 2789 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2790 if (CallType != VariadicDoesNotApply && 2791 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2792 unsigned NumParams = Proto ? Proto->getNumParams() 2793 : FDecl && isa<FunctionDecl>(FDecl) 2794 ? cast<FunctionDecl>(FDecl)->getNumParams() 2795 : FDecl && isa<ObjCMethodDecl>(FDecl) 2796 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2797 : 0; 2798 2799 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2800 // Args[ArgIdx] can be null in malformed code. 2801 if (const Expr *Arg = Args[ArgIdx]) { 2802 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2803 checkVariadicArgument(Arg, CallType); 2804 } 2805 } 2806 } 2807 2808 if (FDecl || Proto) { 2809 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2810 2811 // Type safety checking. 2812 if (FDecl) { 2813 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2814 CheckArgumentWithTypeTag(I, Args, Loc); 2815 } 2816 } 2817 2818 if (FD) 2819 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 2820 } 2821 2822 /// CheckConstructorCall - Check a constructor call for correctness and safety 2823 /// properties not enforced by the C type system. 2824 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2825 ArrayRef<const Expr *> Args, 2826 const FunctionProtoType *Proto, 2827 SourceLocation Loc) { 2828 VariadicCallType CallType = 2829 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2830 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 2831 Loc, SourceRange(), CallType); 2832 } 2833 2834 /// CheckFunctionCall - Check a direct function call for various correctness 2835 /// and safety properties not strictly enforced by the C type system. 2836 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2837 const FunctionProtoType *Proto) { 2838 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2839 isa<CXXMethodDecl>(FDecl); 2840 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2841 IsMemberOperatorCall; 2842 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2843 TheCall->getCallee()); 2844 Expr** Args = TheCall->getArgs(); 2845 unsigned NumArgs = TheCall->getNumArgs(); 2846 2847 Expr *ImplicitThis = nullptr; 2848 if (IsMemberOperatorCall) { 2849 // If this is a call to a member operator, hide the first argument 2850 // from checkCall. 2851 // FIXME: Our choice of AST representation here is less than ideal. 2852 ImplicitThis = Args[0]; 2853 ++Args; 2854 --NumArgs; 2855 } else if (IsMemberFunction) 2856 ImplicitThis = 2857 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 2858 2859 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 2860 IsMemberFunction, TheCall->getRParenLoc(), 2861 TheCall->getCallee()->getSourceRange(), CallType); 2862 2863 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2864 // None of the checks below are needed for functions that don't have 2865 // simple names (e.g., C++ conversion functions). 2866 if (!FnInfo) 2867 return false; 2868 2869 CheckAbsoluteValueFunction(TheCall, FDecl); 2870 CheckMaxUnsignedZero(TheCall, FDecl); 2871 2872 if (getLangOpts().ObjC1) 2873 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2874 2875 unsigned CMId = FDecl->getMemoryFunctionKind(); 2876 if (CMId == 0) 2877 return false; 2878 2879 // Handle memory setting and copying functions. 2880 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2881 CheckStrlcpycatArguments(TheCall, FnInfo); 2882 else if (CMId == Builtin::BIstrncat) 2883 CheckStrncatArguments(TheCall, FnInfo); 2884 else 2885 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2886 2887 return false; 2888 } 2889 2890 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2891 ArrayRef<const Expr *> Args) { 2892 VariadicCallType CallType = 2893 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2894 2895 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 2896 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2897 CallType); 2898 2899 return false; 2900 } 2901 2902 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2903 const FunctionProtoType *Proto) { 2904 QualType Ty; 2905 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2906 Ty = V->getType().getNonReferenceType(); 2907 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2908 Ty = F->getType().getNonReferenceType(); 2909 else 2910 return false; 2911 2912 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2913 !Ty->isFunctionProtoType()) 2914 return false; 2915 2916 VariadicCallType CallType; 2917 if (!Proto || !Proto->isVariadic()) { 2918 CallType = VariadicDoesNotApply; 2919 } else if (Ty->isBlockPointerType()) { 2920 CallType = VariadicBlock; 2921 } else { // Ty->isFunctionPointerType() 2922 CallType = VariadicFunction; 2923 } 2924 2925 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 2926 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2927 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2928 TheCall->getCallee()->getSourceRange(), CallType); 2929 2930 return false; 2931 } 2932 2933 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2934 /// such as function pointers returned from functions. 2935 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2936 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2937 TheCall->getCallee()); 2938 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 2939 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2940 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2941 TheCall->getCallee()->getSourceRange(), CallType); 2942 2943 return false; 2944 } 2945 2946 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2947 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2948 return false; 2949 2950 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2951 switch (Op) { 2952 case AtomicExpr::AO__c11_atomic_init: 2953 case AtomicExpr::AO__opencl_atomic_init: 2954 llvm_unreachable("There is no ordering argument for an init"); 2955 2956 case AtomicExpr::AO__c11_atomic_load: 2957 case AtomicExpr::AO__opencl_atomic_load: 2958 case AtomicExpr::AO__atomic_load_n: 2959 case AtomicExpr::AO__atomic_load: 2960 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2961 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2962 2963 case AtomicExpr::AO__c11_atomic_store: 2964 case AtomicExpr::AO__opencl_atomic_store: 2965 case AtomicExpr::AO__atomic_store: 2966 case AtomicExpr::AO__atomic_store_n: 2967 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2968 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2969 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2970 2971 default: 2972 return true; 2973 } 2974 } 2975 2976 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2977 AtomicExpr::AtomicOp Op) { 2978 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2979 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2980 2981 // All the non-OpenCL operations take one of the following forms. 2982 // The OpenCL operations take the __c11 forms with one extra argument for 2983 // synchronization scope. 2984 enum { 2985 // C __c11_atomic_init(A *, C) 2986 Init, 2987 2988 // C __c11_atomic_load(A *, int) 2989 Load, 2990 2991 // void __atomic_load(A *, CP, int) 2992 LoadCopy, 2993 2994 // void __atomic_store(A *, CP, int) 2995 Copy, 2996 2997 // C __c11_atomic_add(A *, M, int) 2998 Arithmetic, 2999 3000 // C __atomic_exchange_n(A *, CP, int) 3001 Xchg, 3002 3003 // void __atomic_exchange(A *, C *, CP, int) 3004 GNUXchg, 3005 3006 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 3007 C11CmpXchg, 3008 3009 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 3010 GNUCmpXchg 3011 } Form = Init; 3012 3013 const unsigned NumForm = GNUCmpXchg + 1; 3014 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 3015 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 3016 // where: 3017 // C is an appropriate type, 3018 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 3019 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 3020 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 3021 // the int parameters are for orderings. 3022 3023 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 3024 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 3025 "need to update code for modified forms"); 3026 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 3027 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 3028 AtomicExpr::AO__atomic_load, 3029 "need to update code for modified C11 atomics"); 3030 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 3031 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 3032 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 3033 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 3034 IsOpenCL; 3035 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 3036 Op == AtomicExpr::AO__atomic_store_n || 3037 Op == AtomicExpr::AO__atomic_exchange_n || 3038 Op == AtomicExpr::AO__atomic_compare_exchange_n; 3039 bool IsAddSub = false; 3040 3041 switch (Op) { 3042 case AtomicExpr::AO__c11_atomic_init: 3043 case AtomicExpr::AO__opencl_atomic_init: 3044 Form = Init; 3045 break; 3046 3047 case AtomicExpr::AO__c11_atomic_load: 3048 case AtomicExpr::AO__opencl_atomic_load: 3049 case AtomicExpr::AO__atomic_load_n: 3050 Form = Load; 3051 break; 3052 3053 case AtomicExpr::AO__atomic_load: 3054 Form = LoadCopy; 3055 break; 3056 3057 case AtomicExpr::AO__c11_atomic_store: 3058 case AtomicExpr::AO__opencl_atomic_store: 3059 case AtomicExpr::AO__atomic_store: 3060 case AtomicExpr::AO__atomic_store_n: 3061 Form = Copy; 3062 break; 3063 3064 case AtomicExpr::AO__c11_atomic_fetch_add: 3065 case AtomicExpr::AO__c11_atomic_fetch_sub: 3066 case AtomicExpr::AO__opencl_atomic_fetch_add: 3067 case AtomicExpr::AO__opencl_atomic_fetch_sub: 3068 case AtomicExpr::AO__opencl_atomic_fetch_min: 3069 case AtomicExpr::AO__opencl_atomic_fetch_max: 3070 case AtomicExpr::AO__atomic_fetch_add: 3071 case AtomicExpr::AO__atomic_fetch_sub: 3072 case AtomicExpr::AO__atomic_add_fetch: 3073 case AtomicExpr::AO__atomic_sub_fetch: 3074 IsAddSub = true; 3075 LLVM_FALLTHROUGH; 3076 case AtomicExpr::AO__c11_atomic_fetch_and: 3077 case AtomicExpr::AO__c11_atomic_fetch_or: 3078 case AtomicExpr::AO__c11_atomic_fetch_xor: 3079 case AtomicExpr::AO__opencl_atomic_fetch_and: 3080 case AtomicExpr::AO__opencl_atomic_fetch_or: 3081 case AtomicExpr::AO__opencl_atomic_fetch_xor: 3082 case AtomicExpr::AO__atomic_fetch_and: 3083 case AtomicExpr::AO__atomic_fetch_or: 3084 case AtomicExpr::AO__atomic_fetch_xor: 3085 case AtomicExpr::AO__atomic_fetch_nand: 3086 case AtomicExpr::AO__atomic_and_fetch: 3087 case AtomicExpr::AO__atomic_or_fetch: 3088 case AtomicExpr::AO__atomic_xor_fetch: 3089 case AtomicExpr::AO__atomic_nand_fetch: 3090 Form = Arithmetic; 3091 break; 3092 3093 case AtomicExpr::AO__c11_atomic_exchange: 3094 case AtomicExpr::AO__opencl_atomic_exchange: 3095 case AtomicExpr::AO__atomic_exchange_n: 3096 Form = Xchg; 3097 break; 3098 3099 case AtomicExpr::AO__atomic_exchange: 3100 Form = GNUXchg; 3101 break; 3102 3103 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3104 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3105 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 3106 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 3107 Form = C11CmpXchg; 3108 break; 3109 3110 case AtomicExpr::AO__atomic_compare_exchange: 3111 case AtomicExpr::AO__atomic_compare_exchange_n: 3112 Form = GNUCmpXchg; 3113 break; 3114 } 3115 3116 unsigned AdjustedNumArgs = NumArgs[Form]; 3117 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 3118 ++AdjustedNumArgs; 3119 // Check we have the right number of arguments. 3120 if (TheCall->getNumArgs() < AdjustedNumArgs) { 3121 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3122 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3123 << TheCall->getCallee()->getSourceRange(); 3124 return ExprError(); 3125 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 3126 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 3127 diag::err_typecheck_call_too_many_args) 3128 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3129 << TheCall->getCallee()->getSourceRange(); 3130 return ExprError(); 3131 } 3132 3133 // Inspect the first argument of the atomic operation. 3134 Expr *Ptr = TheCall->getArg(0); 3135 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 3136 if (ConvertedPtr.isInvalid()) 3137 return ExprError(); 3138 3139 Ptr = ConvertedPtr.get(); 3140 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 3141 if (!pointerType) { 3142 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3143 << Ptr->getType() << Ptr->getSourceRange(); 3144 return ExprError(); 3145 } 3146 3147 // For a __c11 builtin, this should be a pointer to an _Atomic type. 3148 QualType AtomTy = pointerType->getPointeeType(); // 'A' 3149 QualType ValType = AtomTy; // 'C' 3150 if (IsC11) { 3151 if (!AtomTy->isAtomicType()) { 3152 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 3153 << Ptr->getType() << Ptr->getSourceRange(); 3154 return ExprError(); 3155 } 3156 if (AtomTy.isConstQualified() || 3157 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3158 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 3159 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3160 << Ptr->getSourceRange(); 3161 return ExprError(); 3162 } 3163 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 3164 } else if (Form != Load && Form != LoadCopy) { 3165 if (ValType.isConstQualified()) { 3166 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 3167 << Ptr->getType() << Ptr->getSourceRange(); 3168 return ExprError(); 3169 } 3170 } 3171 3172 // For an arithmetic operation, the implied arithmetic must be well-formed. 3173 if (Form == Arithmetic) { 3174 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3175 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 3176 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3177 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3178 return ExprError(); 3179 } 3180 if (!IsAddSub && !ValType->isIntegerType()) { 3181 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3182 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3183 return ExprError(); 3184 } 3185 if (IsC11 && ValType->isPointerType() && 3186 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3187 diag::err_incomplete_type)) { 3188 return ExprError(); 3189 } 3190 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3191 // For __atomic_*_n operations, the value type must be a scalar integral or 3192 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3193 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3194 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3195 return ExprError(); 3196 } 3197 3198 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3199 !AtomTy->isScalarType()) { 3200 // For GNU atomics, require a trivially-copyable type. This is not part of 3201 // the GNU atomics specification, but we enforce it for sanity. 3202 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3203 << Ptr->getType() << Ptr->getSourceRange(); 3204 return ExprError(); 3205 } 3206 3207 switch (ValType.getObjCLifetime()) { 3208 case Qualifiers::OCL_None: 3209 case Qualifiers::OCL_ExplicitNone: 3210 // okay 3211 break; 3212 3213 case Qualifiers::OCL_Weak: 3214 case Qualifiers::OCL_Strong: 3215 case Qualifiers::OCL_Autoreleasing: 3216 // FIXME: Can this happen? By this point, ValType should be known 3217 // to be trivially copyable. 3218 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3219 << ValType << Ptr->getSourceRange(); 3220 return ExprError(); 3221 } 3222 3223 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 3224 // volatile-ness of the pointee-type inject itself into the result or the 3225 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 3226 ValType.removeLocalVolatile(); 3227 ValType.removeLocalConst(); 3228 QualType ResultType = ValType; 3229 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3230 Form == Init) 3231 ResultType = Context.VoidTy; 3232 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3233 ResultType = Context.BoolTy; 3234 3235 // The type of a parameter passed 'by value'. In the GNU atomics, such 3236 // arguments are actually passed as pointers. 3237 QualType ByValType = ValType; // 'CP' 3238 if (!IsC11 && !IsN) 3239 ByValType = Ptr->getType(); 3240 3241 // The first argument --- the pointer --- has a fixed type; we 3242 // deduce the types of the rest of the arguments accordingly. Walk 3243 // the remaining arguments, converting them to the deduced value type. 3244 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) { 3245 QualType Ty; 3246 if (i < NumVals[Form] + 1) { 3247 switch (i) { 3248 case 1: 3249 // The second argument is the non-atomic operand. For arithmetic, this 3250 // is always passed by value, and for a compare_exchange it is always 3251 // passed by address. For the rest, GNU uses by-address and C11 uses 3252 // by-value. 3253 assert(Form != Load); 3254 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3255 Ty = ValType; 3256 else if (Form == Copy || Form == Xchg) 3257 Ty = ByValType; 3258 else if (Form == Arithmetic) 3259 Ty = Context.getPointerDiffType(); 3260 else { 3261 Expr *ValArg = TheCall->getArg(i); 3262 // Treat this argument as _Nonnull as we want to show a warning if 3263 // NULL is passed into it. 3264 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3265 LangAS AS = LangAS::Default; 3266 // Keep address space of non-atomic pointer type. 3267 if (const PointerType *PtrTy = 3268 ValArg->getType()->getAs<PointerType>()) { 3269 AS = PtrTy->getPointeeType().getAddressSpace(); 3270 } 3271 Ty = Context.getPointerType( 3272 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3273 } 3274 break; 3275 case 2: 3276 // The third argument to compare_exchange / GNU exchange is a 3277 // (pointer to a) desired value. 3278 Ty = ByValType; 3279 break; 3280 case 3: 3281 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3282 Ty = Context.BoolTy; 3283 break; 3284 } 3285 } else { 3286 // The order(s) and scope are always converted to int. 3287 Ty = Context.IntTy; 3288 } 3289 3290 InitializedEntity Entity = 3291 InitializedEntity::InitializeParameter(Context, Ty, false); 3292 ExprResult Arg = TheCall->getArg(i); 3293 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3294 if (Arg.isInvalid()) 3295 return true; 3296 TheCall->setArg(i, Arg.get()); 3297 } 3298 3299 // Permute the arguments into a 'consistent' order. 3300 SmallVector<Expr*, 5> SubExprs; 3301 SubExprs.push_back(Ptr); 3302 switch (Form) { 3303 case Init: 3304 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3305 SubExprs.push_back(TheCall->getArg(1)); // Val1 3306 break; 3307 case Load: 3308 SubExprs.push_back(TheCall->getArg(1)); // Order 3309 break; 3310 case LoadCopy: 3311 case Copy: 3312 case Arithmetic: 3313 case Xchg: 3314 SubExprs.push_back(TheCall->getArg(2)); // Order 3315 SubExprs.push_back(TheCall->getArg(1)); // Val1 3316 break; 3317 case GNUXchg: 3318 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3319 SubExprs.push_back(TheCall->getArg(3)); // Order 3320 SubExprs.push_back(TheCall->getArg(1)); // Val1 3321 SubExprs.push_back(TheCall->getArg(2)); // Val2 3322 break; 3323 case C11CmpXchg: 3324 SubExprs.push_back(TheCall->getArg(3)); // Order 3325 SubExprs.push_back(TheCall->getArg(1)); // Val1 3326 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3327 SubExprs.push_back(TheCall->getArg(2)); // Val2 3328 break; 3329 case GNUCmpXchg: 3330 SubExprs.push_back(TheCall->getArg(4)); // Order 3331 SubExprs.push_back(TheCall->getArg(1)); // Val1 3332 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3333 SubExprs.push_back(TheCall->getArg(2)); // Val2 3334 SubExprs.push_back(TheCall->getArg(3)); // Weak 3335 break; 3336 } 3337 3338 if (SubExprs.size() >= 2 && Form != Init) { 3339 llvm::APSInt Result(32); 3340 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3341 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3342 Diag(SubExprs[1]->getLocStart(), 3343 diag::warn_atomic_op_has_invalid_memory_order) 3344 << SubExprs[1]->getSourceRange(); 3345 } 3346 3347 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 3348 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3349 llvm::APSInt Result(32); 3350 if (Scope->isIntegerConstantExpr(Result, Context) && 3351 !ScopeModel->isValid(Result.getZExtValue())) { 3352 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3353 << Scope->getSourceRange(); 3354 } 3355 SubExprs.push_back(Scope); 3356 } 3357 3358 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3359 SubExprs, ResultType, Op, 3360 TheCall->getRParenLoc()); 3361 3362 if ((Op == AtomicExpr::AO__c11_atomic_load || 3363 Op == AtomicExpr::AO__c11_atomic_store || 3364 Op == AtomicExpr::AO__opencl_atomic_load || 3365 Op == AtomicExpr::AO__opencl_atomic_store ) && 3366 Context.AtomicUsesUnsupportedLibcall(AE)) 3367 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3368 << ((Op == AtomicExpr::AO__c11_atomic_load || 3369 Op == AtomicExpr::AO__opencl_atomic_load) 3370 ? 0 : 1); 3371 3372 return AE; 3373 } 3374 3375 /// checkBuiltinArgument - Given a call to a builtin function, perform 3376 /// normal type-checking on the given argument, updating the call in 3377 /// place. This is useful when a builtin function requires custom 3378 /// type-checking for some of its arguments but not necessarily all of 3379 /// them. 3380 /// 3381 /// Returns true on error. 3382 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3383 FunctionDecl *Fn = E->getDirectCallee(); 3384 assert(Fn && "builtin call without direct callee!"); 3385 3386 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3387 InitializedEntity Entity = 3388 InitializedEntity::InitializeParameter(S.Context, Param); 3389 3390 ExprResult Arg = E->getArg(0); 3391 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3392 if (Arg.isInvalid()) 3393 return true; 3394 3395 E->setArg(ArgIndex, Arg.get()); 3396 return false; 3397 } 3398 3399 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3400 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3401 /// type of its first argument. The main ActOnCallExpr routines have already 3402 /// promoted the types of arguments because all of these calls are prototyped as 3403 /// void(...). 3404 /// 3405 /// This function goes through and does final semantic checking for these 3406 /// builtins, 3407 ExprResult 3408 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3409 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3410 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3411 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3412 3413 // Ensure that we have at least one argument to do type inference from. 3414 if (TheCall->getNumArgs() < 1) { 3415 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3416 << 0 << 1 << TheCall->getNumArgs() 3417 << TheCall->getCallee()->getSourceRange(); 3418 return ExprError(); 3419 } 3420 3421 // Inspect the first argument of the atomic builtin. This should always be 3422 // a pointer type, whose element is an integral scalar or pointer type. 3423 // Because it is a pointer type, we don't have to worry about any implicit 3424 // casts here. 3425 // FIXME: We don't allow floating point scalars as input. 3426 Expr *FirstArg = TheCall->getArg(0); 3427 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3428 if (FirstArgResult.isInvalid()) 3429 return ExprError(); 3430 FirstArg = FirstArgResult.get(); 3431 TheCall->setArg(0, FirstArg); 3432 3433 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3434 if (!pointerType) { 3435 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3436 << FirstArg->getType() << FirstArg->getSourceRange(); 3437 return ExprError(); 3438 } 3439 3440 QualType ValType = pointerType->getPointeeType(); 3441 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3442 !ValType->isBlockPointerType()) { 3443 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3444 << FirstArg->getType() << FirstArg->getSourceRange(); 3445 return ExprError(); 3446 } 3447 3448 if (ValType.isConstQualified()) { 3449 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const) 3450 << FirstArg->getType() << FirstArg->getSourceRange(); 3451 return ExprError(); 3452 } 3453 3454 switch (ValType.getObjCLifetime()) { 3455 case Qualifiers::OCL_None: 3456 case Qualifiers::OCL_ExplicitNone: 3457 // okay 3458 break; 3459 3460 case Qualifiers::OCL_Weak: 3461 case Qualifiers::OCL_Strong: 3462 case Qualifiers::OCL_Autoreleasing: 3463 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3464 << ValType << FirstArg->getSourceRange(); 3465 return ExprError(); 3466 } 3467 3468 // Strip any qualifiers off ValType. 3469 ValType = ValType.getUnqualifiedType(); 3470 3471 // The majority of builtins return a value, but a few have special return 3472 // types, so allow them to override appropriately below. 3473 QualType ResultType = ValType; 3474 3475 // We need to figure out which concrete builtin this maps onto. For example, 3476 // __sync_fetch_and_add with a 2 byte object turns into 3477 // __sync_fetch_and_add_2. 3478 #define BUILTIN_ROW(x) \ 3479 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3480 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3481 3482 static const unsigned BuiltinIndices[][5] = { 3483 BUILTIN_ROW(__sync_fetch_and_add), 3484 BUILTIN_ROW(__sync_fetch_and_sub), 3485 BUILTIN_ROW(__sync_fetch_and_or), 3486 BUILTIN_ROW(__sync_fetch_and_and), 3487 BUILTIN_ROW(__sync_fetch_and_xor), 3488 BUILTIN_ROW(__sync_fetch_and_nand), 3489 3490 BUILTIN_ROW(__sync_add_and_fetch), 3491 BUILTIN_ROW(__sync_sub_and_fetch), 3492 BUILTIN_ROW(__sync_and_and_fetch), 3493 BUILTIN_ROW(__sync_or_and_fetch), 3494 BUILTIN_ROW(__sync_xor_and_fetch), 3495 BUILTIN_ROW(__sync_nand_and_fetch), 3496 3497 BUILTIN_ROW(__sync_val_compare_and_swap), 3498 BUILTIN_ROW(__sync_bool_compare_and_swap), 3499 BUILTIN_ROW(__sync_lock_test_and_set), 3500 BUILTIN_ROW(__sync_lock_release), 3501 BUILTIN_ROW(__sync_swap) 3502 }; 3503 #undef BUILTIN_ROW 3504 3505 // Determine the index of the size. 3506 unsigned SizeIndex; 3507 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3508 case 1: SizeIndex = 0; break; 3509 case 2: SizeIndex = 1; break; 3510 case 4: SizeIndex = 2; break; 3511 case 8: SizeIndex = 3; break; 3512 case 16: SizeIndex = 4; break; 3513 default: 3514 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3515 << FirstArg->getType() << FirstArg->getSourceRange(); 3516 return ExprError(); 3517 } 3518 3519 // Each of these builtins has one pointer argument, followed by some number of 3520 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3521 // that we ignore. Find out which row of BuiltinIndices to read from as well 3522 // as the number of fixed args. 3523 unsigned BuiltinID = FDecl->getBuiltinID(); 3524 unsigned BuiltinIndex, NumFixed = 1; 3525 bool WarnAboutSemanticsChange = false; 3526 switch (BuiltinID) { 3527 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3528 case Builtin::BI__sync_fetch_and_add: 3529 case Builtin::BI__sync_fetch_and_add_1: 3530 case Builtin::BI__sync_fetch_and_add_2: 3531 case Builtin::BI__sync_fetch_and_add_4: 3532 case Builtin::BI__sync_fetch_and_add_8: 3533 case Builtin::BI__sync_fetch_and_add_16: 3534 BuiltinIndex = 0; 3535 break; 3536 3537 case Builtin::BI__sync_fetch_and_sub: 3538 case Builtin::BI__sync_fetch_and_sub_1: 3539 case Builtin::BI__sync_fetch_and_sub_2: 3540 case Builtin::BI__sync_fetch_and_sub_4: 3541 case Builtin::BI__sync_fetch_and_sub_8: 3542 case Builtin::BI__sync_fetch_and_sub_16: 3543 BuiltinIndex = 1; 3544 break; 3545 3546 case Builtin::BI__sync_fetch_and_or: 3547 case Builtin::BI__sync_fetch_and_or_1: 3548 case Builtin::BI__sync_fetch_and_or_2: 3549 case Builtin::BI__sync_fetch_and_or_4: 3550 case Builtin::BI__sync_fetch_and_or_8: 3551 case Builtin::BI__sync_fetch_and_or_16: 3552 BuiltinIndex = 2; 3553 break; 3554 3555 case Builtin::BI__sync_fetch_and_and: 3556 case Builtin::BI__sync_fetch_and_and_1: 3557 case Builtin::BI__sync_fetch_and_and_2: 3558 case Builtin::BI__sync_fetch_and_and_4: 3559 case Builtin::BI__sync_fetch_and_and_8: 3560 case Builtin::BI__sync_fetch_and_and_16: 3561 BuiltinIndex = 3; 3562 break; 3563 3564 case Builtin::BI__sync_fetch_and_xor: 3565 case Builtin::BI__sync_fetch_and_xor_1: 3566 case Builtin::BI__sync_fetch_and_xor_2: 3567 case Builtin::BI__sync_fetch_and_xor_4: 3568 case Builtin::BI__sync_fetch_and_xor_8: 3569 case Builtin::BI__sync_fetch_and_xor_16: 3570 BuiltinIndex = 4; 3571 break; 3572 3573 case Builtin::BI__sync_fetch_and_nand: 3574 case Builtin::BI__sync_fetch_and_nand_1: 3575 case Builtin::BI__sync_fetch_and_nand_2: 3576 case Builtin::BI__sync_fetch_and_nand_4: 3577 case Builtin::BI__sync_fetch_and_nand_8: 3578 case Builtin::BI__sync_fetch_and_nand_16: 3579 BuiltinIndex = 5; 3580 WarnAboutSemanticsChange = true; 3581 break; 3582 3583 case Builtin::BI__sync_add_and_fetch: 3584 case Builtin::BI__sync_add_and_fetch_1: 3585 case Builtin::BI__sync_add_and_fetch_2: 3586 case Builtin::BI__sync_add_and_fetch_4: 3587 case Builtin::BI__sync_add_and_fetch_8: 3588 case Builtin::BI__sync_add_and_fetch_16: 3589 BuiltinIndex = 6; 3590 break; 3591 3592 case Builtin::BI__sync_sub_and_fetch: 3593 case Builtin::BI__sync_sub_and_fetch_1: 3594 case Builtin::BI__sync_sub_and_fetch_2: 3595 case Builtin::BI__sync_sub_and_fetch_4: 3596 case Builtin::BI__sync_sub_and_fetch_8: 3597 case Builtin::BI__sync_sub_and_fetch_16: 3598 BuiltinIndex = 7; 3599 break; 3600 3601 case Builtin::BI__sync_and_and_fetch: 3602 case Builtin::BI__sync_and_and_fetch_1: 3603 case Builtin::BI__sync_and_and_fetch_2: 3604 case Builtin::BI__sync_and_and_fetch_4: 3605 case Builtin::BI__sync_and_and_fetch_8: 3606 case Builtin::BI__sync_and_and_fetch_16: 3607 BuiltinIndex = 8; 3608 break; 3609 3610 case Builtin::BI__sync_or_and_fetch: 3611 case Builtin::BI__sync_or_and_fetch_1: 3612 case Builtin::BI__sync_or_and_fetch_2: 3613 case Builtin::BI__sync_or_and_fetch_4: 3614 case Builtin::BI__sync_or_and_fetch_8: 3615 case Builtin::BI__sync_or_and_fetch_16: 3616 BuiltinIndex = 9; 3617 break; 3618 3619 case Builtin::BI__sync_xor_and_fetch: 3620 case Builtin::BI__sync_xor_and_fetch_1: 3621 case Builtin::BI__sync_xor_and_fetch_2: 3622 case Builtin::BI__sync_xor_and_fetch_4: 3623 case Builtin::BI__sync_xor_and_fetch_8: 3624 case Builtin::BI__sync_xor_and_fetch_16: 3625 BuiltinIndex = 10; 3626 break; 3627 3628 case Builtin::BI__sync_nand_and_fetch: 3629 case Builtin::BI__sync_nand_and_fetch_1: 3630 case Builtin::BI__sync_nand_and_fetch_2: 3631 case Builtin::BI__sync_nand_and_fetch_4: 3632 case Builtin::BI__sync_nand_and_fetch_8: 3633 case Builtin::BI__sync_nand_and_fetch_16: 3634 BuiltinIndex = 11; 3635 WarnAboutSemanticsChange = true; 3636 break; 3637 3638 case Builtin::BI__sync_val_compare_and_swap: 3639 case Builtin::BI__sync_val_compare_and_swap_1: 3640 case Builtin::BI__sync_val_compare_and_swap_2: 3641 case Builtin::BI__sync_val_compare_and_swap_4: 3642 case Builtin::BI__sync_val_compare_and_swap_8: 3643 case Builtin::BI__sync_val_compare_and_swap_16: 3644 BuiltinIndex = 12; 3645 NumFixed = 2; 3646 break; 3647 3648 case Builtin::BI__sync_bool_compare_and_swap: 3649 case Builtin::BI__sync_bool_compare_and_swap_1: 3650 case Builtin::BI__sync_bool_compare_and_swap_2: 3651 case Builtin::BI__sync_bool_compare_and_swap_4: 3652 case Builtin::BI__sync_bool_compare_and_swap_8: 3653 case Builtin::BI__sync_bool_compare_and_swap_16: 3654 BuiltinIndex = 13; 3655 NumFixed = 2; 3656 ResultType = Context.BoolTy; 3657 break; 3658 3659 case Builtin::BI__sync_lock_test_and_set: 3660 case Builtin::BI__sync_lock_test_and_set_1: 3661 case Builtin::BI__sync_lock_test_and_set_2: 3662 case Builtin::BI__sync_lock_test_and_set_4: 3663 case Builtin::BI__sync_lock_test_and_set_8: 3664 case Builtin::BI__sync_lock_test_and_set_16: 3665 BuiltinIndex = 14; 3666 break; 3667 3668 case Builtin::BI__sync_lock_release: 3669 case Builtin::BI__sync_lock_release_1: 3670 case Builtin::BI__sync_lock_release_2: 3671 case Builtin::BI__sync_lock_release_4: 3672 case Builtin::BI__sync_lock_release_8: 3673 case Builtin::BI__sync_lock_release_16: 3674 BuiltinIndex = 15; 3675 NumFixed = 0; 3676 ResultType = Context.VoidTy; 3677 break; 3678 3679 case Builtin::BI__sync_swap: 3680 case Builtin::BI__sync_swap_1: 3681 case Builtin::BI__sync_swap_2: 3682 case Builtin::BI__sync_swap_4: 3683 case Builtin::BI__sync_swap_8: 3684 case Builtin::BI__sync_swap_16: 3685 BuiltinIndex = 16; 3686 break; 3687 } 3688 3689 // Now that we know how many fixed arguments we expect, first check that we 3690 // have at least that many. 3691 if (TheCall->getNumArgs() < 1+NumFixed) { 3692 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3693 << 0 << 1+NumFixed << TheCall->getNumArgs() 3694 << TheCall->getCallee()->getSourceRange(); 3695 return ExprError(); 3696 } 3697 3698 if (WarnAboutSemanticsChange) { 3699 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3700 << TheCall->getCallee()->getSourceRange(); 3701 } 3702 3703 // Get the decl for the concrete builtin from this, we can tell what the 3704 // concrete integer type we should convert to is. 3705 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3706 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3707 FunctionDecl *NewBuiltinDecl; 3708 if (NewBuiltinID == BuiltinID) 3709 NewBuiltinDecl = FDecl; 3710 else { 3711 // Perform builtin lookup to avoid redeclaring it. 3712 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3713 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3714 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3715 assert(Res.getFoundDecl()); 3716 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3717 if (!NewBuiltinDecl) 3718 return ExprError(); 3719 } 3720 3721 // The first argument --- the pointer --- has a fixed type; we 3722 // deduce the types of the rest of the arguments accordingly. Walk 3723 // the remaining arguments, converting them to the deduced value type. 3724 for (unsigned i = 0; i != NumFixed; ++i) { 3725 ExprResult Arg = TheCall->getArg(i+1); 3726 3727 // GCC does an implicit conversion to the pointer or integer ValType. This 3728 // can fail in some cases (1i -> int**), check for this error case now. 3729 // Initialize the argument. 3730 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3731 ValType, /*consume*/ false); 3732 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3733 if (Arg.isInvalid()) 3734 return ExprError(); 3735 3736 // Okay, we have something that *can* be converted to the right type. Check 3737 // to see if there is a potentially weird extension going on here. This can 3738 // happen when you do an atomic operation on something like an char* and 3739 // pass in 42. The 42 gets converted to char. This is even more strange 3740 // for things like 45.123 -> char, etc. 3741 // FIXME: Do this check. 3742 TheCall->setArg(i+1, Arg.get()); 3743 } 3744 3745 ASTContext& Context = this->getASTContext(); 3746 3747 // Create a new DeclRefExpr to refer to the new decl. 3748 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3749 Context, 3750 DRE->getQualifierLoc(), 3751 SourceLocation(), 3752 NewBuiltinDecl, 3753 /*enclosing*/ false, 3754 DRE->getLocation(), 3755 Context.BuiltinFnTy, 3756 DRE->getValueKind()); 3757 3758 // Set the callee in the CallExpr. 3759 // FIXME: This loses syntactic information. 3760 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3761 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3762 CK_BuiltinFnToFnPtr); 3763 TheCall->setCallee(PromotedCall.get()); 3764 3765 // Change the result type of the call to match the original value type. This 3766 // is arbitrary, but the codegen for these builtins ins design to handle it 3767 // gracefully. 3768 TheCall->setType(ResultType); 3769 3770 return TheCallResult; 3771 } 3772 3773 /// SemaBuiltinNontemporalOverloaded - We have a call to 3774 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3775 /// overloaded function based on the pointer type of its last argument. 3776 /// 3777 /// This function goes through and does final semantic checking for these 3778 /// builtins. 3779 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3780 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3781 DeclRefExpr *DRE = 3782 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3783 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3784 unsigned BuiltinID = FDecl->getBuiltinID(); 3785 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3786 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3787 "Unexpected nontemporal load/store builtin!"); 3788 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3789 unsigned numArgs = isStore ? 2 : 1; 3790 3791 // Ensure that we have the proper number of arguments. 3792 if (checkArgCount(*this, TheCall, numArgs)) 3793 return ExprError(); 3794 3795 // Inspect the last argument of the nontemporal builtin. This should always 3796 // be a pointer type, from which we imply the type of the memory access. 3797 // Because it is a pointer type, we don't have to worry about any implicit 3798 // casts here. 3799 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3800 ExprResult PointerArgResult = 3801 DefaultFunctionArrayLvalueConversion(PointerArg); 3802 3803 if (PointerArgResult.isInvalid()) 3804 return ExprError(); 3805 PointerArg = PointerArgResult.get(); 3806 TheCall->setArg(numArgs - 1, PointerArg); 3807 3808 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3809 if (!pointerType) { 3810 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3811 << PointerArg->getType() << PointerArg->getSourceRange(); 3812 return ExprError(); 3813 } 3814 3815 QualType ValType = pointerType->getPointeeType(); 3816 3817 // Strip any qualifiers off ValType. 3818 ValType = ValType.getUnqualifiedType(); 3819 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3820 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3821 !ValType->isVectorType()) { 3822 Diag(DRE->getLocStart(), 3823 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3824 << PointerArg->getType() << PointerArg->getSourceRange(); 3825 return ExprError(); 3826 } 3827 3828 if (!isStore) { 3829 TheCall->setType(ValType); 3830 return TheCallResult; 3831 } 3832 3833 ExprResult ValArg = TheCall->getArg(0); 3834 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3835 Context, ValType, /*consume*/ false); 3836 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3837 if (ValArg.isInvalid()) 3838 return ExprError(); 3839 3840 TheCall->setArg(0, ValArg.get()); 3841 TheCall->setType(Context.VoidTy); 3842 return TheCallResult; 3843 } 3844 3845 /// CheckObjCString - Checks that the argument to the builtin 3846 /// CFString constructor is correct 3847 /// Note: It might also make sense to do the UTF-16 conversion here (would 3848 /// simplify the backend). 3849 bool Sema::CheckObjCString(Expr *Arg) { 3850 Arg = Arg->IgnoreParenCasts(); 3851 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3852 3853 if (!Literal || !Literal->isAscii()) { 3854 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3855 << Arg->getSourceRange(); 3856 return true; 3857 } 3858 3859 if (Literal->containsNonAsciiOrNull()) { 3860 StringRef String = Literal->getString(); 3861 unsigned NumBytes = String.size(); 3862 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3863 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3864 llvm::UTF16 *ToPtr = &ToBuf[0]; 3865 3866 llvm::ConversionResult Result = 3867 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3868 ToPtr + NumBytes, llvm::strictConversion); 3869 // Check for conversion failure. 3870 if (Result != llvm::conversionOK) 3871 Diag(Arg->getLocStart(), 3872 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3873 } 3874 return false; 3875 } 3876 3877 /// CheckObjCString - Checks that the format string argument to the os_log() 3878 /// and os_trace() functions is correct, and converts it to const char *. 3879 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3880 Arg = Arg->IgnoreParenCasts(); 3881 auto *Literal = dyn_cast<StringLiteral>(Arg); 3882 if (!Literal) { 3883 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3884 Literal = ObjcLiteral->getString(); 3885 } 3886 } 3887 3888 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3889 return ExprError( 3890 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3891 << Arg->getSourceRange()); 3892 } 3893 3894 ExprResult Result(Literal); 3895 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3896 InitializedEntity Entity = 3897 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3898 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3899 return Result; 3900 } 3901 3902 /// Check that the user is calling the appropriate va_start builtin for the 3903 /// target and calling convention. 3904 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 3905 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 3906 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 3907 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 3908 bool IsWindows = TT.isOSWindows(); 3909 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 3910 if (IsX64 || IsAArch64) { 3911 CallingConv CC = CC_C; 3912 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 3913 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3914 if (IsMSVAStart) { 3915 // Don't allow this in System V ABI functions. 3916 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 3917 return S.Diag(Fn->getLocStart(), 3918 diag::err_ms_va_start_used_in_sysv_function); 3919 } else { 3920 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 3921 // On x64 Windows, don't allow this in System V ABI functions. 3922 // (Yes, that means there's no corresponding way to support variadic 3923 // System V ABI functions on Windows.) 3924 if ((IsWindows && CC == CC_X86_64SysV) || 3925 (!IsWindows && CC == CC_Win64)) 3926 return S.Diag(Fn->getLocStart(), 3927 diag::err_va_start_used_in_wrong_abi_function) 3928 << !IsWindows; 3929 } 3930 return false; 3931 } 3932 3933 if (IsMSVAStart) 3934 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 3935 return false; 3936 } 3937 3938 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 3939 ParmVarDecl **LastParam = nullptr) { 3940 // Determine whether the current function, block, or obj-c method is variadic 3941 // and get its parameter list. 3942 bool IsVariadic = false; 3943 ArrayRef<ParmVarDecl *> Params; 3944 DeclContext *Caller = S.CurContext; 3945 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 3946 IsVariadic = Block->isVariadic(); 3947 Params = Block->parameters(); 3948 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 3949 IsVariadic = FD->isVariadic(); 3950 Params = FD->parameters(); 3951 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 3952 IsVariadic = MD->isVariadic(); 3953 // FIXME: This isn't correct for methods (results in bogus warning). 3954 Params = MD->parameters(); 3955 } else if (isa<CapturedDecl>(Caller)) { 3956 // We don't support va_start in a CapturedDecl. 3957 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 3958 return true; 3959 } else { 3960 // This must be some other declcontext that parses exprs. 3961 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 3962 return true; 3963 } 3964 3965 if (!IsVariadic) { 3966 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 3967 return true; 3968 } 3969 3970 if (LastParam) 3971 *LastParam = Params.empty() ? nullptr : Params.back(); 3972 3973 return false; 3974 } 3975 3976 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3977 /// for validity. Emit an error and return true on failure; return false 3978 /// on success. 3979 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 3980 Expr *Fn = TheCall->getCallee(); 3981 3982 if (checkVAStartABI(*this, BuiltinID, Fn)) 3983 return true; 3984 3985 if (TheCall->getNumArgs() > 2) { 3986 Diag(TheCall->getArg(2)->getLocStart(), 3987 diag::err_typecheck_call_too_many_args) 3988 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3989 << Fn->getSourceRange() 3990 << SourceRange(TheCall->getArg(2)->getLocStart(), 3991 (*(TheCall->arg_end()-1))->getLocEnd()); 3992 return true; 3993 } 3994 3995 if (TheCall->getNumArgs() < 2) { 3996 return Diag(TheCall->getLocEnd(), 3997 diag::err_typecheck_call_too_few_args_at_least) 3998 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3999 } 4000 4001 // Type-check the first argument normally. 4002 if (checkBuiltinArgument(*this, TheCall, 0)) 4003 return true; 4004 4005 // Check that the current function is variadic, and get its last parameter. 4006 ParmVarDecl *LastParam; 4007 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 4008 return true; 4009 4010 // Verify that the second argument to the builtin is the last argument of the 4011 // current function or method. 4012 bool SecondArgIsLastNamedArgument = false; 4013 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 4014 4015 // These are valid if SecondArgIsLastNamedArgument is false after the next 4016 // block. 4017 QualType Type; 4018 SourceLocation ParamLoc; 4019 bool IsCRegister = false; 4020 4021 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 4022 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 4023 SecondArgIsLastNamedArgument = PV == LastParam; 4024 4025 Type = PV->getType(); 4026 ParamLoc = PV->getLocation(); 4027 IsCRegister = 4028 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 4029 } 4030 } 4031 4032 if (!SecondArgIsLastNamedArgument) 4033 Diag(TheCall->getArg(1)->getLocStart(), 4034 diag::warn_second_arg_of_va_start_not_last_named_param); 4035 else if (IsCRegister || Type->isReferenceType() || 4036 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 4037 // Promotable integers are UB, but enumerations need a bit of 4038 // extra checking to see what their promotable type actually is. 4039 if (!Type->isPromotableIntegerType()) 4040 return false; 4041 if (!Type->isEnumeralType()) 4042 return true; 4043 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 4044 return !(ED && 4045 Context.typesAreCompatible(ED->getPromotionType(), Type)); 4046 }()) { 4047 unsigned Reason = 0; 4048 if (Type->isReferenceType()) Reason = 1; 4049 else if (IsCRegister) Reason = 2; 4050 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 4051 Diag(ParamLoc, diag::note_parameter_type) << Type; 4052 } 4053 4054 TheCall->setType(Context.VoidTy); 4055 return false; 4056 } 4057 4058 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 4059 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 4060 // const char *named_addr); 4061 4062 Expr *Func = Call->getCallee(); 4063 4064 if (Call->getNumArgs() < 3) 4065 return Diag(Call->getLocEnd(), 4066 diag::err_typecheck_call_too_few_args_at_least) 4067 << 0 /*function call*/ << 3 << Call->getNumArgs(); 4068 4069 // Type-check the first argument normally. 4070 if (checkBuiltinArgument(*this, Call, 0)) 4071 return true; 4072 4073 // Check that the current function is variadic. 4074 if (checkVAStartIsInVariadicFunction(*this, Func)) 4075 return true; 4076 4077 // __va_start on Windows does not validate the parameter qualifiers 4078 4079 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 4080 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 4081 4082 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 4083 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 4084 4085 const QualType &ConstCharPtrTy = 4086 Context.getPointerType(Context.CharTy.withConst()); 4087 if (!Arg1Ty->isPointerType() || 4088 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 4089 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible) 4090 << Arg1->getType() << ConstCharPtrTy 4091 << 1 /* different class */ 4092 << 0 /* qualifier difference */ 4093 << 3 /* parameter mismatch */ 4094 << 2 << Arg1->getType() << ConstCharPtrTy; 4095 4096 const QualType SizeTy = Context.getSizeType(); 4097 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 4098 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible) 4099 << Arg2->getType() << SizeTy 4100 << 1 /* different class */ 4101 << 0 /* qualifier difference */ 4102 << 3 /* parameter mismatch */ 4103 << 3 << Arg2->getType() << SizeTy; 4104 4105 return false; 4106 } 4107 4108 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 4109 /// friends. This is declared to take (...), so we have to check everything. 4110 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 4111 if (TheCall->getNumArgs() < 2) 4112 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4113 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 4114 if (TheCall->getNumArgs() > 2) 4115 return Diag(TheCall->getArg(2)->getLocStart(), 4116 diag::err_typecheck_call_too_many_args) 4117 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4118 << SourceRange(TheCall->getArg(2)->getLocStart(), 4119 (*(TheCall->arg_end()-1))->getLocEnd()); 4120 4121 ExprResult OrigArg0 = TheCall->getArg(0); 4122 ExprResult OrigArg1 = TheCall->getArg(1); 4123 4124 // Do standard promotions between the two arguments, returning their common 4125 // type. 4126 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 4127 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 4128 return true; 4129 4130 // Make sure any conversions are pushed back into the call; this is 4131 // type safe since unordered compare builtins are declared as "_Bool 4132 // foo(...)". 4133 TheCall->setArg(0, OrigArg0.get()); 4134 TheCall->setArg(1, OrigArg1.get()); 4135 4136 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 4137 return false; 4138 4139 // If the common type isn't a real floating type, then the arguments were 4140 // invalid for this operation. 4141 if (Res.isNull() || !Res->isRealFloatingType()) 4142 return Diag(OrigArg0.get()->getLocStart(), 4143 diag::err_typecheck_call_invalid_ordered_compare) 4144 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 4145 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 4146 4147 return false; 4148 } 4149 4150 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 4151 /// __builtin_isnan and friends. This is declared to take (...), so we have 4152 /// to check everything. We expect the last argument to be a floating point 4153 /// value. 4154 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 4155 if (TheCall->getNumArgs() < NumArgs) 4156 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4157 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 4158 if (TheCall->getNumArgs() > NumArgs) 4159 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 4160 diag::err_typecheck_call_too_many_args) 4161 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 4162 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 4163 (*(TheCall->arg_end()-1))->getLocEnd()); 4164 4165 Expr *OrigArg = TheCall->getArg(NumArgs-1); 4166 4167 if (OrigArg->isTypeDependent()) 4168 return false; 4169 4170 // This operation requires a non-_Complex floating-point number. 4171 if (!OrigArg->getType()->isRealFloatingType()) 4172 return Diag(OrigArg->getLocStart(), 4173 diag::err_typecheck_call_invalid_unary_fp) 4174 << OrigArg->getType() << OrigArg->getSourceRange(); 4175 4176 // If this is an implicit conversion from float -> float or double, remove it. 4177 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4178 // Only remove standard FloatCasts, leaving other casts inplace 4179 if (Cast->getCastKind() == CK_FloatingCast) { 4180 Expr *CastArg = Cast->getSubExpr(); 4181 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4182 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4183 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 4184 "promotion from float to either float or double is the only expected cast here"); 4185 Cast->setSubExpr(nullptr); 4186 TheCall->setArg(NumArgs-1, CastArg); 4187 } 4188 } 4189 } 4190 4191 return false; 4192 } 4193 4194 // Customized Sema Checking for VSX builtins that have the following signature: 4195 // vector [...] builtinName(vector [...], vector [...], const int); 4196 // Which takes the same type of vectors (any legal vector type) for the first 4197 // two arguments and takes compile time constant for the third argument. 4198 // Example builtins are : 4199 // vector double vec_xxpermdi(vector double, vector double, int); 4200 // vector short vec_xxsldwi(vector short, vector short, int); 4201 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4202 unsigned ExpectedNumArgs = 3; 4203 if (TheCall->getNumArgs() < ExpectedNumArgs) 4204 return Diag(TheCall->getLocEnd(), 4205 diag::err_typecheck_call_too_few_args_at_least) 4206 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4207 << TheCall->getSourceRange(); 4208 4209 if (TheCall->getNumArgs() > ExpectedNumArgs) 4210 return Diag(TheCall->getLocEnd(), 4211 diag::err_typecheck_call_too_many_args_at_most) 4212 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4213 << TheCall->getSourceRange(); 4214 4215 // Check the third argument is a compile time constant 4216 llvm::APSInt Value; 4217 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4218 return Diag(TheCall->getLocStart(), 4219 diag::err_vsx_builtin_nonconstant_argument) 4220 << 3 /* argument index */ << TheCall->getDirectCallee() 4221 << SourceRange(TheCall->getArg(2)->getLocStart(), 4222 TheCall->getArg(2)->getLocEnd()); 4223 4224 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4225 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4226 4227 // Check the type of argument 1 and argument 2 are vectors. 4228 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4229 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4230 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4231 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4232 << TheCall->getDirectCallee() 4233 << SourceRange(TheCall->getArg(0)->getLocStart(), 4234 TheCall->getArg(1)->getLocEnd()); 4235 } 4236 4237 // Check the first two arguments are the same type. 4238 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4239 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4240 << TheCall->getDirectCallee() 4241 << SourceRange(TheCall->getArg(0)->getLocStart(), 4242 TheCall->getArg(1)->getLocEnd()); 4243 } 4244 4245 // When default clang type checking is turned off and the customized type 4246 // checking is used, the returning type of the function must be explicitly 4247 // set. Otherwise it is _Bool by default. 4248 TheCall->setType(Arg1Ty); 4249 4250 return false; 4251 } 4252 4253 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4254 // This is declared to take (...), so we have to check everything. 4255 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4256 if (TheCall->getNumArgs() < 2) 4257 return ExprError(Diag(TheCall->getLocEnd(), 4258 diag::err_typecheck_call_too_few_args_at_least) 4259 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4260 << TheCall->getSourceRange()); 4261 4262 // Determine which of the following types of shufflevector we're checking: 4263 // 1) unary, vector mask: (lhs, mask) 4264 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4265 QualType resType = TheCall->getArg(0)->getType(); 4266 unsigned numElements = 0; 4267 4268 if (!TheCall->getArg(0)->isTypeDependent() && 4269 !TheCall->getArg(1)->isTypeDependent()) { 4270 QualType LHSType = TheCall->getArg(0)->getType(); 4271 QualType RHSType = TheCall->getArg(1)->getType(); 4272 4273 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4274 return ExprError(Diag(TheCall->getLocStart(), 4275 diag::err_vec_builtin_non_vector) 4276 << TheCall->getDirectCallee() 4277 << SourceRange(TheCall->getArg(0)->getLocStart(), 4278 TheCall->getArg(1)->getLocEnd())); 4279 4280 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4281 unsigned numResElements = TheCall->getNumArgs() - 2; 4282 4283 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4284 // with mask. If so, verify that RHS is an integer vector type with the 4285 // same number of elts as lhs. 4286 if (TheCall->getNumArgs() == 2) { 4287 if (!RHSType->hasIntegerRepresentation() || 4288 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4289 return ExprError(Diag(TheCall->getLocStart(), 4290 diag::err_vec_builtin_incompatible_vector) 4291 << TheCall->getDirectCallee() 4292 << SourceRange(TheCall->getArg(1)->getLocStart(), 4293 TheCall->getArg(1)->getLocEnd())); 4294 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4295 return ExprError(Diag(TheCall->getLocStart(), 4296 diag::err_vec_builtin_incompatible_vector) 4297 << TheCall->getDirectCallee() 4298 << SourceRange(TheCall->getArg(0)->getLocStart(), 4299 TheCall->getArg(1)->getLocEnd())); 4300 } else if (numElements != numResElements) { 4301 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4302 resType = Context.getVectorType(eltType, numResElements, 4303 VectorType::GenericVector); 4304 } 4305 } 4306 4307 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4308 if (TheCall->getArg(i)->isTypeDependent() || 4309 TheCall->getArg(i)->isValueDependent()) 4310 continue; 4311 4312 llvm::APSInt Result(32); 4313 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4314 return ExprError(Diag(TheCall->getLocStart(), 4315 diag::err_shufflevector_nonconstant_argument) 4316 << TheCall->getArg(i)->getSourceRange()); 4317 4318 // Allow -1 which will be translated to undef in the IR. 4319 if (Result.isSigned() && Result.isAllOnesValue()) 4320 continue; 4321 4322 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4323 return ExprError(Diag(TheCall->getLocStart(), 4324 diag::err_shufflevector_argument_too_large) 4325 << TheCall->getArg(i)->getSourceRange()); 4326 } 4327 4328 SmallVector<Expr*, 32> exprs; 4329 4330 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4331 exprs.push_back(TheCall->getArg(i)); 4332 TheCall->setArg(i, nullptr); 4333 } 4334 4335 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4336 TheCall->getCallee()->getLocStart(), 4337 TheCall->getRParenLoc()); 4338 } 4339 4340 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4341 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4342 SourceLocation BuiltinLoc, 4343 SourceLocation RParenLoc) { 4344 ExprValueKind VK = VK_RValue; 4345 ExprObjectKind OK = OK_Ordinary; 4346 QualType DstTy = TInfo->getType(); 4347 QualType SrcTy = E->getType(); 4348 4349 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4350 return ExprError(Diag(BuiltinLoc, 4351 diag::err_convertvector_non_vector) 4352 << E->getSourceRange()); 4353 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4354 return ExprError(Diag(BuiltinLoc, 4355 diag::err_convertvector_non_vector_type)); 4356 4357 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4358 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4359 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4360 if (SrcElts != DstElts) 4361 return ExprError(Diag(BuiltinLoc, 4362 diag::err_convertvector_incompatible_vector) 4363 << E->getSourceRange()); 4364 } 4365 4366 return new (Context) 4367 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4368 } 4369 4370 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4371 // This is declared to take (const void*, ...) and can take two 4372 // optional constant int args. 4373 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4374 unsigned NumArgs = TheCall->getNumArgs(); 4375 4376 if (NumArgs > 3) 4377 return Diag(TheCall->getLocEnd(), 4378 diag::err_typecheck_call_too_many_args_at_most) 4379 << 0 /*function call*/ << 3 << NumArgs 4380 << TheCall->getSourceRange(); 4381 4382 // Argument 0 is checked for us and the remaining arguments must be 4383 // constant integers. 4384 for (unsigned i = 1; i != NumArgs; ++i) 4385 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4386 return true; 4387 4388 return false; 4389 } 4390 4391 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4392 // __assume does not evaluate its arguments, and should warn if its argument 4393 // has side effects. 4394 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4395 Expr *Arg = TheCall->getArg(0); 4396 if (Arg->isInstantiationDependent()) return false; 4397 4398 if (Arg->HasSideEffects(Context)) 4399 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4400 << Arg->getSourceRange() 4401 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4402 4403 return false; 4404 } 4405 4406 /// Handle __builtin_alloca_with_align. This is declared 4407 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4408 /// than 8. 4409 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4410 // The alignment must be a constant integer. 4411 Expr *Arg = TheCall->getArg(1); 4412 4413 // We can't check the value of a dependent argument. 4414 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4415 if (const auto *UE = 4416 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4417 if (UE->getKind() == UETT_AlignOf) 4418 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4419 << Arg->getSourceRange(); 4420 4421 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4422 4423 if (!Result.isPowerOf2()) 4424 return Diag(TheCall->getLocStart(), 4425 diag::err_alignment_not_power_of_two) 4426 << Arg->getSourceRange(); 4427 4428 if (Result < Context.getCharWidth()) 4429 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4430 << (unsigned)Context.getCharWidth() 4431 << Arg->getSourceRange(); 4432 4433 if (Result > std::numeric_limits<int32_t>::max()) 4434 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4435 << std::numeric_limits<int32_t>::max() 4436 << Arg->getSourceRange(); 4437 } 4438 4439 return false; 4440 } 4441 4442 /// Handle __builtin_assume_aligned. This is declared 4443 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4444 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4445 unsigned NumArgs = TheCall->getNumArgs(); 4446 4447 if (NumArgs > 3) 4448 return Diag(TheCall->getLocEnd(), 4449 diag::err_typecheck_call_too_many_args_at_most) 4450 << 0 /*function call*/ << 3 << NumArgs 4451 << TheCall->getSourceRange(); 4452 4453 // The alignment must be a constant integer. 4454 Expr *Arg = TheCall->getArg(1); 4455 4456 // We can't check the value of a dependent argument. 4457 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4458 llvm::APSInt Result; 4459 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4460 return true; 4461 4462 if (!Result.isPowerOf2()) 4463 return Diag(TheCall->getLocStart(), 4464 diag::err_alignment_not_power_of_two) 4465 << Arg->getSourceRange(); 4466 } 4467 4468 if (NumArgs > 2) { 4469 ExprResult Arg(TheCall->getArg(2)); 4470 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4471 Context.getSizeType(), false); 4472 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4473 if (Arg.isInvalid()) return true; 4474 TheCall->setArg(2, Arg.get()); 4475 } 4476 4477 return false; 4478 } 4479 4480 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4481 unsigned BuiltinID = 4482 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4483 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4484 4485 unsigned NumArgs = TheCall->getNumArgs(); 4486 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4487 if (NumArgs < NumRequiredArgs) { 4488 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4489 << 0 /* function call */ << NumRequiredArgs << NumArgs 4490 << TheCall->getSourceRange(); 4491 } 4492 if (NumArgs >= NumRequiredArgs + 0x100) { 4493 return Diag(TheCall->getLocEnd(), 4494 diag::err_typecheck_call_too_many_args_at_most) 4495 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4496 << TheCall->getSourceRange(); 4497 } 4498 unsigned i = 0; 4499 4500 // For formatting call, check buffer arg. 4501 if (!IsSizeCall) { 4502 ExprResult Arg(TheCall->getArg(i)); 4503 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4504 Context, Context.VoidPtrTy, false); 4505 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4506 if (Arg.isInvalid()) 4507 return true; 4508 TheCall->setArg(i, Arg.get()); 4509 i++; 4510 } 4511 4512 // Check string literal arg. 4513 unsigned FormatIdx = i; 4514 { 4515 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4516 if (Arg.isInvalid()) 4517 return true; 4518 TheCall->setArg(i, Arg.get()); 4519 i++; 4520 } 4521 4522 // Make sure variadic args are scalar. 4523 unsigned FirstDataArg = i; 4524 while (i < NumArgs) { 4525 ExprResult Arg = DefaultVariadicArgumentPromotion( 4526 TheCall->getArg(i), VariadicFunction, nullptr); 4527 if (Arg.isInvalid()) 4528 return true; 4529 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4530 if (ArgSize.getQuantity() >= 0x100) { 4531 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4532 << i << (int)ArgSize.getQuantity() << 0xff 4533 << TheCall->getSourceRange(); 4534 } 4535 TheCall->setArg(i, Arg.get()); 4536 i++; 4537 } 4538 4539 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4540 // call to avoid duplicate diagnostics. 4541 if (!IsSizeCall) { 4542 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4543 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4544 bool Success = CheckFormatArguments( 4545 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4546 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4547 CheckedVarArgs); 4548 if (!Success) 4549 return true; 4550 } 4551 4552 if (IsSizeCall) { 4553 TheCall->setType(Context.getSizeType()); 4554 } else { 4555 TheCall->setType(Context.VoidPtrTy); 4556 } 4557 return false; 4558 } 4559 4560 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4561 /// TheCall is a constant expression. 4562 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4563 llvm::APSInt &Result) { 4564 Expr *Arg = TheCall->getArg(ArgNum); 4565 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4566 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4567 4568 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4569 4570 if (!Arg->isIntegerConstantExpr(Result, Context)) 4571 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4572 << FDecl->getDeclName() << Arg->getSourceRange(); 4573 4574 return false; 4575 } 4576 4577 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4578 /// TheCall is a constant expression in the range [Low, High]. 4579 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4580 int Low, int High) { 4581 llvm::APSInt Result; 4582 4583 // We can't check the value of a dependent argument. 4584 Expr *Arg = TheCall->getArg(ArgNum); 4585 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4586 return false; 4587 4588 // Check constant-ness first. 4589 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4590 return true; 4591 4592 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4593 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4594 << Low << High << Arg->getSourceRange(); 4595 4596 return false; 4597 } 4598 4599 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4600 /// TheCall is a constant expression is a multiple of Num.. 4601 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4602 unsigned Num) { 4603 llvm::APSInt Result; 4604 4605 // We can't check the value of a dependent argument. 4606 Expr *Arg = TheCall->getArg(ArgNum); 4607 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4608 return false; 4609 4610 // Check constant-ness first. 4611 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4612 return true; 4613 4614 if (Result.getSExtValue() % Num != 0) 4615 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4616 << Num << Arg->getSourceRange(); 4617 4618 return false; 4619 } 4620 4621 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4622 /// TheCall is an ARM/AArch64 special register string literal. 4623 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4624 int ArgNum, unsigned ExpectedFieldNum, 4625 bool AllowName) { 4626 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4627 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4628 BuiltinID == ARM::BI__builtin_arm_rsr || 4629 BuiltinID == ARM::BI__builtin_arm_rsrp || 4630 BuiltinID == ARM::BI__builtin_arm_wsr || 4631 BuiltinID == ARM::BI__builtin_arm_wsrp; 4632 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4633 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4634 BuiltinID == AArch64::BI__builtin_arm_rsr || 4635 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4636 BuiltinID == AArch64::BI__builtin_arm_wsr || 4637 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4638 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4639 4640 // We can't check the value of a dependent argument. 4641 Expr *Arg = TheCall->getArg(ArgNum); 4642 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4643 return false; 4644 4645 // Check if the argument is a string literal. 4646 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4647 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4648 << Arg->getSourceRange(); 4649 4650 // Check the type of special register given. 4651 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4652 SmallVector<StringRef, 6> Fields; 4653 Reg.split(Fields, ":"); 4654 4655 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4656 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4657 << Arg->getSourceRange(); 4658 4659 // If the string is the name of a register then we cannot check that it is 4660 // valid here but if the string is of one the forms described in ACLE then we 4661 // can check that the supplied fields are integers and within the valid 4662 // ranges. 4663 if (Fields.size() > 1) { 4664 bool FiveFields = Fields.size() == 5; 4665 4666 bool ValidString = true; 4667 if (IsARMBuiltin) { 4668 ValidString &= Fields[0].startswith_lower("cp") || 4669 Fields[0].startswith_lower("p"); 4670 if (ValidString) 4671 Fields[0] = 4672 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4673 4674 ValidString &= Fields[2].startswith_lower("c"); 4675 if (ValidString) 4676 Fields[2] = Fields[2].drop_front(1); 4677 4678 if (FiveFields) { 4679 ValidString &= Fields[3].startswith_lower("c"); 4680 if (ValidString) 4681 Fields[3] = Fields[3].drop_front(1); 4682 } 4683 } 4684 4685 SmallVector<int, 5> Ranges; 4686 if (FiveFields) 4687 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4688 else 4689 Ranges.append({15, 7, 15}); 4690 4691 for (unsigned i=0; i<Fields.size(); ++i) { 4692 int IntField; 4693 ValidString &= !Fields[i].getAsInteger(10, IntField); 4694 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4695 } 4696 4697 if (!ValidString) 4698 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4699 << Arg->getSourceRange(); 4700 } else if (IsAArch64Builtin && Fields.size() == 1) { 4701 // If the register name is one of those that appear in the condition below 4702 // and the special register builtin being used is one of the write builtins, 4703 // then we require that the argument provided for writing to the register 4704 // is an integer constant expression. This is because it will be lowered to 4705 // an MSR (immediate) instruction, so we need to know the immediate at 4706 // compile time. 4707 if (TheCall->getNumArgs() != 2) 4708 return false; 4709 4710 std::string RegLower = Reg.lower(); 4711 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4712 RegLower != "pan" && RegLower != "uao") 4713 return false; 4714 4715 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4716 } 4717 4718 return false; 4719 } 4720 4721 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4722 /// This checks that the target supports __builtin_longjmp and 4723 /// that val is a constant 1. 4724 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4725 if (!Context.getTargetInfo().hasSjLjLowering()) 4726 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4727 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4728 4729 Expr *Arg = TheCall->getArg(1); 4730 llvm::APSInt Result; 4731 4732 // TODO: This is less than ideal. Overload this to take a value. 4733 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4734 return true; 4735 4736 if (Result != 1) 4737 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4738 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4739 4740 return false; 4741 } 4742 4743 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4744 /// This checks that the target supports __builtin_setjmp. 4745 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4746 if (!Context.getTargetInfo().hasSjLjLowering()) 4747 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4748 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4749 return false; 4750 } 4751 4752 namespace { 4753 4754 class UncoveredArgHandler { 4755 enum { Unknown = -1, AllCovered = -2 }; 4756 4757 signed FirstUncoveredArg = Unknown; 4758 SmallVector<const Expr *, 4> DiagnosticExprs; 4759 4760 public: 4761 UncoveredArgHandler() = default; 4762 4763 bool hasUncoveredArg() const { 4764 return (FirstUncoveredArg >= 0); 4765 } 4766 4767 unsigned getUncoveredArg() const { 4768 assert(hasUncoveredArg() && "no uncovered argument"); 4769 return FirstUncoveredArg; 4770 } 4771 4772 void setAllCovered() { 4773 // A string has been found with all arguments covered, so clear out 4774 // the diagnostics. 4775 DiagnosticExprs.clear(); 4776 FirstUncoveredArg = AllCovered; 4777 } 4778 4779 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4780 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4781 4782 // Don't update if a previous string covers all arguments. 4783 if (FirstUncoveredArg == AllCovered) 4784 return; 4785 4786 // UncoveredArgHandler tracks the highest uncovered argument index 4787 // and with it all the strings that match this index. 4788 if (NewFirstUncoveredArg == FirstUncoveredArg) 4789 DiagnosticExprs.push_back(StrExpr); 4790 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4791 DiagnosticExprs.clear(); 4792 DiagnosticExprs.push_back(StrExpr); 4793 FirstUncoveredArg = NewFirstUncoveredArg; 4794 } 4795 } 4796 4797 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4798 }; 4799 4800 enum StringLiteralCheckType { 4801 SLCT_NotALiteral, 4802 SLCT_UncheckedLiteral, 4803 SLCT_CheckedLiteral 4804 }; 4805 4806 } // namespace 4807 4808 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4809 BinaryOperatorKind BinOpKind, 4810 bool AddendIsRight) { 4811 unsigned BitWidth = Offset.getBitWidth(); 4812 unsigned AddendBitWidth = Addend.getBitWidth(); 4813 // There might be negative interim results. 4814 if (Addend.isUnsigned()) { 4815 Addend = Addend.zext(++AddendBitWidth); 4816 Addend.setIsSigned(true); 4817 } 4818 // Adjust the bit width of the APSInts. 4819 if (AddendBitWidth > BitWidth) { 4820 Offset = Offset.sext(AddendBitWidth); 4821 BitWidth = AddendBitWidth; 4822 } else if (BitWidth > AddendBitWidth) { 4823 Addend = Addend.sext(BitWidth); 4824 } 4825 4826 bool Ov = false; 4827 llvm::APSInt ResOffset = Offset; 4828 if (BinOpKind == BO_Add) 4829 ResOffset = Offset.sadd_ov(Addend, Ov); 4830 else { 4831 assert(AddendIsRight && BinOpKind == BO_Sub && 4832 "operator must be add or sub with addend on the right"); 4833 ResOffset = Offset.ssub_ov(Addend, Ov); 4834 } 4835 4836 // We add an offset to a pointer here so we should support an offset as big as 4837 // possible. 4838 if (Ov) { 4839 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 4840 "index (intermediate) result too big"); 4841 Offset = Offset.sext(2 * BitWidth); 4842 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4843 return; 4844 } 4845 4846 Offset = ResOffset; 4847 } 4848 4849 namespace { 4850 4851 // This is a wrapper class around StringLiteral to support offsetted string 4852 // literals as format strings. It takes the offset into account when returning 4853 // the string and its length or the source locations to display notes correctly. 4854 class FormatStringLiteral { 4855 const StringLiteral *FExpr; 4856 int64_t Offset; 4857 4858 public: 4859 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4860 : FExpr(fexpr), Offset(Offset) {} 4861 4862 StringRef getString() const { 4863 return FExpr->getString().drop_front(Offset); 4864 } 4865 4866 unsigned getByteLength() const { 4867 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4868 } 4869 4870 unsigned getLength() const { return FExpr->getLength() - Offset; } 4871 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4872 4873 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4874 4875 QualType getType() const { return FExpr->getType(); } 4876 4877 bool isAscii() const { return FExpr->isAscii(); } 4878 bool isWide() const { return FExpr->isWide(); } 4879 bool isUTF8() const { return FExpr->isUTF8(); } 4880 bool isUTF16() const { return FExpr->isUTF16(); } 4881 bool isUTF32() const { return FExpr->isUTF32(); } 4882 bool isPascal() const { return FExpr->isPascal(); } 4883 4884 SourceLocation getLocationOfByte( 4885 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4886 const TargetInfo &Target, unsigned *StartToken = nullptr, 4887 unsigned *StartTokenByteOffset = nullptr) const { 4888 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4889 StartToken, StartTokenByteOffset); 4890 } 4891 4892 SourceLocation getLocStart() const LLVM_READONLY { 4893 return FExpr->getLocStart().getLocWithOffset(Offset); 4894 } 4895 4896 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4897 }; 4898 4899 } // namespace 4900 4901 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4902 const Expr *OrigFormatExpr, 4903 ArrayRef<const Expr *> Args, 4904 bool HasVAListArg, unsigned format_idx, 4905 unsigned firstDataArg, 4906 Sema::FormatStringType Type, 4907 bool inFunctionCall, 4908 Sema::VariadicCallType CallType, 4909 llvm::SmallBitVector &CheckedVarArgs, 4910 UncoveredArgHandler &UncoveredArg); 4911 4912 // Determine if an expression is a string literal or constant string. 4913 // If this function returns false on the arguments to a function expecting a 4914 // format string, we will usually need to emit a warning. 4915 // True string literals are then checked by CheckFormatString. 4916 static StringLiteralCheckType 4917 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4918 bool HasVAListArg, unsigned format_idx, 4919 unsigned firstDataArg, Sema::FormatStringType Type, 4920 Sema::VariadicCallType CallType, bool InFunctionCall, 4921 llvm::SmallBitVector &CheckedVarArgs, 4922 UncoveredArgHandler &UncoveredArg, 4923 llvm::APSInt Offset) { 4924 tryAgain: 4925 assert(Offset.isSigned() && "invalid offset"); 4926 4927 if (E->isTypeDependent() || E->isValueDependent()) 4928 return SLCT_NotALiteral; 4929 4930 E = E->IgnoreParenCasts(); 4931 4932 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4933 // Technically -Wformat-nonliteral does not warn about this case. 4934 // The behavior of printf and friends in this case is implementation 4935 // dependent. Ideally if the format string cannot be null then 4936 // it should have a 'nonnull' attribute in the function prototype. 4937 return SLCT_UncheckedLiteral; 4938 4939 switch (E->getStmtClass()) { 4940 case Stmt::BinaryConditionalOperatorClass: 4941 case Stmt::ConditionalOperatorClass: { 4942 // The expression is a literal if both sub-expressions were, and it was 4943 // completely checked only if both sub-expressions were checked. 4944 const AbstractConditionalOperator *C = 4945 cast<AbstractConditionalOperator>(E); 4946 4947 // Determine whether it is necessary to check both sub-expressions, for 4948 // example, because the condition expression is a constant that can be 4949 // evaluated at compile time. 4950 bool CheckLeft = true, CheckRight = true; 4951 4952 bool Cond; 4953 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4954 if (Cond) 4955 CheckRight = false; 4956 else 4957 CheckLeft = false; 4958 } 4959 4960 // We need to maintain the offsets for the right and the left hand side 4961 // separately to check if every possible indexed expression is a valid 4962 // string literal. They might have different offsets for different string 4963 // literals in the end. 4964 StringLiteralCheckType Left; 4965 if (!CheckLeft) 4966 Left = SLCT_UncheckedLiteral; 4967 else { 4968 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4969 HasVAListArg, format_idx, firstDataArg, 4970 Type, CallType, InFunctionCall, 4971 CheckedVarArgs, UncoveredArg, Offset); 4972 if (Left == SLCT_NotALiteral || !CheckRight) { 4973 return Left; 4974 } 4975 } 4976 4977 StringLiteralCheckType Right = 4978 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4979 HasVAListArg, format_idx, firstDataArg, 4980 Type, CallType, InFunctionCall, CheckedVarArgs, 4981 UncoveredArg, Offset); 4982 4983 return (CheckLeft && Left < Right) ? Left : Right; 4984 } 4985 4986 case Stmt::ImplicitCastExprClass: 4987 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4988 goto tryAgain; 4989 4990 case Stmt::OpaqueValueExprClass: 4991 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4992 E = src; 4993 goto tryAgain; 4994 } 4995 return SLCT_NotALiteral; 4996 4997 case Stmt::PredefinedExprClass: 4998 // While __func__, etc., are technically not string literals, they 4999 // cannot contain format specifiers and thus are not a security 5000 // liability. 5001 return SLCT_UncheckedLiteral; 5002 5003 case Stmt::DeclRefExprClass: { 5004 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 5005 5006 // As an exception, do not flag errors for variables binding to 5007 // const string literals. 5008 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 5009 bool isConstant = false; 5010 QualType T = DR->getType(); 5011 5012 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 5013 isConstant = AT->getElementType().isConstant(S.Context); 5014 } else if (const PointerType *PT = T->getAs<PointerType>()) { 5015 isConstant = T.isConstant(S.Context) && 5016 PT->getPointeeType().isConstant(S.Context); 5017 } else if (T->isObjCObjectPointerType()) { 5018 // In ObjC, there is usually no "const ObjectPointer" type, 5019 // so don't check if the pointee type is constant. 5020 isConstant = T.isConstant(S.Context); 5021 } 5022 5023 if (isConstant) { 5024 if (const Expr *Init = VD->getAnyInitializer()) { 5025 // Look through initializers like const char c[] = { "foo" } 5026 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 5027 if (InitList->isStringLiteralInit()) 5028 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 5029 } 5030 return checkFormatStringExpr(S, Init, Args, 5031 HasVAListArg, format_idx, 5032 firstDataArg, Type, CallType, 5033 /*InFunctionCall*/ false, CheckedVarArgs, 5034 UncoveredArg, Offset); 5035 } 5036 } 5037 5038 // For vprintf* functions (i.e., HasVAListArg==true), we add a 5039 // special check to see if the format string is a function parameter 5040 // of the function calling the printf function. If the function 5041 // has an attribute indicating it is a printf-like function, then we 5042 // should suppress warnings concerning non-literals being used in a call 5043 // to a vprintf function. For example: 5044 // 5045 // void 5046 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 5047 // va_list ap; 5048 // va_start(ap, fmt); 5049 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 5050 // ... 5051 // } 5052 if (HasVAListArg) { 5053 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 5054 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 5055 int PVIndex = PV->getFunctionScopeIndex() + 1; 5056 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 5057 // adjust for implicit parameter 5058 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5059 if (MD->isInstance()) 5060 ++PVIndex; 5061 // We also check if the formats are compatible. 5062 // We can't pass a 'scanf' string to a 'printf' function. 5063 if (PVIndex == PVFormat->getFormatIdx() && 5064 Type == S.GetFormatStringType(PVFormat)) 5065 return SLCT_UncheckedLiteral; 5066 } 5067 } 5068 } 5069 } 5070 } 5071 5072 return SLCT_NotALiteral; 5073 } 5074 5075 case Stmt::CallExprClass: 5076 case Stmt::CXXMemberCallExprClass: { 5077 const CallExpr *CE = cast<CallExpr>(E); 5078 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 5079 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 5080 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 5081 return checkFormatStringExpr(S, Arg, Args, 5082 HasVAListArg, format_idx, firstDataArg, 5083 Type, CallType, InFunctionCall, 5084 CheckedVarArgs, UncoveredArg, Offset); 5085 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 5086 unsigned BuiltinID = FD->getBuiltinID(); 5087 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 5088 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 5089 const Expr *Arg = CE->getArg(0); 5090 return checkFormatStringExpr(S, Arg, Args, 5091 HasVAListArg, format_idx, 5092 firstDataArg, Type, CallType, 5093 InFunctionCall, CheckedVarArgs, 5094 UncoveredArg, Offset); 5095 } 5096 } 5097 } 5098 5099 return SLCT_NotALiteral; 5100 } 5101 case Stmt::ObjCMessageExprClass: { 5102 const auto *ME = cast<ObjCMessageExpr>(E); 5103 if (const auto *ND = ME->getMethodDecl()) { 5104 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 5105 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 5106 return checkFormatStringExpr( 5107 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 5108 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 5109 } 5110 } 5111 5112 return SLCT_NotALiteral; 5113 } 5114 case Stmt::ObjCStringLiteralClass: 5115 case Stmt::StringLiteralClass: { 5116 const StringLiteral *StrE = nullptr; 5117 5118 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 5119 StrE = ObjCFExpr->getString(); 5120 else 5121 StrE = cast<StringLiteral>(E); 5122 5123 if (StrE) { 5124 if (Offset.isNegative() || Offset > StrE->getLength()) { 5125 // TODO: It would be better to have an explicit warning for out of 5126 // bounds literals. 5127 return SLCT_NotALiteral; 5128 } 5129 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 5130 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 5131 firstDataArg, Type, InFunctionCall, CallType, 5132 CheckedVarArgs, UncoveredArg); 5133 return SLCT_CheckedLiteral; 5134 } 5135 5136 return SLCT_NotALiteral; 5137 } 5138 case Stmt::BinaryOperatorClass: { 5139 llvm::APSInt LResult; 5140 llvm::APSInt RResult; 5141 5142 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 5143 5144 // A string literal + an int offset is still a string literal. 5145 if (BinOp->isAdditiveOp()) { 5146 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 5147 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 5148 5149 if (LIsInt != RIsInt) { 5150 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 5151 5152 if (LIsInt) { 5153 if (BinOpKind == BO_Add) { 5154 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 5155 E = BinOp->getRHS(); 5156 goto tryAgain; 5157 } 5158 } else { 5159 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 5160 E = BinOp->getLHS(); 5161 goto tryAgain; 5162 } 5163 } 5164 } 5165 5166 return SLCT_NotALiteral; 5167 } 5168 case Stmt::UnaryOperatorClass: { 5169 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 5170 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 5171 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 5172 llvm::APSInt IndexResult; 5173 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5174 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5175 E = ASE->getBase(); 5176 goto tryAgain; 5177 } 5178 } 5179 5180 return SLCT_NotALiteral; 5181 } 5182 5183 default: 5184 return SLCT_NotALiteral; 5185 } 5186 } 5187 5188 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5189 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5190 .Case("scanf", FST_Scanf) 5191 .Cases("printf", "printf0", FST_Printf) 5192 .Cases("NSString", "CFString", FST_NSString) 5193 .Case("strftime", FST_Strftime) 5194 .Case("strfmon", FST_Strfmon) 5195 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5196 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5197 .Case("os_trace", FST_OSLog) 5198 .Case("os_log", FST_OSLog) 5199 .Default(FST_Unknown); 5200 } 5201 5202 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5203 /// functions) for correct use of format strings. 5204 /// Returns true if a format string has been fully checked. 5205 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5206 ArrayRef<const Expr *> Args, 5207 bool IsCXXMember, 5208 VariadicCallType CallType, 5209 SourceLocation Loc, SourceRange Range, 5210 llvm::SmallBitVector &CheckedVarArgs) { 5211 FormatStringInfo FSI; 5212 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5213 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5214 FSI.FirstDataArg, GetFormatStringType(Format), 5215 CallType, Loc, Range, CheckedVarArgs); 5216 return false; 5217 } 5218 5219 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5220 bool HasVAListArg, unsigned format_idx, 5221 unsigned firstDataArg, FormatStringType Type, 5222 VariadicCallType CallType, 5223 SourceLocation Loc, SourceRange Range, 5224 llvm::SmallBitVector &CheckedVarArgs) { 5225 // CHECK: printf/scanf-like function is called with no format string. 5226 if (format_idx >= Args.size()) { 5227 Diag(Loc, diag::warn_missing_format_string) << Range; 5228 return false; 5229 } 5230 5231 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5232 5233 // CHECK: format string is not a string literal. 5234 // 5235 // Dynamically generated format strings are difficult to 5236 // automatically vet at compile time. Requiring that format strings 5237 // are string literals: (1) permits the checking of format strings by 5238 // the compiler and thereby (2) can practically remove the source of 5239 // many format string exploits. 5240 5241 // Format string can be either ObjC string (e.g. @"%d") or 5242 // C string (e.g. "%d") 5243 // ObjC string uses the same format specifiers as C string, so we can use 5244 // the same format string checking logic for both ObjC and C strings. 5245 UncoveredArgHandler UncoveredArg; 5246 StringLiteralCheckType CT = 5247 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5248 format_idx, firstDataArg, Type, CallType, 5249 /*IsFunctionCall*/ true, CheckedVarArgs, 5250 UncoveredArg, 5251 /*no string offset*/ llvm::APSInt(64, false) = 0); 5252 5253 // Generate a diagnostic where an uncovered argument is detected. 5254 if (UncoveredArg.hasUncoveredArg()) { 5255 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5256 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5257 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5258 } 5259 5260 if (CT != SLCT_NotALiteral) 5261 // Literal format string found, check done! 5262 return CT == SLCT_CheckedLiteral; 5263 5264 // Strftime is particular as it always uses a single 'time' argument, 5265 // so it is safe to pass a non-literal string. 5266 if (Type == FST_Strftime) 5267 return false; 5268 5269 // Do not emit diag when the string param is a macro expansion and the 5270 // format is either NSString or CFString. This is a hack to prevent 5271 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5272 // which are usually used in place of NS and CF string literals. 5273 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5274 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5275 return false; 5276 5277 // If there are no arguments specified, warn with -Wformat-security, otherwise 5278 // warn only with -Wformat-nonliteral. 5279 if (Args.size() == firstDataArg) { 5280 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5281 << OrigFormatExpr->getSourceRange(); 5282 switch (Type) { 5283 default: 5284 break; 5285 case FST_Kprintf: 5286 case FST_FreeBSDKPrintf: 5287 case FST_Printf: 5288 Diag(FormatLoc, diag::note_format_security_fixit) 5289 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5290 break; 5291 case FST_NSString: 5292 Diag(FormatLoc, diag::note_format_security_fixit) 5293 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5294 break; 5295 } 5296 } else { 5297 Diag(FormatLoc, diag::warn_format_nonliteral) 5298 << OrigFormatExpr->getSourceRange(); 5299 } 5300 return false; 5301 } 5302 5303 namespace { 5304 5305 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5306 protected: 5307 Sema &S; 5308 const FormatStringLiteral *FExpr; 5309 const Expr *OrigFormatExpr; 5310 const Sema::FormatStringType FSType; 5311 const unsigned FirstDataArg; 5312 const unsigned NumDataArgs; 5313 const char *Beg; // Start of format string. 5314 const bool HasVAListArg; 5315 ArrayRef<const Expr *> Args; 5316 unsigned FormatIdx; 5317 llvm::SmallBitVector CoveredArgs; 5318 bool usesPositionalArgs = false; 5319 bool atFirstArg = true; 5320 bool inFunctionCall; 5321 Sema::VariadicCallType CallType; 5322 llvm::SmallBitVector &CheckedVarArgs; 5323 UncoveredArgHandler &UncoveredArg; 5324 5325 public: 5326 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5327 const Expr *origFormatExpr, 5328 const Sema::FormatStringType type, unsigned firstDataArg, 5329 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5330 ArrayRef<const Expr *> Args, unsigned formatIdx, 5331 bool inFunctionCall, Sema::VariadicCallType callType, 5332 llvm::SmallBitVector &CheckedVarArgs, 5333 UncoveredArgHandler &UncoveredArg) 5334 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5335 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5336 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5337 inFunctionCall(inFunctionCall), CallType(callType), 5338 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5339 CoveredArgs.resize(numDataArgs); 5340 CoveredArgs.reset(); 5341 } 5342 5343 void DoneProcessing(); 5344 5345 void HandleIncompleteSpecifier(const char *startSpecifier, 5346 unsigned specifierLen) override; 5347 5348 void HandleInvalidLengthModifier( 5349 const analyze_format_string::FormatSpecifier &FS, 5350 const analyze_format_string::ConversionSpecifier &CS, 5351 const char *startSpecifier, unsigned specifierLen, 5352 unsigned DiagID); 5353 5354 void HandleNonStandardLengthModifier( 5355 const analyze_format_string::FormatSpecifier &FS, 5356 const char *startSpecifier, unsigned specifierLen); 5357 5358 void HandleNonStandardConversionSpecifier( 5359 const analyze_format_string::ConversionSpecifier &CS, 5360 const char *startSpecifier, unsigned specifierLen); 5361 5362 void HandlePosition(const char *startPos, unsigned posLen) override; 5363 5364 void HandleInvalidPosition(const char *startSpecifier, 5365 unsigned specifierLen, 5366 analyze_format_string::PositionContext p) override; 5367 5368 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5369 5370 void HandleNullChar(const char *nullCharacter) override; 5371 5372 template <typename Range> 5373 static void 5374 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5375 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5376 bool IsStringLocation, Range StringRange, 5377 ArrayRef<FixItHint> Fixit = None); 5378 5379 protected: 5380 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5381 const char *startSpec, 5382 unsigned specifierLen, 5383 const char *csStart, unsigned csLen); 5384 5385 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5386 const char *startSpec, 5387 unsigned specifierLen); 5388 5389 SourceRange getFormatStringRange(); 5390 CharSourceRange getSpecifierRange(const char *startSpecifier, 5391 unsigned specifierLen); 5392 SourceLocation getLocationOfByte(const char *x); 5393 5394 const Expr *getDataArg(unsigned i) const; 5395 5396 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5397 const analyze_format_string::ConversionSpecifier &CS, 5398 const char *startSpecifier, unsigned specifierLen, 5399 unsigned argIndex); 5400 5401 template <typename Range> 5402 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5403 bool IsStringLocation, Range StringRange, 5404 ArrayRef<FixItHint> Fixit = None); 5405 }; 5406 5407 } // namespace 5408 5409 SourceRange CheckFormatHandler::getFormatStringRange() { 5410 return OrigFormatExpr->getSourceRange(); 5411 } 5412 5413 CharSourceRange CheckFormatHandler:: 5414 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5415 SourceLocation Start = getLocationOfByte(startSpecifier); 5416 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5417 5418 // Advance the end SourceLocation by one due to half-open ranges. 5419 End = End.getLocWithOffset(1); 5420 5421 return CharSourceRange::getCharRange(Start, End); 5422 } 5423 5424 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5425 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5426 S.getLangOpts(), S.Context.getTargetInfo()); 5427 } 5428 5429 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5430 unsigned specifierLen){ 5431 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5432 getLocationOfByte(startSpecifier), 5433 /*IsStringLocation*/true, 5434 getSpecifierRange(startSpecifier, specifierLen)); 5435 } 5436 5437 void CheckFormatHandler::HandleInvalidLengthModifier( 5438 const analyze_format_string::FormatSpecifier &FS, 5439 const analyze_format_string::ConversionSpecifier &CS, 5440 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5441 using namespace analyze_format_string; 5442 5443 const LengthModifier &LM = FS.getLengthModifier(); 5444 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5445 5446 // See if we know how to fix this length modifier. 5447 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5448 if (FixedLM) { 5449 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5450 getLocationOfByte(LM.getStart()), 5451 /*IsStringLocation*/true, 5452 getSpecifierRange(startSpecifier, specifierLen)); 5453 5454 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5455 << FixedLM->toString() 5456 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5457 5458 } else { 5459 FixItHint Hint; 5460 if (DiagID == diag::warn_format_nonsensical_length) 5461 Hint = FixItHint::CreateRemoval(LMRange); 5462 5463 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5464 getLocationOfByte(LM.getStart()), 5465 /*IsStringLocation*/true, 5466 getSpecifierRange(startSpecifier, specifierLen), 5467 Hint); 5468 } 5469 } 5470 5471 void CheckFormatHandler::HandleNonStandardLengthModifier( 5472 const analyze_format_string::FormatSpecifier &FS, 5473 const char *startSpecifier, unsigned specifierLen) { 5474 using namespace analyze_format_string; 5475 5476 const LengthModifier &LM = FS.getLengthModifier(); 5477 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5478 5479 // See if we know how to fix this length modifier. 5480 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5481 if (FixedLM) { 5482 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5483 << LM.toString() << 0, 5484 getLocationOfByte(LM.getStart()), 5485 /*IsStringLocation*/true, 5486 getSpecifierRange(startSpecifier, specifierLen)); 5487 5488 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5489 << FixedLM->toString() 5490 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5491 5492 } else { 5493 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5494 << LM.toString() << 0, 5495 getLocationOfByte(LM.getStart()), 5496 /*IsStringLocation*/true, 5497 getSpecifierRange(startSpecifier, specifierLen)); 5498 } 5499 } 5500 5501 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5502 const analyze_format_string::ConversionSpecifier &CS, 5503 const char *startSpecifier, unsigned specifierLen) { 5504 using namespace analyze_format_string; 5505 5506 // See if we know how to fix this conversion specifier. 5507 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5508 if (FixedCS) { 5509 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5510 << CS.toString() << /*conversion specifier*/1, 5511 getLocationOfByte(CS.getStart()), 5512 /*IsStringLocation*/true, 5513 getSpecifierRange(startSpecifier, specifierLen)); 5514 5515 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5516 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5517 << FixedCS->toString() 5518 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5519 } else { 5520 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5521 << CS.toString() << /*conversion specifier*/1, 5522 getLocationOfByte(CS.getStart()), 5523 /*IsStringLocation*/true, 5524 getSpecifierRange(startSpecifier, specifierLen)); 5525 } 5526 } 5527 5528 void CheckFormatHandler::HandlePosition(const char *startPos, 5529 unsigned posLen) { 5530 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5531 getLocationOfByte(startPos), 5532 /*IsStringLocation*/true, 5533 getSpecifierRange(startPos, posLen)); 5534 } 5535 5536 void 5537 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5538 analyze_format_string::PositionContext p) { 5539 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5540 << (unsigned) p, 5541 getLocationOfByte(startPos), /*IsStringLocation*/true, 5542 getSpecifierRange(startPos, posLen)); 5543 } 5544 5545 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5546 unsigned posLen) { 5547 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5548 getLocationOfByte(startPos), 5549 /*IsStringLocation*/true, 5550 getSpecifierRange(startPos, posLen)); 5551 } 5552 5553 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5554 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5555 // The presence of a null character is likely an error. 5556 EmitFormatDiagnostic( 5557 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5558 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5559 getFormatStringRange()); 5560 } 5561 } 5562 5563 // Note that this may return NULL if there was an error parsing or building 5564 // one of the argument expressions. 5565 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5566 return Args[FirstDataArg + i]; 5567 } 5568 5569 void CheckFormatHandler::DoneProcessing() { 5570 // Does the number of data arguments exceed the number of 5571 // format conversions in the format string? 5572 if (!HasVAListArg) { 5573 // Find any arguments that weren't covered. 5574 CoveredArgs.flip(); 5575 signed notCoveredArg = CoveredArgs.find_first(); 5576 if (notCoveredArg >= 0) { 5577 assert((unsigned)notCoveredArg < NumDataArgs); 5578 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5579 } else { 5580 UncoveredArg.setAllCovered(); 5581 } 5582 } 5583 } 5584 5585 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5586 const Expr *ArgExpr) { 5587 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5588 "Invalid state"); 5589 5590 if (!ArgExpr) 5591 return; 5592 5593 SourceLocation Loc = ArgExpr->getLocStart(); 5594 5595 if (S.getSourceManager().isInSystemMacro(Loc)) 5596 return; 5597 5598 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5599 for (auto E : DiagnosticExprs) 5600 PDiag << E->getSourceRange(); 5601 5602 CheckFormatHandler::EmitFormatDiagnostic( 5603 S, IsFunctionCall, DiagnosticExprs[0], 5604 PDiag, Loc, /*IsStringLocation*/false, 5605 DiagnosticExprs[0]->getSourceRange()); 5606 } 5607 5608 bool 5609 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5610 SourceLocation Loc, 5611 const char *startSpec, 5612 unsigned specifierLen, 5613 const char *csStart, 5614 unsigned csLen) { 5615 bool keepGoing = true; 5616 if (argIndex < NumDataArgs) { 5617 // Consider the argument coverered, even though the specifier doesn't 5618 // make sense. 5619 CoveredArgs.set(argIndex); 5620 } 5621 else { 5622 // If argIndex exceeds the number of data arguments we 5623 // don't issue a warning because that is just a cascade of warnings (and 5624 // they may have intended '%%' anyway). We don't want to continue processing 5625 // the format string after this point, however, as we will like just get 5626 // gibberish when trying to match arguments. 5627 keepGoing = false; 5628 } 5629 5630 StringRef Specifier(csStart, csLen); 5631 5632 // If the specifier in non-printable, it could be the first byte of a UTF-8 5633 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5634 // hex value. 5635 std::string CodePointStr; 5636 if (!llvm::sys::locale::isPrint(*csStart)) { 5637 llvm::UTF32 CodePoint; 5638 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5639 const llvm::UTF8 *E = 5640 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5641 llvm::ConversionResult Result = 5642 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5643 5644 if (Result != llvm::conversionOK) { 5645 unsigned char FirstChar = *csStart; 5646 CodePoint = (llvm::UTF32)FirstChar; 5647 } 5648 5649 llvm::raw_string_ostream OS(CodePointStr); 5650 if (CodePoint < 256) 5651 OS << "\\x" << llvm::format("%02x", CodePoint); 5652 else if (CodePoint <= 0xFFFF) 5653 OS << "\\u" << llvm::format("%04x", CodePoint); 5654 else 5655 OS << "\\U" << llvm::format("%08x", CodePoint); 5656 OS.flush(); 5657 Specifier = CodePointStr; 5658 } 5659 5660 EmitFormatDiagnostic( 5661 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5662 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5663 5664 return keepGoing; 5665 } 5666 5667 void 5668 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5669 const char *startSpec, 5670 unsigned specifierLen) { 5671 EmitFormatDiagnostic( 5672 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5673 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5674 } 5675 5676 bool 5677 CheckFormatHandler::CheckNumArgs( 5678 const analyze_format_string::FormatSpecifier &FS, 5679 const analyze_format_string::ConversionSpecifier &CS, 5680 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5681 5682 if (argIndex >= NumDataArgs) { 5683 PartialDiagnostic PDiag = FS.usesPositionalArg() 5684 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5685 << (argIndex+1) << NumDataArgs) 5686 : S.PDiag(diag::warn_printf_insufficient_data_args); 5687 EmitFormatDiagnostic( 5688 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5689 getSpecifierRange(startSpecifier, specifierLen)); 5690 5691 // Since more arguments than conversion tokens are given, by extension 5692 // all arguments are covered, so mark this as so. 5693 UncoveredArg.setAllCovered(); 5694 return false; 5695 } 5696 return true; 5697 } 5698 5699 template<typename Range> 5700 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5701 SourceLocation Loc, 5702 bool IsStringLocation, 5703 Range StringRange, 5704 ArrayRef<FixItHint> FixIt) { 5705 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5706 Loc, IsStringLocation, StringRange, FixIt); 5707 } 5708 5709 /// \brief If the format string is not within the function call, emit a note 5710 /// so that the function call and string are in diagnostic messages. 5711 /// 5712 /// \param InFunctionCall if true, the format string is within the function 5713 /// call and only one diagnostic message will be produced. Otherwise, an 5714 /// extra note will be emitted pointing to location of the format string. 5715 /// 5716 /// \param ArgumentExpr the expression that is passed as the format string 5717 /// argument in the function call. Used for getting locations when two 5718 /// diagnostics are emitted. 5719 /// 5720 /// \param PDiag the callee should already have provided any strings for the 5721 /// diagnostic message. This function only adds locations and fixits 5722 /// to diagnostics. 5723 /// 5724 /// \param Loc primary location for diagnostic. If two diagnostics are 5725 /// required, one will be at Loc and a new SourceLocation will be created for 5726 /// the other one. 5727 /// 5728 /// \param IsStringLocation if true, Loc points to the format string should be 5729 /// used for the note. Otherwise, Loc points to the argument list and will 5730 /// be used with PDiag. 5731 /// 5732 /// \param StringRange some or all of the string to highlight. This is 5733 /// templated so it can accept either a CharSourceRange or a SourceRange. 5734 /// 5735 /// \param FixIt optional fix it hint for the format string. 5736 template <typename Range> 5737 void CheckFormatHandler::EmitFormatDiagnostic( 5738 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5739 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5740 Range StringRange, ArrayRef<FixItHint> FixIt) { 5741 if (InFunctionCall) { 5742 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5743 D << StringRange; 5744 D << FixIt; 5745 } else { 5746 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5747 << ArgumentExpr->getSourceRange(); 5748 5749 const Sema::SemaDiagnosticBuilder &Note = 5750 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5751 diag::note_format_string_defined); 5752 5753 Note << StringRange; 5754 Note << FixIt; 5755 } 5756 } 5757 5758 //===--- CHECK: Printf format string checking ------------------------------===// 5759 5760 namespace { 5761 5762 class CheckPrintfHandler : public CheckFormatHandler { 5763 public: 5764 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5765 const Expr *origFormatExpr, 5766 const Sema::FormatStringType type, unsigned firstDataArg, 5767 unsigned numDataArgs, bool isObjC, const char *beg, 5768 bool hasVAListArg, ArrayRef<const Expr *> Args, 5769 unsigned formatIdx, bool inFunctionCall, 5770 Sema::VariadicCallType CallType, 5771 llvm::SmallBitVector &CheckedVarArgs, 5772 UncoveredArgHandler &UncoveredArg) 5773 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5774 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5775 inFunctionCall, CallType, CheckedVarArgs, 5776 UncoveredArg) {} 5777 5778 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5779 5780 /// Returns true if '%@' specifiers are allowed in the format string. 5781 bool allowsObjCArg() const { 5782 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5783 FSType == Sema::FST_OSTrace; 5784 } 5785 5786 bool HandleInvalidPrintfConversionSpecifier( 5787 const analyze_printf::PrintfSpecifier &FS, 5788 const char *startSpecifier, 5789 unsigned specifierLen) override; 5790 5791 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5792 const char *startSpecifier, 5793 unsigned specifierLen) override; 5794 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5795 const char *StartSpecifier, 5796 unsigned SpecifierLen, 5797 const Expr *E); 5798 5799 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5800 const char *startSpecifier, unsigned specifierLen); 5801 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5802 const analyze_printf::OptionalAmount &Amt, 5803 unsigned type, 5804 const char *startSpecifier, unsigned specifierLen); 5805 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5806 const analyze_printf::OptionalFlag &flag, 5807 const char *startSpecifier, unsigned specifierLen); 5808 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5809 const analyze_printf::OptionalFlag &ignoredFlag, 5810 const analyze_printf::OptionalFlag &flag, 5811 const char *startSpecifier, unsigned specifierLen); 5812 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5813 const Expr *E); 5814 5815 void HandleEmptyObjCModifierFlag(const char *startFlag, 5816 unsigned flagLen) override; 5817 5818 void HandleInvalidObjCModifierFlag(const char *startFlag, 5819 unsigned flagLen) override; 5820 5821 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5822 const char *flagsEnd, 5823 const char *conversionPosition) 5824 override; 5825 }; 5826 5827 } // namespace 5828 5829 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5830 const analyze_printf::PrintfSpecifier &FS, 5831 const char *startSpecifier, 5832 unsigned specifierLen) { 5833 const analyze_printf::PrintfConversionSpecifier &CS = 5834 FS.getConversionSpecifier(); 5835 5836 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5837 getLocationOfByte(CS.getStart()), 5838 startSpecifier, specifierLen, 5839 CS.getStart(), CS.getLength()); 5840 } 5841 5842 bool CheckPrintfHandler::HandleAmount( 5843 const analyze_format_string::OptionalAmount &Amt, 5844 unsigned k, const char *startSpecifier, 5845 unsigned specifierLen) { 5846 if (Amt.hasDataArgument()) { 5847 if (!HasVAListArg) { 5848 unsigned argIndex = Amt.getArgIndex(); 5849 if (argIndex >= NumDataArgs) { 5850 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5851 << k, 5852 getLocationOfByte(Amt.getStart()), 5853 /*IsStringLocation*/true, 5854 getSpecifierRange(startSpecifier, specifierLen)); 5855 // Don't do any more checking. We will just emit 5856 // spurious errors. 5857 return false; 5858 } 5859 5860 // Type check the data argument. It should be an 'int'. 5861 // Although not in conformance with C99, we also allow the argument to be 5862 // an 'unsigned int' as that is a reasonably safe case. GCC also 5863 // doesn't emit a warning for that case. 5864 CoveredArgs.set(argIndex); 5865 const Expr *Arg = getDataArg(argIndex); 5866 if (!Arg) 5867 return false; 5868 5869 QualType T = Arg->getType(); 5870 5871 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5872 assert(AT.isValid()); 5873 5874 if (!AT.matchesType(S.Context, T)) { 5875 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5876 << k << AT.getRepresentativeTypeName(S.Context) 5877 << T << Arg->getSourceRange(), 5878 getLocationOfByte(Amt.getStart()), 5879 /*IsStringLocation*/true, 5880 getSpecifierRange(startSpecifier, specifierLen)); 5881 // Don't do any more checking. We will just emit 5882 // spurious errors. 5883 return false; 5884 } 5885 } 5886 } 5887 return true; 5888 } 5889 5890 void CheckPrintfHandler::HandleInvalidAmount( 5891 const analyze_printf::PrintfSpecifier &FS, 5892 const analyze_printf::OptionalAmount &Amt, 5893 unsigned type, 5894 const char *startSpecifier, 5895 unsigned specifierLen) { 5896 const analyze_printf::PrintfConversionSpecifier &CS = 5897 FS.getConversionSpecifier(); 5898 5899 FixItHint fixit = 5900 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5901 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5902 Amt.getConstantLength())) 5903 : FixItHint(); 5904 5905 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5906 << type << CS.toString(), 5907 getLocationOfByte(Amt.getStart()), 5908 /*IsStringLocation*/true, 5909 getSpecifierRange(startSpecifier, specifierLen), 5910 fixit); 5911 } 5912 5913 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5914 const analyze_printf::OptionalFlag &flag, 5915 const char *startSpecifier, 5916 unsigned specifierLen) { 5917 // Warn about pointless flag with a fixit removal. 5918 const analyze_printf::PrintfConversionSpecifier &CS = 5919 FS.getConversionSpecifier(); 5920 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5921 << flag.toString() << CS.toString(), 5922 getLocationOfByte(flag.getPosition()), 5923 /*IsStringLocation*/true, 5924 getSpecifierRange(startSpecifier, specifierLen), 5925 FixItHint::CreateRemoval( 5926 getSpecifierRange(flag.getPosition(), 1))); 5927 } 5928 5929 void CheckPrintfHandler::HandleIgnoredFlag( 5930 const analyze_printf::PrintfSpecifier &FS, 5931 const analyze_printf::OptionalFlag &ignoredFlag, 5932 const analyze_printf::OptionalFlag &flag, 5933 const char *startSpecifier, 5934 unsigned specifierLen) { 5935 // Warn about ignored flag with a fixit removal. 5936 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5937 << ignoredFlag.toString() << flag.toString(), 5938 getLocationOfByte(ignoredFlag.getPosition()), 5939 /*IsStringLocation*/true, 5940 getSpecifierRange(startSpecifier, specifierLen), 5941 FixItHint::CreateRemoval( 5942 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5943 } 5944 5945 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5946 unsigned flagLen) { 5947 // Warn about an empty flag. 5948 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5949 getLocationOfByte(startFlag), 5950 /*IsStringLocation*/true, 5951 getSpecifierRange(startFlag, flagLen)); 5952 } 5953 5954 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5955 unsigned flagLen) { 5956 // Warn about an invalid flag. 5957 auto Range = getSpecifierRange(startFlag, flagLen); 5958 StringRef flag(startFlag, flagLen); 5959 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5960 getLocationOfByte(startFlag), 5961 /*IsStringLocation*/true, 5962 Range, FixItHint::CreateRemoval(Range)); 5963 } 5964 5965 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5966 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5967 // Warn about using '[...]' without a '@' conversion. 5968 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5969 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5970 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5971 getLocationOfByte(conversionPosition), 5972 /*IsStringLocation*/true, 5973 Range, FixItHint::CreateRemoval(Range)); 5974 } 5975 5976 // Determines if the specified is a C++ class or struct containing 5977 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5978 // "c_str()"). 5979 template<typename MemberKind> 5980 static llvm::SmallPtrSet<MemberKind*, 1> 5981 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5982 const RecordType *RT = Ty->getAs<RecordType>(); 5983 llvm::SmallPtrSet<MemberKind*, 1> Results; 5984 5985 if (!RT) 5986 return Results; 5987 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5988 if (!RD || !RD->getDefinition()) 5989 return Results; 5990 5991 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5992 Sema::LookupMemberName); 5993 R.suppressDiagnostics(); 5994 5995 // We just need to include all members of the right kind turned up by the 5996 // filter, at this point. 5997 if (S.LookupQualifiedName(R, RT->getDecl())) 5998 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5999 NamedDecl *decl = (*I)->getUnderlyingDecl(); 6000 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 6001 Results.insert(FK); 6002 } 6003 return Results; 6004 } 6005 6006 /// Check if we could call '.c_str()' on an object. 6007 /// 6008 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 6009 /// allow the call, or if it would be ambiguous). 6010 bool Sema::hasCStrMethod(const Expr *E) { 6011 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 6012 6013 MethodSet Results = 6014 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 6015 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 6016 MI != ME; ++MI) 6017 if ((*MI)->getMinRequiredArguments() == 0) 6018 return true; 6019 return false; 6020 } 6021 6022 // Check if a (w)string was passed when a (w)char* was needed, and offer a 6023 // better diagnostic if so. AT is assumed to be valid. 6024 // Returns true when a c_str() conversion method is found. 6025 bool CheckPrintfHandler::checkForCStrMembers( 6026 const analyze_printf::ArgType &AT, const Expr *E) { 6027 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 6028 6029 MethodSet Results = 6030 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 6031 6032 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 6033 MI != ME; ++MI) { 6034 const CXXMethodDecl *Method = *MI; 6035 if (Method->getMinRequiredArguments() == 0 && 6036 AT.matchesType(S.Context, Method->getReturnType())) { 6037 // FIXME: Suggest parens if the expression needs them. 6038 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 6039 S.Diag(E->getLocStart(), diag::note_printf_c_str) 6040 << "c_str()" 6041 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 6042 return true; 6043 } 6044 } 6045 6046 return false; 6047 } 6048 6049 bool 6050 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 6051 &FS, 6052 const char *startSpecifier, 6053 unsigned specifierLen) { 6054 using namespace analyze_format_string; 6055 using namespace analyze_printf; 6056 6057 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 6058 6059 if (FS.consumesDataArgument()) { 6060 if (atFirstArg) { 6061 atFirstArg = false; 6062 usesPositionalArgs = FS.usesPositionalArg(); 6063 } 6064 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6065 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6066 startSpecifier, specifierLen); 6067 return false; 6068 } 6069 } 6070 6071 // First check if the field width, precision, and conversion specifier 6072 // have matching data arguments. 6073 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 6074 startSpecifier, specifierLen)) { 6075 return false; 6076 } 6077 6078 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 6079 startSpecifier, specifierLen)) { 6080 return false; 6081 } 6082 6083 if (!CS.consumesDataArgument()) { 6084 // FIXME: Technically specifying a precision or field width here 6085 // makes no sense. Worth issuing a warning at some point. 6086 return true; 6087 } 6088 6089 // Consume the argument. 6090 unsigned argIndex = FS.getArgIndex(); 6091 if (argIndex < NumDataArgs) { 6092 // The check to see if the argIndex is valid will come later. 6093 // We set the bit here because we may exit early from this 6094 // function if we encounter some other error. 6095 CoveredArgs.set(argIndex); 6096 } 6097 6098 // FreeBSD kernel extensions. 6099 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 6100 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 6101 // We need at least two arguments. 6102 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 6103 return false; 6104 6105 // Claim the second argument. 6106 CoveredArgs.set(argIndex + 1); 6107 6108 // Type check the first argument (int for %b, pointer for %D) 6109 const Expr *Ex = getDataArg(argIndex); 6110 const analyze_printf::ArgType &AT = 6111 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 6112 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 6113 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 6114 EmitFormatDiagnostic( 6115 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6116 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 6117 << false << Ex->getSourceRange(), 6118 Ex->getLocStart(), /*IsStringLocation*/false, 6119 getSpecifierRange(startSpecifier, specifierLen)); 6120 6121 // Type check the second argument (char * for both %b and %D) 6122 Ex = getDataArg(argIndex + 1); 6123 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 6124 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 6125 EmitFormatDiagnostic( 6126 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6127 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 6128 << false << Ex->getSourceRange(), 6129 Ex->getLocStart(), /*IsStringLocation*/false, 6130 getSpecifierRange(startSpecifier, specifierLen)); 6131 6132 return true; 6133 } 6134 6135 // Check for using an Objective-C specific conversion specifier 6136 // in a non-ObjC literal. 6137 if (!allowsObjCArg() && CS.isObjCArg()) { 6138 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6139 specifierLen); 6140 } 6141 6142 // %P can only be used with os_log. 6143 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 6144 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6145 specifierLen); 6146 } 6147 6148 // %n is not allowed with os_log. 6149 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 6150 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 6151 getLocationOfByte(CS.getStart()), 6152 /*IsStringLocation*/ false, 6153 getSpecifierRange(startSpecifier, specifierLen)); 6154 6155 return true; 6156 } 6157 6158 // Only scalars are allowed for os_trace. 6159 if (FSType == Sema::FST_OSTrace && 6160 (CS.getKind() == ConversionSpecifier::PArg || 6161 CS.getKind() == ConversionSpecifier::sArg || 6162 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 6163 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6164 specifierLen); 6165 } 6166 6167 // Check for use of public/private annotation outside of os_log(). 6168 if (FSType != Sema::FST_OSLog) { 6169 if (FS.isPublic().isSet()) { 6170 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6171 << "public", 6172 getLocationOfByte(FS.isPublic().getPosition()), 6173 /*IsStringLocation*/ false, 6174 getSpecifierRange(startSpecifier, specifierLen)); 6175 } 6176 if (FS.isPrivate().isSet()) { 6177 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6178 << "private", 6179 getLocationOfByte(FS.isPrivate().getPosition()), 6180 /*IsStringLocation*/ false, 6181 getSpecifierRange(startSpecifier, specifierLen)); 6182 } 6183 } 6184 6185 // Check for invalid use of field width 6186 if (!FS.hasValidFieldWidth()) { 6187 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6188 startSpecifier, specifierLen); 6189 } 6190 6191 // Check for invalid use of precision 6192 if (!FS.hasValidPrecision()) { 6193 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6194 startSpecifier, specifierLen); 6195 } 6196 6197 // Precision is mandatory for %P specifier. 6198 if (CS.getKind() == ConversionSpecifier::PArg && 6199 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6200 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6201 getLocationOfByte(startSpecifier), 6202 /*IsStringLocation*/ false, 6203 getSpecifierRange(startSpecifier, specifierLen)); 6204 } 6205 6206 // Check each flag does not conflict with any other component. 6207 if (!FS.hasValidThousandsGroupingPrefix()) 6208 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6209 if (!FS.hasValidLeadingZeros()) 6210 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6211 if (!FS.hasValidPlusPrefix()) 6212 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6213 if (!FS.hasValidSpacePrefix()) 6214 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6215 if (!FS.hasValidAlternativeForm()) 6216 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6217 if (!FS.hasValidLeftJustified()) 6218 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6219 6220 // Check that flags are not ignored by another flag 6221 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6222 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6223 startSpecifier, specifierLen); 6224 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6225 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6226 startSpecifier, specifierLen); 6227 6228 // Check the length modifier is valid with the given conversion specifier. 6229 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6230 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6231 diag::warn_format_nonsensical_length); 6232 else if (!FS.hasStandardLengthModifier()) 6233 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6234 else if (!FS.hasStandardLengthConversionCombination()) 6235 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6236 diag::warn_format_non_standard_conversion_spec); 6237 6238 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6239 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6240 6241 // The remaining checks depend on the data arguments. 6242 if (HasVAListArg) 6243 return true; 6244 6245 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6246 return false; 6247 6248 const Expr *Arg = getDataArg(argIndex); 6249 if (!Arg) 6250 return true; 6251 6252 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6253 } 6254 6255 static bool requiresParensToAddCast(const Expr *E) { 6256 // FIXME: We should have a general way to reason about operator 6257 // precedence and whether parens are actually needed here. 6258 // Take care of a few common cases where they aren't. 6259 const Expr *Inside = E->IgnoreImpCasts(); 6260 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6261 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6262 6263 switch (Inside->getStmtClass()) { 6264 case Stmt::ArraySubscriptExprClass: 6265 case Stmt::CallExprClass: 6266 case Stmt::CharacterLiteralClass: 6267 case Stmt::CXXBoolLiteralExprClass: 6268 case Stmt::DeclRefExprClass: 6269 case Stmt::FloatingLiteralClass: 6270 case Stmt::IntegerLiteralClass: 6271 case Stmt::MemberExprClass: 6272 case Stmt::ObjCArrayLiteralClass: 6273 case Stmt::ObjCBoolLiteralExprClass: 6274 case Stmt::ObjCBoxedExprClass: 6275 case Stmt::ObjCDictionaryLiteralClass: 6276 case Stmt::ObjCEncodeExprClass: 6277 case Stmt::ObjCIvarRefExprClass: 6278 case Stmt::ObjCMessageExprClass: 6279 case Stmt::ObjCPropertyRefExprClass: 6280 case Stmt::ObjCStringLiteralClass: 6281 case Stmt::ObjCSubscriptRefExprClass: 6282 case Stmt::ParenExprClass: 6283 case Stmt::StringLiteralClass: 6284 case Stmt::UnaryOperatorClass: 6285 return false; 6286 default: 6287 return true; 6288 } 6289 } 6290 6291 static std::pair<QualType, StringRef> 6292 shouldNotPrintDirectly(const ASTContext &Context, 6293 QualType IntendedTy, 6294 const Expr *E) { 6295 // Use a 'while' to peel off layers of typedefs. 6296 QualType TyTy = IntendedTy; 6297 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6298 StringRef Name = UserTy->getDecl()->getName(); 6299 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6300 .Case("CFIndex", Context.getNSIntegerType()) 6301 .Case("NSInteger", Context.getNSIntegerType()) 6302 .Case("NSUInteger", Context.getNSUIntegerType()) 6303 .Case("SInt32", Context.IntTy) 6304 .Case("UInt32", Context.UnsignedIntTy) 6305 .Default(QualType()); 6306 6307 if (!CastTy.isNull()) 6308 return std::make_pair(CastTy, Name); 6309 6310 TyTy = UserTy->desugar(); 6311 } 6312 6313 // Strip parens if necessary. 6314 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6315 return shouldNotPrintDirectly(Context, 6316 PE->getSubExpr()->getType(), 6317 PE->getSubExpr()); 6318 6319 // If this is a conditional expression, then its result type is constructed 6320 // via usual arithmetic conversions and thus there might be no necessary 6321 // typedef sugar there. Recurse to operands to check for NSInteger & 6322 // Co. usage condition. 6323 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6324 QualType TrueTy, FalseTy; 6325 StringRef TrueName, FalseName; 6326 6327 std::tie(TrueTy, TrueName) = 6328 shouldNotPrintDirectly(Context, 6329 CO->getTrueExpr()->getType(), 6330 CO->getTrueExpr()); 6331 std::tie(FalseTy, FalseName) = 6332 shouldNotPrintDirectly(Context, 6333 CO->getFalseExpr()->getType(), 6334 CO->getFalseExpr()); 6335 6336 if (TrueTy == FalseTy) 6337 return std::make_pair(TrueTy, TrueName); 6338 else if (TrueTy.isNull()) 6339 return std::make_pair(FalseTy, FalseName); 6340 else if (FalseTy.isNull()) 6341 return std::make_pair(TrueTy, TrueName); 6342 } 6343 6344 return std::make_pair(QualType(), StringRef()); 6345 } 6346 6347 bool 6348 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6349 const char *StartSpecifier, 6350 unsigned SpecifierLen, 6351 const Expr *E) { 6352 using namespace analyze_format_string; 6353 using namespace analyze_printf; 6354 6355 // Now type check the data expression that matches the 6356 // format specifier. 6357 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6358 if (!AT.isValid()) 6359 return true; 6360 6361 QualType ExprTy = E->getType(); 6362 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6363 ExprTy = TET->getUnderlyingExpr()->getType(); 6364 } 6365 6366 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6367 6368 if (match == analyze_printf::ArgType::Match) { 6369 return true; 6370 } 6371 6372 // Look through argument promotions for our error message's reported type. 6373 // This includes the integral and floating promotions, but excludes array 6374 // and function pointer decay; seeing that an argument intended to be a 6375 // string has type 'char [6]' is probably more confusing than 'char *'. 6376 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6377 if (ICE->getCastKind() == CK_IntegralCast || 6378 ICE->getCastKind() == CK_FloatingCast) { 6379 E = ICE->getSubExpr(); 6380 ExprTy = E->getType(); 6381 6382 // Check if we didn't match because of an implicit cast from a 'char' 6383 // or 'short' to an 'int'. This is done because printf is a varargs 6384 // function. 6385 if (ICE->getType() == S.Context.IntTy || 6386 ICE->getType() == S.Context.UnsignedIntTy) { 6387 // All further checking is done on the subexpression. 6388 if (AT.matchesType(S.Context, ExprTy)) 6389 return true; 6390 } 6391 } 6392 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6393 // Special case for 'a', which has type 'int' in C. 6394 // Note, however, that we do /not/ want to treat multibyte constants like 6395 // 'MooV' as characters! This form is deprecated but still exists. 6396 if (ExprTy == S.Context.IntTy) 6397 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6398 ExprTy = S.Context.CharTy; 6399 } 6400 6401 // Look through enums to their underlying type. 6402 bool IsEnum = false; 6403 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6404 ExprTy = EnumTy->getDecl()->getIntegerType(); 6405 IsEnum = true; 6406 } 6407 6408 // %C in an Objective-C context prints a unichar, not a wchar_t. 6409 // If the argument is an integer of some kind, believe the %C and suggest 6410 // a cast instead of changing the conversion specifier. 6411 QualType IntendedTy = ExprTy; 6412 if (isObjCContext() && 6413 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6414 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6415 !ExprTy->isCharType()) { 6416 // 'unichar' is defined as a typedef of unsigned short, but we should 6417 // prefer using the typedef if it is visible. 6418 IntendedTy = S.Context.UnsignedShortTy; 6419 6420 // While we are here, check if the value is an IntegerLiteral that happens 6421 // to be within the valid range. 6422 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6423 const llvm::APInt &V = IL->getValue(); 6424 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6425 return true; 6426 } 6427 6428 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6429 Sema::LookupOrdinaryName); 6430 if (S.LookupName(Result, S.getCurScope())) { 6431 NamedDecl *ND = Result.getFoundDecl(); 6432 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6433 if (TD->getUnderlyingType() == IntendedTy) 6434 IntendedTy = S.Context.getTypedefType(TD); 6435 } 6436 } 6437 } 6438 6439 // Special-case some of Darwin's platform-independence types by suggesting 6440 // casts to primitive types that are known to be large enough. 6441 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6442 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6443 QualType CastTy; 6444 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6445 if (!CastTy.isNull()) { 6446 IntendedTy = CastTy; 6447 ShouldNotPrintDirectly = true; 6448 } 6449 } 6450 6451 // We may be able to offer a FixItHint if it is a supported type. 6452 PrintfSpecifier fixedFS = FS; 6453 bool success = 6454 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6455 6456 if (success) { 6457 // Get the fix string from the fixed format specifier 6458 SmallString<16> buf; 6459 llvm::raw_svector_ostream os(buf); 6460 fixedFS.toString(os); 6461 6462 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6463 6464 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6465 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6466 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6467 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6468 } 6469 // In this case, the specifier is wrong and should be changed to match 6470 // the argument. 6471 EmitFormatDiagnostic(S.PDiag(diag) 6472 << AT.getRepresentativeTypeName(S.Context) 6473 << IntendedTy << IsEnum << E->getSourceRange(), 6474 E->getLocStart(), 6475 /*IsStringLocation*/ false, SpecRange, 6476 FixItHint::CreateReplacement(SpecRange, os.str())); 6477 } else { 6478 // The canonical type for formatting this value is different from the 6479 // actual type of the expression. (This occurs, for example, with Darwin's 6480 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6481 // should be printed as 'long' for 64-bit compatibility.) 6482 // Rather than emitting a normal format/argument mismatch, we want to 6483 // add a cast to the recommended type (and correct the format string 6484 // if necessary). 6485 SmallString<16> CastBuf; 6486 llvm::raw_svector_ostream CastFix(CastBuf); 6487 CastFix << "("; 6488 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6489 CastFix << ")"; 6490 6491 SmallVector<FixItHint,4> Hints; 6492 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 6493 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6494 6495 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6496 // If there's already a cast present, just replace it. 6497 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6498 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6499 6500 } else if (!requiresParensToAddCast(E)) { 6501 // If the expression has high enough precedence, 6502 // just write the C-style cast. 6503 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6504 CastFix.str())); 6505 } else { 6506 // Otherwise, add parens around the expression as well as the cast. 6507 CastFix << "("; 6508 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6509 CastFix.str())); 6510 6511 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6512 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6513 } 6514 6515 if (ShouldNotPrintDirectly) { 6516 // The expression has a type that should not be printed directly. 6517 // We extract the name from the typedef because we don't want to show 6518 // the underlying type in the diagnostic. 6519 StringRef Name; 6520 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6521 Name = TypedefTy->getDecl()->getName(); 6522 else 6523 Name = CastTyName; 6524 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6525 << Name << IntendedTy << IsEnum 6526 << E->getSourceRange(), 6527 E->getLocStart(), /*IsStringLocation=*/false, 6528 SpecRange, Hints); 6529 } else { 6530 // In this case, the expression could be printed using a different 6531 // specifier, but we've decided that the specifier is probably correct 6532 // and we should cast instead. Just use the normal warning message. 6533 EmitFormatDiagnostic( 6534 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6535 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6536 << E->getSourceRange(), 6537 E->getLocStart(), /*IsStringLocation*/false, 6538 SpecRange, Hints); 6539 } 6540 } 6541 } else { 6542 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6543 SpecifierLen); 6544 // Since the warning for passing non-POD types to variadic functions 6545 // was deferred until now, we emit a warning for non-POD 6546 // arguments here. 6547 switch (S.isValidVarArgType(ExprTy)) { 6548 case Sema::VAK_Valid: 6549 case Sema::VAK_ValidInCXX11: { 6550 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6551 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6552 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6553 } 6554 6555 EmitFormatDiagnostic( 6556 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6557 << IsEnum << CSR << E->getSourceRange(), 6558 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6559 break; 6560 } 6561 case Sema::VAK_Undefined: 6562 case Sema::VAK_MSVCUndefined: 6563 EmitFormatDiagnostic( 6564 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6565 << S.getLangOpts().CPlusPlus11 6566 << ExprTy 6567 << CallType 6568 << AT.getRepresentativeTypeName(S.Context) 6569 << CSR 6570 << E->getSourceRange(), 6571 E->getLocStart(), /*IsStringLocation*/false, CSR); 6572 checkForCStrMembers(AT, E); 6573 break; 6574 6575 case Sema::VAK_Invalid: 6576 if (ExprTy->isObjCObjectType()) 6577 EmitFormatDiagnostic( 6578 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6579 << S.getLangOpts().CPlusPlus11 6580 << ExprTy 6581 << CallType 6582 << AT.getRepresentativeTypeName(S.Context) 6583 << CSR 6584 << E->getSourceRange(), 6585 E->getLocStart(), /*IsStringLocation*/false, CSR); 6586 else 6587 // FIXME: If this is an initializer list, suggest removing the braces 6588 // or inserting a cast to the target type. 6589 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6590 << isa<InitListExpr>(E) << ExprTy << CallType 6591 << AT.getRepresentativeTypeName(S.Context) 6592 << E->getSourceRange(); 6593 break; 6594 } 6595 6596 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6597 "format string specifier index out of range"); 6598 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6599 } 6600 6601 return true; 6602 } 6603 6604 //===--- CHECK: Scanf format string checking ------------------------------===// 6605 6606 namespace { 6607 6608 class CheckScanfHandler : public CheckFormatHandler { 6609 public: 6610 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6611 const Expr *origFormatExpr, Sema::FormatStringType type, 6612 unsigned firstDataArg, unsigned numDataArgs, 6613 const char *beg, bool hasVAListArg, 6614 ArrayRef<const Expr *> Args, unsigned formatIdx, 6615 bool inFunctionCall, Sema::VariadicCallType CallType, 6616 llvm::SmallBitVector &CheckedVarArgs, 6617 UncoveredArgHandler &UncoveredArg) 6618 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6619 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6620 inFunctionCall, CallType, CheckedVarArgs, 6621 UncoveredArg) {} 6622 6623 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6624 const char *startSpecifier, 6625 unsigned specifierLen) override; 6626 6627 bool HandleInvalidScanfConversionSpecifier( 6628 const analyze_scanf::ScanfSpecifier &FS, 6629 const char *startSpecifier, 6630 unsigned specifierLen) override; 6631 6632 void HandleIncompleteScanList(const char *start, const char *end) override; 6633 }; 6634 6635 } // namespace 6636 6637 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6638 const char *end) { 6639 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6640 getLocationOfByte(end), /*IsStringLocation*/true, 6641 getSpecifierRange(start, end - start)); 6642 } 6643 6644 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6645 const analyze_scanf::ScanfSpecifier &FS, 6646 const char *startSpecifier, 6647 unsigned specifierLen) { 6648 const analyze_scanf::ScanfConversionSpecifier &CS = 6649 FS.getConversionSpecifier(); 6650 6651 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6652 getLocationOfByte(CS.getStart()), 6653 startSpecifier, specifierLen, 6654 CS.getStart(), CS.getLength()); 6655 } 6656 6657 bool CheckScanfHandler::HandleScanfSpecifier( 6658 const analyze_scanf::ScanfSpecifier &FS, 6659 const char *startSpecifier, 6660 unsigned specifierLen) { 6661 using namespace analyze_scanf; 6662 using namespace analyze_format_string; 6663 6664 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6665 6666 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6667 // be used to decide if we are using positional arguments consistently. 6668 if (FS.consumesDataArgument()) { 6669 if (atFirstArg) { 6670 atFirstArg = false; 6671 usesPositionalArgs = FS.usesPositionalArg(); 6672 } 6673 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6674 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6675 startSpecifier, specifierLen); 6676 return false; 6677 } 6678 } 6679 6680 // Check if the field with is non-zero. 6681 const OptionalAmount &Amt = FS.getFieldWidth(); 6682 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6683 if (Amt.getConstantAmount() == 0) { 6684 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6685 Amt.getConstantLength()); 6686 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6687 getLocationOfByte(Amt.getStart()), 6688 /*IsStringLocation*/true, R, 6689 FixItHint::CreateRemoval(R)); 6690 } 6691 } 6692 6693 if (!FS.consumesDataArgument()) { 6694 // FIXME: Technically specifying a precision or field width here 6695 // makes no sense. Worth issuing a warning at some point. 6696 return true; 6697 } 6698 6699 // Consume the argument. 6700 unsigned argIndex = FS.getArgIndex(); 6701 if (argIndex < NumDataArgs) { 6702 // The check to see if the argIndex is valid will come later. 6703 // We set the bit here because we may exit early from this 6704 // function if we encounter some other error. 6705 CoveredArgs.set(argIndex); 6706 } 6707 6708 // Check the length modifier is valid with the given conversion specifier. 6709 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6710 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6711 diag::warn_format_nonsensical_length); 6712 else if (!FS.hasStandardLengthModifier()) 6713 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6714 else if (!FS.hasStandardLengthConversionCombination()) 6715 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6716 diag::warn_format_non_standard_conversion_spec); 6717 6718 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6719 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6720 6721 // The remaining checks depend on the data arguments. 6722 if (HasVAListArg) 6723 return true; 6724 6725 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6726 return false; 6727 6728 // Check that the argument type matches the format specifier. 6729 const Expr *Ex = getDataArg(argIndex); 6730 if (!Ex) 6731 return true; 6732 6733 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6734 6735 if (!AT.isValid()) { 6736 return true; 6737 } 6738 6739 analyze_format_string::ArgType::MatchKind match = 6740 AT.matchesType(S.Context, Ex->getType()); 6741 if (match == analyze_format_string::ArgType::Match) { 6742 return true; 6743 } 6744 6745 ScanfSpecifier fixedFS = FS; 6746 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6747 S.getLangOpts(), S.Context); 6748 6749 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6750 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6751 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6752 } 6753 6754 if (success) { 6755 // Get the fix string from the fixed format specifier. 6756 SmallString<128> buf; 6757 llvm::raw_svector_ostream os(buf); 6758 fixedFS.toString(os); 6759 6760 EmitFormatDiagnostic( 6761 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6762 << Ex->getType() << false << Ex->getSourceRange(), 6763 Ex->getLocStart(), 6764 /*IsStringLocation*/ false, 6765 getSpecifierRange(startSpecifier, specifierLen), 6766 FixItHint::CreateReplacement( 6767 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6768 } else { 6769 EmitFormatDiagnostic(S.PDiag(diag) 6770 << AT.getRepresentativeTypeName(S.Context) 6771 << Ex->getType() << false << Ex->getSourceRange(), 6772 Ex->getLocStart(), 6773 /*IsStringLocation*/ false, 6774 getSpecifierRange(startSpecifier, specifierLen)); 6775 } 6776 6777 return true; 6778 } 6779 6780 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6781 const Expr *OrigFormatExpr, 6782 ArrayRef<const Expr *> Args, 6783 bool HasVAListArg, unsigned format_idx, 6784 unsigned firstDataArg, 6785 Sema::FormatStringType Type, 6786 bool inFunctionCall, 6787 Sema::VariadicCallType CallType, 6788 llvm::SmallBitVector &CheckedVarArgs, 6789 UncoveredArgHandler &UncoveredArg) { 6790 // CHECK: is the format string a wide literal? 6791 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6792 CheckFormatHandler::EmitFormatDiagnostic( 6793 S, inFunctionCall, Args[format_idx], 6794 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6795 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6796 return; 6797 } 6798 6799 // Str - The format string. NOTE: this is NOT null-terminated! 6800 StringRef StrRef = FExpr->getString(); 6801 const char *Str = StrRef.data(); 6802 // Account for cases where the string literal is truncated in a declaration. 6803 const ConstantArrayType *T = 6804 S.Context.getAsConstantArrayType(FExpr->getType()); 6805 assert(T && "String literal not of constant array type!"); 6806 size_t TypeSize = T->getSize().getZExtValue(); 6807 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6808 const unsigned numDataArgs = Args.size() - firstDataArg; 6809 6810 // Emit a warning if the string literal is truncated and does not contain an 6811 // embedded null character. 6812 if (TypeSize <= StrRef.size() && 6813 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6814 CheckFormatHandler::EmitFormatDiagnostic( 6815 S, inFunctionCall, Args[format_idx], 6816 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6817 FExpr->getLocStart(), 6818 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6819 return; 6820 } 6821 6822 // CHECK: empty format string? 6823 if (StrLen == 0 && numDataArgs > 0) { 6824 CheckFormatHandler::EmitFormatDiagnostic( 6825 S, inFunctionCall, Args[format_idx], 6826 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6827 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6828 return; 6829 } 6830 6831 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6832 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6833 Type == Sema::FST_OSTrace) { 6834 CheckPrintfHandler H( 6835 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6836 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6837 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6838 CheckedVarArgs, UncoveredArg); 6839 6840 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6841 S.getLangOpts(), 6842 S.Context.getTargetInfo(), 6843 Type == Sema::FST_FreeBSDKPrintf)) 6844 H.DoneProcessing(); 6845 } else if (Type == Sema::FST_Scanf) { 6846 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6847 numDataArgs, Str, HasVAListArg, Args, format_idx, 6848 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6849 6850 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6851 S.getLangOpts(), 6852 S.Context.getTargetInfo())) 6853 H.DoneProcessing(); 6854 } // TODO: handle other formats 6855 } 6856 6857 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6858 // Str - The format string. NOTE: this is NOT null-terminated! 6859 StringRef StrRef = FExpr->getString(); 6860 const char *Str = StrRef.data(); 6861 // Account for cases where the string literal is truncated in a declaration. 6862 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6863 assert(T && "String literal not of constant array type!"); 6864 size_t TypeSize = T->getSize().getZExtValue(); 6865 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6866 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6867 getLangOpts(), 6868 Context.getTargetInfo()); 6869 } 6870 6871 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6872 6873 // Returns the related absolute value function that is larger, of 0 if one 6874 // does not exist. 6875 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6876 switch (AbsFunction) { 6877 default: 6878 return 0; 6879 6880 case Builtin::BI__builtin_abs: 6881 return Builtin::BI__builtin_labs; 6882 case Builtin::BI__builtin_labs: 6883 return Builtin::BI__builtin_llabs; 6884 case Builtin::BI__builtin_llabs: 6885 return 0; 6886 6887 case Builtin::BI__builtin_fabsf: 6888 return Builtin::BI__builtin_fabs; 6889 case Builtin::BI__builtin_fabs: 6890 return Builtin::BI__builtin_fabsl; 6891 case Builtin::BI__builtin_fabsl: 6892 return 0; 6893 6894 case Builtin::BI__builtin_cabsf: 6895 return Builtin::BI__builtin_cabs; 6896 case Builtin::BI__builtin_cabs: 6897 return Builtin::BI__builtin_cabsl; 6898 case Builtin::BI__builtin_cabsl: 6899 return 0; 6900 6901 case Builtin::BIabs: 6902 return Builtin::BIlabs; 6903 case Builtin::BIlabs: 6904 return Builtin::BIllabs; 6905 case Builtin::BIllabs: 6906 return 0; 6907 6908 case Builtin::BIfabsf: 6909 return Builtin::BIfabs; 6910 case Builtin::BIfabs: 6911 return Builtin::BIfabsl; 6912 case Builtin::BIfabsl: 6913 return 0; 6914 6915 case Builtin::BIcabsf: 6916 return Builtin::BIcabs; 6917 case Builtin::BIcabs: 6918 return Builtin::BIcabsl; 6919 case Builtin::BIcabsl: 6920 return 0; 6921 } 6922 } 6923 6924 // Returns the argument type of the absolute value function. 6925 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6926 unsigned AbsType) { 6927 if (AbsType == 0) 6928 return QualType(); 6929 6930 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6931 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6932 if (Error != ASTContext::GE_None) 6933 return QualType(); 6934 6935 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6936 if (!FT) 6937 return QualType(); 6938 6939 if (FT->getNumParams() != 1) 6940 return QualType(); 6941 6942 return FT->getParamType(0); 6943 } 6944 6945 // Returns the best absolute value function, or zero, based on type and 6946 // current absolute value function. 6947 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6948 unsigned AbsFunctionKind) { 6949 unsigned BestKind = 0; 6950 uint64_t ArgSize = Context.getTypeSize(ArgType); 6951 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6952 Kind = getLargerAbsoluteValueFunction(Kind)) { 6953 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6954 if (Context.getTypeSize(ParamType) >= ArgSize) { 6955 if (BestKind == 0) 6956 BestKind = Kind; 6957 else if (Context.hasSameType(ParamType, ArgType)) { 6958 BestKind = Kind; 6959 break; 6960 } 6961 } 6962 } 6963 return BestKind; 6964 } 6965 6966 enum AbsoluteValueKind { 6967 AVK_Integer, 6968 AVK_Floating, 6969 AVK_Complex 6970 }; 6971 6972 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6973 if (T->isIntegralOrEnumerationType()) 6974 return AVK_Integer; 6975 if (T->isRealFloatingType()) 6976 return AVK_Floating; 6977 if (T->isAnyComplexType()) 6978 return AVK_Complex; 6979 6980 llvm_unreachable("Type not integer, floating, or complex"); 6981 } 6982 6983 // Changes the absolute value function to a different type. Preserves whether 6984 // the function is a builtin. 6985 static unsigned changeAbsFunction(unsigned AbsKind, 6986 AbsoluteValueKind ValueKind) { 6987 switch (ValueKind) { 6988 case AVK_Integer: 6989 switch (AbsKind) { 6990 default: 6991 return 0; 6992 case Builtin::BI__builtin_fabsf: 6993 case Builtin::BI__builtin_fabs: 6994 case Builtin::BI__builtin_fabsl: 6995 case Builtin::BI__builtin_cabsf: 6996 case Builtin::BI__builtin_cabs: 6997 case Builtin::BI__builtin_cabsl: 6998 return Builtin::BI__builtin_abs; 6999 case Builtin::BIfabsf: 7000 case Builtin::BIfabs: 7001 case Builtin::BIfabsl: 7002 case Builtin::BIcabsf: 7003 case Builtin::BIcabs: 7004 case Builtin::BIcabsl: 7005 return Builtin::BIabs; 7006 } 7007 case AVK_Floating: 7008 switch (AbsKind) { 7009 default: 7010 return 0; 7011 case Builtin::BI__builtin_abs: 7012 case Builtin::BI__builtin_labs: 7013 case Builtin::BI__builtin_llabs: 7014 case Builtin::BI__builtin_cabsf: 7015 case Builtin::BI__builtin_cabs: 7016 case Builtin::BI__builtin_cabsl: 7017 return Builtin::BI__builtin_fabsf; 7018 case Builtin::BIabs: 7019 case Builtin::BIlabs: 7020 case Builtin::BIllabs: 7021 case Builtin::BIcabsf: 7022 case Builtin::BIcabs: 7023 case Builtin::BIcabsl: 7024 return Builtin::BIfabsf; 7025 } 7026 case AVK_Complex: 7027 switch (AbsKind) { 7028 default: 7029 return 0; 7030 case Builtin::BI__builtin_abs: 7031 case Builtin::BI__builtin_labs: 7032 case Builtin::BI__builtin_llabs: 7033 case Builtin::BI__builtin_fabsf: 7034 case Builtin::BI__builtin_fabs: 7035 case Builtin::BI__builtin_fabsl: 7036 return Builtin::BI__builtin_cabsf; 7037 case Builtin::BIabs: 7038 case Builtin::BIlabs: 7039 case Builtin::BIllabs: 7040 case Builtin::BIfabsf: 7041 case Builtin::BIfabs: 7042 case Builtin::BIfabsl: 7043 return Builtin::BIcabsf; 7044 } 7045 } 7046 llvm_unreachable("Unable to convert function"); 7047 } 7048 7049 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 7050 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 7051 if (!FnInfo) 7052 return 0; 7053 7054 switch (FDecl->getBuiltinID()) { 7055 default: 7056 return 0; 7057 case Builtin::BI__builtin_abs: 7058 case Builtin::BI__builtin_fabs: 7059 case Builtin::BI__builtin_fabsf: 7060 case Builtin::BI__builtin_fabsl: 7061 case Builtin::BI__builtin_labs: 7062 case Builtin::BI__builtin_llabs: 7063 case Builtin::BI__builtin_cabs: 7064 case Builtin::BI__builtin_cabsf: 7065 case Builtin::BI__builtin_cabsl: 7066 case Builtin::BIabs: 7067 case Builtin::BIlabs: 7068 case Builtin::BIllabs: 7069 case Builtin::BIfabs: 7070 case Builtin::BIfabsf: 7071 case Builtin::BIfabsl: 7072 case Builtin::BIcabs: 7073 case Builtin::BIcabsf: 7074 case Builtin::BIcabsl: 7075 return FDecl->getBuiltinID(); 7076 } 7077 llvm_unreachable("Unknown Builtin type"); 7078 } 7079 7080 // If the replacement is valid, emit a note with replacement function. 7081 // Additionally, suggest including the proper header if not already included. 7082 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 7083 unsigned AbsKind, QualType ArgType) { 7084 bool EmitHeaderHint = true; 7085 const char *HeaderName = nullptr; 7086 const char *FunctionName = nullptr; 7087 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 7088 FunctionName = "std::abs"; 7089 if (ArgType->isIntegralOrEnumerationType()) { 7090 HeaderName = "cstdlib"; 7091 } else if (ArgType->isRealFloatingType()) { 7092 HeaderName = "cmath"; 7093 } else { 7094 llvm_unreachable("Invalid Type"); 7095 } 7096 7097 // Lookup all std::abs 7098 if (NamespaceDecl *Std = S.getStdNamespace()) { 7099 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 7100 R.suppressDiagnostics(); 7101 S.LookupQualifiedName(R, Std); 7102 7103 for (const auto *I : R) { 7104 const FunctionDecl *FDecl = nullptr; 7105 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 7106 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 7107 } else { 7108 FDecl = dyn_cast<FunctionDecl>(I); 7109 } 7110 if (!FDecl) 7111 continue; 7112 7113 // Found std::abs(), check that they are the right ones. 7114 if (FDecl->getNumParams() != 1) 7115 continue; 7116 7117 // Check that the parameter type can handle the argument. 7118 QualType ParamType = FDecl->getParamDecl(0)->getType(); 7119 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 7120 S.Context.getTypeSize(ArgType) <= 7121 S.Context.getTypeSize(ParamType)) { 7122 // Found a function, don't need the header hint. 7123 EmitHeaderHint = false; 7124 break; 7125 } 7126 } 7127 } 7128 } else { 7129 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 7130 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 7131 7132 if (HeaderName) { 7133 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 7134 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 7135 R.suppressDiagnostics(); 7136 S.LookupName(R, S.getCurScope()); 7137 7138 if (R.isSingleResult()) { 7139 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 7140 if (FD && FD->getBuiltinID() == AbsKind) { 7141 EmitHeaderHint = false; 7142 } else { 7143 return; 7144 } 7145 } else if (!R.empty()) { 7146 return; 7147 } 7148 } 7149 } 7150 7151 S.Diag(Loc, diag::note_replace_abs_function) 7152 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 7153 7154 if (!HeaderName) 7155 return; 7156 7157 if (!EmitHeaderHint) 7158 return; 7159 7160 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 7161 << FunctionName; 7162 } 7163 7164 template <std::size_t StrLen> 7165 static bool IsStdFunction(const FunctionDecl *FDecl, 7166 const char (&Str)[StrLen]) { 7167 if (!FDecl) 7168 return false; 7169 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 7170 return false; 7171 if (!FDecl->isInStdNamespace()) 7172 return false; 7173 7174 return true; 7175 } 7176 7177 // Warn when using the wrong abs() function. 7178 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7179 const FunctionDecl *FDecl) { 7180 if (Call->getNumArgs() != 1) 7181 return; 7182 7183 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7184 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7185 if (AbsKind == 0 && !IsStdAbs) 7186 return; 7187 7188 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7189 QualType ParamType = Call->getArg(0)->getType(); 7190 7191 // Unsigned types cannot be negative. Suggest removing the absolute value 7192 // function call. 7193 if (ArgType->isUnsignedIntegerType()) { 7194 const char *FunctionName = 7195 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7196 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7197 Diag(Call->getExprLoc(), diag::note_remove_abs) 7198 << FunctionName 7199 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7200 return; 7201 } 7202 7203 // Taking the absolute value of a pointer is very suspicious, they probably 7204 // wanted to index into an array, dereference a pointer, call a function, etc. 7205 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7206 unsigned DiagType = 0; 7207 if (ArgType->isFunctionType()) 7208 DiagType = 1; 7209 else if (ArgType->isArrayType()) 7210 DiagType = 2; 7211 7212 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7213 return; 7214 } 7215 7216 // std::abs has overloads which prevent most of the absolute value problems 7217 // from occurring. 7218 if (IsStdAbs) 7219 return; 7220 7221 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7222 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7223 7224 // The argument and parameter are the same kind. Check if they are the right 7225 // size. 7226 if (ArgValueKind == ParamValueKind) { 7227 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7228 return; 7229 7230 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7231 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7232 << FDecl << ArgType << ParamType; 7233 7234 if (NewAbsKind == 0) 7235 return; 7236 7237 emitReplacement(*this, Call->getExprLoc(), 7238 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7239 return; 7240 } 7241 7242 // ArgValueKind != ParamValueKind 7243 // The wrong type of absolute value function was used. Attempt to find the 7244 // proper one. 7245 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7246 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7247 if (NewAbsKind == 0) 7248 return; 7249 7250 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7251 << FDecl << ParamValueKind << ArgValueKind; 7252 7253 emitReplacement(*this, Call->getExprLoc(), 7254 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7255 } 7256 7257 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7258 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7259 const FunctionDecl *FDecl) { 7260 if (!Call || !FDecl) return; 7261 7262 // Ignore template specializations and macros. 7263 if (inTemplateInstantiation()) return; 7264 if (Call->getExprLoc().isMacroID()) return; 7265 7266 // Only care about the one template argument, two function parameter std::max 7267 if (Call->getNumArgs() != 2) return; 7268 if (!IsStdFunction(FDecl, "max")) return; 7269 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7270 if (!ArgList) return; 7271 if (ArgList->size() != 1) return; 7272 7273 // Check that template type argument is unsigned integer. 7274 const auto& TA = ArgList->get(0); 7275 if (TA.getKind() != TemplateArgument::Type) return; 7276 QualType ArgType = TA.getAsType(); 7277 if (!ArgType->isUnsignedIntegerType()) return; 7278 7279 // See if either argument is a literal zero. 7280 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7281 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7282 if (!MTE) return false; 7283 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7284 if (!Num) return false; 7285 if (Num->getValue() != 0) return false; 7286 return true; 7287 }; 7288 7289 const Expr *FirstArg = Call->getArg(0); 7290 const Expr *SecondArg = Call->getArg(1); 7291 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7292 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7293 7294 // Only warn when exactly one argument is zero. 7295 if (IsFirstArgZero == IsSecondArgZero) return; 7296 7297 SourceRange FirstRange = FirstArg->getSourceRange(); 7298 SourceRange SecondRange = SecondArg->getSourceRange(); 7299 7300 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7301 7302 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7303 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7304 7305 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7306 SourceRange RemovalRange; 7307 if (IsFirstArgZero) { 7308 RemovalRange = SourceRange(FirstRange.getBegin(), 7309 SecondRange.getBegin().getLocWithOffset(-1)); 7310 } else { 7311 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7312 SecondRange.getEnd()); 7313 } 7314 7315 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7316 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7317 << FixItHint::CreateRemoval(RemovalRange); 7318 } 7319 7320 //===--- CHECK: Standard memory functions ---------------------------------===// 7321 7322 /// \brief Takes the expression passed to the size_t parameter of functions 7323 /// such as memcmp, strncat, etc and warns if it's a comparison. 7324 /// 7325 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7326 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7327 IdentifierInfo *FnName, 7328 SourceLocation FnLoc, 7329 SourceLocation RParenLoc) { 7330 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7331 if (!Size) 7332 return false; 7333 7334 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 7335 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 7336 return false; 7337 7338 SourceRange SizeRange = Size->getSourceRange(); 7339 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7340 << SizeRange << FnName; 7341 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7342 << FnName << FixItHint::CreateInsertion( 7343 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7344 << FixItHint::CreateRemoval(RParenLoc); 7345 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7346 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7347 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7348 ")"); 7349 7350 return true; 7351 } 7352 7353 /// \brief Determine whether the given type is or contains a dynamic class type 7354 /// (e.g., whether it has a vtable). 7355 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7356 bool &IsContained) { 7357 // Look through array types while ignoring qualifiers. 7358 const Type *Ty = T->getBaseElementTypeUnsafe(); 7359 IsContained = false; 7360 7361 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7362 RD = RD ? RD->getDefinition() : nullptr; 7363 if (!RD || RD->isInvalidDecl()) 7364 return nullptr; 7365 7366 if (RD->isDynamicClass()) 7367 return RD; 7368 7369 // Check all the fields. If any bases were dynamic, the class is dynamic. 7370 // It's impossible for a class to transitively contain itself by value, so 7371 // infinite recursion is impossible. 7372 for (auto *FD : RD->fields()) { 7373 bool SubContained; 7374 if (const CXXRecordDecl *ContainedRD = 7375 getContainedDynamicClass(FD->getType(), SubContained)) { 7376 IsContained = true; 7377 return ContainedRD; 7378 } 7379 } 7380 7381 return nullptr; 7382 } 7383 7384 /// \brief If E is a sizeof expression, returns its argument expression, 7385 /// otherwise returns NULL. 7386 static const Expr *getSizeOfExprArg(const Expr *E) { 7387 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7388 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7389 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType()) 7390 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7391 7392 return nullptr; 7393 } 7394 7395 /// \brief If E is a sizeof expression, returns its argument type. 7396 static QualType getSizeOfArgType(const Expr *E) { 7397 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7398 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7399 if (SizeOf->getKind() == UETT_SizeOf) 7400 return SizeOf->getTypeOfArgument(); 7401 7402 return QualType(); 7403 } 7404 7405 namespace { 7406 7407 struct SearchNonTrivialToInitializeField 7408 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 7409 using Super = 7410 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 7411 7412 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 7413 7414 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 7415 SourceLocation SL) { 7416 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 7417 asDerived().visitArray(PDIK, AT, SL); 7418 return; 7419 } 7420 7421 Super::visitWithKind(PDIK, FT, SL); 7422 } 7423 7424 void visitARCStrong(QualType FT, SourceLocation SL) { 7425 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 7426 } 7427 void visitARCWeak(QualType FT, SourceLocation SL) { 7428 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 7429 } 7430 void visitStruct(QualType FT, SourceLocation SL) { 7431 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 7432 visit(FD->getType(), FD->getLocation()); 7433 } 7434 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 7435 const ArrayType *AT, SourceLocation SL) { 7436 visit(getContext().getBaseElementType(AT), SL); 7437 } 7438 void visitTrivial(QualType FT, SourceLocation SL) {} 7439 7440 static void diag(QualType RT, const Expr *E, Sema &S) { 7441 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 7442 } 7443 7444 ASTContext &getContext() { return S.getASTContext(); } 7445 7446 const Expr *E; 7447 Sema &S; 7448 }; 7449 7450 struct SearchNonTrivialToCopyField 7451 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 7452 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 7453 7454 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 7455 7456 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 7457 SourceLocation SL) { 7458 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 7459 asDerived().visitArray(PCK, AT, SL); 7460 return; 7461 } 7462 7463 Super::visitWithKind(PCK, FT, SL); 7464 } 7465 7466 void visitARCStrong(QualType FT, SourceLocation SL) { 7467 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 7468 } 7469 void visitARCWeak(QualType FT, SourceLocation SL) { 7470 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 7471 } 7472 void visitStruct(QualType FT, SourceLocation SL) { 7473 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 7474 visit(FD->getType(), FD->getLocation()); 7475 } 7476 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 7477 SourceLocation SL) { 7478 visit(getContext().getBaseElementType(AT), SL); 7479 } 7480 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 7481 SourceLocation SL) {} 7482 void visitTrivial(QualType FT, SourceLocation SL) {} 7483 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 7484 7485 static void diag(QualType RT, const Expr *E, Sema &S) { 7486 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 7487 } 7488 7489 ASTContext &getContext() { return S.getASTContext(); } 7490 7491 const Expr *E; 7492 Sema &S; 7493 }; 7494 7495 } 7496 7497 /// \brief Check for dangerous or invalid arguments to memset(). 7498 /// 7499 /// This issues warnings on known problematic, dangerous or unspecified 7500 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7501 /// function calls. 7502 /// 7503 /// \param Call The call expression to diagnose. 7504 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7505 unsigned BId, 7506 IdentifierInfo *FnName) { 7507 assert(BId != 0); 7508 7509 // It is possible to have a non-standard definition of memset. Validate 7510 // we have enough arguments, and if not, abort further checking. 7511 unsigned ExpectedNumArgs = 7512 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7513 if (Call->getNumArgs() < ExpectedNumArgs) 7514 return; 7515 7516 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7517 BId == Builtin::BIstrndup ? 1 : 2); 7518 unsigned LenArg = 7519 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7520 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7521 7522 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7523 Call->getLocStart(), Call->getRParenLoc())) 7524 return; 7525 7526 // We have special checking when the length is a sizeof expression. 7527 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7528 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7529 llvm::FoldingSetNodeID SizeOfArgID; 7530 7531 // Although widely used, 'bzero' is not a standard function. Be more strict 7532 // with the argument types before allowing diagnostics and only allow the 7533 // form bzero(ptr, sizeof(...)). 7534 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7535 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7536 return; 7537 7538 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7539 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7540 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7541 7542 QualType DestTy = Dest->getType(); 7543 QualType PointeeTy; 7544 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7545 PointeeTy = DestPtrTy->getPointeeType(); 7546 7547 // Never warn about void type pointers. This can be used to suppress 7548 // false positives. 7549 if (PointeeTy->isVoidType()) 7550 continue; 7551 7552 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7553 // actually comparing the expressions for equality. Because computing the 7554 // expression IDs can be expensive, we only do this if the diagnostic is 7555 // enabled. 7556 if (SizeOfArg && 7557 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7558 SizeOfArg->getExprLoc())) { 7559 // We only compute IDs for expressions if the warning is enabled, and 7560 // cache the sizeof arg's ID. 7561 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7562 SizeOfArg->Profile(SizeOfArgID, Context, true); 7563 llvm::FoldingSetNodeID DestID; 7564 Dest->Profile(DestID, Context, true); 7565 if (DestID == SizeOfArgID) { 7566 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7567 // over sizeof(src) as well. 7568 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7569 StringRef ReadableName = FnName->getName(); 7570 7571 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7572 if (UnaryOp->getOpcode() == UO_AddrOf) 7573 ActionIdx = 1; // If its an address-of operator, just remove it. 7574 if (!PointeeTy->isIncompleteType() && 7575 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7576 ActionIdx = 2; // If the pointee's size is sizeof(char), 7577 // suggest an explicit length. 7578 7579 // If the function is defined as a builtin macro, do not show macro 7580 // expansion. 7581 SourceLocation SL = SizeOfArg->getExprLoc(); 7582 SourceRange DSR = Dest->getSourceRange(); 7583 SourceRange SSR = SizeOfArg->getSourceRange(); 7584 SourceManager &SM = getSourceManager(); 7585 7586 if (SM.isMacroArgExpansion(SL)) { 7587 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7588 SL = SM.getSpellingLoc(SL); 7589 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7590 SM.getSpellingLoc(DSR.getEnd())); 7591 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7592 SM.getSpellingLoc(SSR.getEnd())); 7593 } 7594 7595 DiagRuntimeBehavior(SL, SizeOfArg, 7596 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7597 << ReadableName 7598 << PointeeTy 7599 << DestTy 7600 << DSR 7601 << SSR); 7602 DiagRuntimeBehavior(SL, SizeOfArg, 7603 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7604 << ActionIdx 7605 << SSR); 7606 7607 break; 7608 } 7609 } 7610 7611 // Also check for cases where the sizeof argument is the exact same 7612 // type as the memory argument, and where it points to a user-defined 7613 // record type. 7614 if (SizeOfArgTy != QualType()) { 7615 if (PointeeTy->isRecordType() && 7616 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7617 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7618 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7619 << FnName << SizeOfArgTy << ArgIdx 7620 << PointeeTy << Dest->getSourceRange() 7621 << LenExpr->getSourceRange()); 7622 break; 7623 } 7624 } 7625 } else if (DestTy->isArrayType()) { 7626 PointeeTy = DestTy; 7627 } 7628 7629 if (PointeeTy == QualType()) 7630 continue; 7631 7632 // Always complain about dynamic classes. 7633 bool IsContained; 7634 if (const CXXRecordDecl *ContainedRD = 7635 getContainedDynamicClass(PointeeTy, IsContained)) { 7636 7637 unsigned OperationType = 0; 7638 // "overwritten" if we're warning about the destination for any call 7639 // but memcmp; otherwise a verb appropriate to the call. 7640 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7641 if (BId == Builtin::BImemcpy) 7642 OperationType = 1; 7643 else if(BId == Builtin::BImemmove) 7644 OperationType = 2; 7645 else if (BId == Builtin::BImemcmp) 7646 OperationType = 3; 7647 } 7648 7649 DiagRuntimeBehavior( 7650 Dest->getExprLoc(), Dest, 7651 PDiag(diag::warn_dyn_class_memaccess) 7652 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7653 << FnName << IsContained << ContainedRD << OperationType 7654 << Call->getCallee()->getSourceRange()); 7655 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7656 BId != Builtin::BImemset) 7657 DiagRuntimeBehavior( 7658 Dest->getExprLoc(), Dest, 7659 PDiag(diag::warn_arc_object_memaccess) 7660 << ArgIdx << FnName << PointeeTy 7661 << Call->getCallee()->getSourceRange()); 7662 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 7663 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 7664 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 7665 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 7666 PDiag(diag::warn_cstruct_memaccess) 7667 << ArgIdx << FnName << PointeeTy << 0); 7668 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 7669 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 7670 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 7671 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 7672 PDiag(diag::warn_cstruct_memaccess) 7673 << ArgIdx << FnName << PointeeTy << 1); 7674 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 7675 } else { 7676 continue; 7677 } 7678 } else 7679 continue; 7680 7681 DiagRuntimeBehavior( 7682 Dest->getExprLoc(), Dest, 7683 PDiag(diag::note_bad_memaccess_silence) 7684 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7685 break; 7686 } 7687 } 7688 7689 // A little helper routine: ignore addition and subtraction of integer literals. 7690 // This intentionally does not ignore all integer constant expressions because 7691 // we don't want to remove sizeof(). 7692 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7693 Ex = Ex->IgnoreParenCasts(); 7694 7695 while (true) { 7696 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7697 if (!BO || !BO->isAdditiveOp()) 7698 break; 7699 7700 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7701 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7702 7703 if (isa<IntegerLiteral>(RHS)) 7704 Ex = LHS; 7705 else if (isa<IntegerLiteral>(LHS)) 7706 Ex = RHS; 7707 else 7708 break; 7709 } 7710 7711 return Ex; 7712 } 7713 7714 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7715 ASTContext &Context) { 7716 // Only handle constant-sized or VLAs, but not flexible members. 7717 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7718 // Only issue the FIXIT for arrays of size > 1. 7719 if (CAT->getSize().getSExtValue() <= 1) 7720 return false; 7721 } else if (!Ty->isVariableArrayType()) { 7722 return false; 7723 } 7724 return true; 7725 } 7726 7727 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7728 // be the size of the source, instead of the destination. 7729 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7730 IdentifierInfo *FnName) { 7731 7732 // Don't crash if the user has the wrong number of arguments 7733 unsigned NumArgs = Call->getNumArgs(); 7734 if ((NumArgs != 3) && (NumArgs != 4)) 7735 return; 7736 7737 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7738 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7739 const Expr *CompareWithSrc = nullptr; 7740 7741 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7742 Call->getLocStart(), Call->getRParenLoc())) 7743 return; 7744 7745 // Look for 'strlcpy(dst, x, sizeof(x))' 7746 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7747 CompareWithSrc = Ex; 7748 else { 7749 // Look for 'strlcpy(dst, x, strlen(x))' 7750 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7751 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7752 SizeCall->getNumArgs() == 1) 7753 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7754 } 7755 } 7756 7757 if (!CompareWithSrc) 7758 return; 7759 7760 // Determine if the argument to sizeof/strlen is equal to the source 7761 // argument. In principle there's all kinds of things you could do 7762 // here, for instance creating an == expression and evaluating it with 7763 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7764 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7765 if (!SrcArgDRE) 7766 return; 7767 7768 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7769 if (!CompareWithSrcDRE || 7770 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7771 return; 7772 7773 const Expr *OriginalSizeArg = Call->getArg(2); 7774 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7775 << OriginalSizeArg->getSourceRange() << FnName; 7776 7777 // Output a FIXIT hint if the destination is an array (rather than a 7778 // pointer to an array). This could be enhanced to handle some 7779 // pointers if we know the actual size, like if DstArg is 'array+2' 7780 // we could say 'sizeof(array)-2'. 7781 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7782 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7783 return; 7784 7785 SmallString<128> sizeString; 7786 llvm::raw_svector_ostream OS(sizeString); 7787 OS << "sizeof("; 7788 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7789 OS << ")"; 7790 7791 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7792 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7793 OS.str()); 7794 } 7795 7796 /// Check if two expressions refer to the same declaration. 7797 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7798 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7799 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7800 return D1->getDecl() == D2->getDecl(); 7801 return false; 7802 } 7803 7804 static const Expr *getStrlenExprArg(const Expr *E) { 7805 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7806 const FunctionDecl *FD = CE->getDirectCallee(); 7807 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7808 return nullptr; 7809 return CE->getArg(0)->IgnoreParenCasts(); 7810 } 7811 return nullptr; 7812 } 7813 7814 // Warn on anti-patterns as the 'size' argument to strncat. 7815 // The correct size argument should look like following: 7816 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7817 void Sema::CheckStrncatArguments(const CallExpr *CE, 7818 IdentifierInfo *FnName) { 7819 // Don't crash if the user has the wrong number of arguments. 7820 if (CE->getNumArgs() < 3) 7821 return; 7822 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7823 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7824 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7825 7826 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7827 CE->getRParenLoc())) 7828 return; 7829 7830 // Identify common expressions, which are wrongly used as the size argument 7831 // to strncat and may lead to buffer overflows. 7832 unsigned PatternType = 0; 7833 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7834 // - sizeof(dst) 7835 if (referToTheSameDecl(SizeOfArg, DstArg)) 7836 PatternType = 1; 7837 // - sizeof(src) 7838 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7839 PatternType = 2; 7840 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7841 if (BE->getOpcode() == BO_Sub) { 7842 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7843 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7844 // - sizeof(dst) - strlen(dst) 7845 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7846 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7847 PatternType = 1; 7848 // - sizeof(src) - (anything) 7849 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7850 PatternType = 2; 7851 } 7852 } 7853 7854 if (PatternType == 0) 7855 return; 7856 7857 // Generate the diagnostic. 7858 SourceLocation SL = LenArg->getLocStart(); 7859 SourceRange SR = LenArg->getSourceRange(); 7860 SourceManager &SM = getSourceManager(); 7861 7862 // If the function is defined as a builtin macro, do not show macro expansion. 7863 if (SM.isMacroArgExpansion(SL)) { 7864 SL = SM.getSpellingLoc(SL); 7865 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7866 SM.getSpellingLoc(SR.getEnd())); 7867 } 7868 7869 // Check if the destination is an array (rather than a pointer to an array). 7870 QualType DstTy = DstArg->getType(); 7871 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7872 Context); 7873 if (!isKnownSizeArray) { 7874 if (PatternType == 1) 7875 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7876 else 7877 Diag(SL, diag::warn_strncat_src_size) << SR; 7878 return; 7879 } 7880 7881 if (PatternType == 1) 7882 Diag(SL, diag::warn_strncat_large_size) << SR; 7883 else 7884 Diag(SL, diag::warn_strncat_src_size) << SR; 7885 7886 SmallString<128> sizeString; 7887 llvm::raw_svector_ostream OS(sizeString); 7888 OS << "sizeof("; 7889 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7890 OS << ") - "; 7891 OS << "strlen("; 7892 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7893 OS << ") - 1"; 7894 7895 Diag(SL, diag::note_strncat_wrong_size) 7896 << FixItHint::CreateReplacement(SR, OS.str()); 7897 } 7898 7899 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7900 7901 static const Expr *EvalVal(const Expr *E, 7902 SmallVectorImpl<const DeclRefExpr *> &refVars, 7903 const Decl *ParentDecl); 7904 static const Expr *EvalAddr(const Expr *E, 7905 SmallVectorImpl<const DeclRefExpr *> &refVars, 7906 const Decl *ParentDecl); 7907 7908 /// CheckReturnStackAddr - Check if a return statement returns the address 7909 /// of a stack variable. 7910 static void 7911 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7912 SourceLocation ReturnLoc) { 7913 const Expr *stackE = nullptr; 7914 SmallVector<const DeclRefExpr *, 8> refVars; 7915 7916 // Perform checking for returned stack addresses, local blocks, 7917 // label addresses or references to temporaries. 7918 if (lhsType->isPointerType() || 7919 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7920 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7921 } else if (lhsType->isReferenceType()) { 7922 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7923 } 7924 7925 if (!stackE) 7926 return; // Nothing suspicious was found. 7927 7928 // Parameters are initialized in the calling scope, so taking the address 7929 // of a parameter reference doesn't need a warning. 7930 for (auto *DRE : refVars) 7931 if (isa<ParmVarDecl>(DRE->getDecl())) 7932 return; 7933 7934 SourceLocation diagLoc; 7935 SourceRange diagRange; 7936 if (refVars.empty()) { 7937 diagLoc = stackE->getLocStart(); 7938 diagRange = stackE->getSourceRange(); 7939 } else { 7940 // We followed through a reference variable. 'stackE' contains the 7941 // problematic expression but we will warn at the return statement pointing 7942 // at the reference variable. We will later display the "trail" of 7943 // reference variables using notes. 7944 diagLoc = refVars[0]->getLocStart(); 7945 diagRange = refVars[0]->getSourceRange(); 7946 } 7947 7948 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7949 // address of local var 7950 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7951 << DR->getDecl()->getDeclName() << diagRange; 7952 } else if (isa<BlockExpr>(stackE)) { // local block. 7953 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7954 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7955 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7956 } else { // local temporary. 7957 // If there is an LValue->RValue conversion, then the value of the 7958 // reference type is used, not the reference. 7959 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7960 if (ICE->getCastKind() == CK_LValueToRValue) { 7961 return; 7962 } 7963 } 7964 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7965 << lhsType->isReferenceType() << diagRange; 7966 } 7967 7968 // Display the "trail" of reference variables that we followed until we 7969 // found the problematic expression using notes. 7970 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7971 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7972 // If this var binds to another reference var, show the range of the next 7973 // var, otherwise the var binds to the problematic expression, in which case 7974 // show the range of the expression. 7975 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7976 : stackE->getSourceRange(); 7977 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7978 << VD->getDeclName() << range; 7979 } 7980 } 7981 7982 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7983 /// check if the expression in a return statement evaluates to an address 7984 /// to a location on the stack, a local block, an address of a label, or a 7985 /// reference to local temporary. The recursion is used to traverse the 7986 /// AST of the return expression, with recursion backtracking when we 7987 /// encounter a subexpression that (1) clearly does not lead to one of the 7988 /// above problematic expressions (2) is something we cannot determine leads to 7989 /// a problematic expression based on such local checking. 7990 /// 7991 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7992 /// the expression that they point to. Such variables are added to the 7993 /// 'refVars' vector so that we know what the reference variable "trail" was. 7994 /// 7995 /// EvalAddr processes expressions that are pointers that are used as 7996 /// references (and not L-values). EvalVal handles all other values. 7997 /// At the base case of the recursion is a check for the above problematic 7998 /// expressions. 7999 /// 8000 /// This implementation handles: 8001 /// 8002 /// * pointer-to-pointer casts 8003 /// * implicit conversions from array references to pointers 8004 /// * taking the address of fields 8005 /// * arbitrary interplay between "&" and "*" operators 8006 /// * pointer arithmetic from an address of a stack variable 8007 /// * taking the address of an array element where the array is on the stack 8008 static const Expr *EvalAddr(const Expr *E, 8009 SmallVectorImpl<const DeclRefExpr *> &refVars, 8010 const Decl *ParentDecl) { 8011 if (E->isTypeDependent()) 8012 return nullptr; 8013 8014 // We should only be called for evaluating pointer expressions. 8015 assert((E->getType()->isAnyPointerType() || 8016 E->getType()->isBlockPointerType() || 8017 E->getType()->isObjCQualifiedIdType()) && 8018 "EvalAddr only works on pointers"); 8019 8020 E = E->IgnoreParens(); 8021 8022 // Our "symbolic interpreter" is just a dispatch off the currently 8023 // viewed AST node. We then recursively traverse the AST by calling 8024 // EvalAddr and EvalVal appropriately. 8025 switch (E->getStmtClass()) { 8026 case Stmt::DeclRefExprClass: { 8027 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8028 8029 // If we leave the immediate function, the lifetime isn't about to end. 8030 if (DR->refersToEnclosingVariableOrCapture()) 8031 return nullptr; 8032 8033 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 8034 // If this is a reference variable, follow through to the expression that 8035 // it points to. 8036 if (V->hasLocalStorage() && 8037 V->getType()->isReferenceType() && V->hasInit()) { 8038 // Add the reference variable to the "trail". 8039 refVars.push_back(DR); 8040 return EvalAddr(V->getInit(), refVars, ParentDecl); 8041 } 8042 8043 return nullptr; 8044 } 8045 8046 case Stmt::UnaryOperatorClass: { 8047 // The only unary operator that make sense to handle here 8048 // is AddrOf. All others don't make sense as pointers. 8049 const UnaryOperator *U = cast<UnaryOperator>(E); 8050 8051 if (U->getOpcode() == UO_AddrOf) 8052 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 8053 return nullptr; 8054 } 8055 8056 case Stmt::BinaryOperatorClass: { 8057 // Handle pointer arithmetic. All other binary operators are not valid 8058 // in this context. 8059 const BinaryOperator *B = cast<BinaryOperator>(E); 8060 BinaryOperatorKind op = B->getOpcode(); 8061 8062 if (op != BO_Add && op != BO_Sub) 8063 return nullptr; 8064 8065 const Expr *Base = B->getLHS(); 8066 8067 // Determine which argument is the real pointer base. It could be 8068 // the RHS argument instead of the LHS. 8069 if (!Base->getType()->isPointerType()) 8070 Base = B->getRHS(); 8071 8072 assert(Base->getType()->isPointerType()); 8073 return EvalAddr(Base, refVars, ParentDecl); 8074 } 8075 8076 // For conditional operators we need to see if either the LHS or RHS are 8077 // valid DeclRefExpr*s. If one of them is valid, we return it. 8078 case Stmt::ConditionalOperatorClass: { 8079 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8080 8081 // Handle the GNU extension for missing LHS. 8082 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 8083 if (const Expr *LHSExpr = C->getLHS()) { 8084 // In C++, we can have a throw-expression, which has 'void' type. 8085 if (!LHSExpr->getType()->isVoidType()) 8086 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 8087 return LHS; 8088 } 8089 8090 // In C++, we can have a throw-expression, which has 'void' type. 8091 if (C->getRHS()->getType()->isVoidType()) 8092 return nullptr; 8093 8094 return EvalAddr(C->getRHS(), refVars, ParentDecl); 8095 } 8096 8097 case Stmt::BlockExprClass: 8098 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 8099 return E; // local block. 8100 return nullptr; 8101 8102 case Stmt::AddrLabelExprClass: 8103 return E; // address of label. 8104 8105 case Stmt::ExprWithCleanupsClass: 8106 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8107 ParentDecl); 8108 8109 // For casts, we need to handle conversions from arrays to 8110 // pointer values, and pointer-to-pointer conversions. 8111 case Stmt::ImplicitCastExprClass: 8112 case Stmt::CStyleCastExprClass: 8113 case Stmt::CXXFunctionalCastExprClass: 8114 case Stmt::ObjCBridgedCastExprClass: 8115 case Stmt::CXXStaticCastExprClass: 8116 case Stmt::CXXDynamicCastExprClass: 8117 case Stmt::CXXConstCastExprClass: 8118 case Stmt::CXXReinterpretCastExprClass: { 8119 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 8120 switch (cast<CastExpr>(E)->getCastKind()) { 8121 case CK_LValueToRValue: 8122 case CK_NoOp: 8123 case CK_BaseToDerived: 8124 case CK_DerivedToBase: 8125 case CK_UncheckedDerivedToBase: 8126 case CK_Dynamic: 8127 case CK_CPointerToObjCPointerCast: 8128 case CK_BlockPointerToObjCPointerCast: 8129 case CK_AnyPointerToBlockPointerCast: 8130 return EvalAddr(SubExpr, refVars, ParentDecl); 8131 8132 case CK_ArrayToPointerDecay: 8133 return EvalVal(SubExpr, refVars, ParentDecl); 8134 8135 case CK_BitCast: 8136 if (SubExpr->getType()->isAnyPointerType() || 8137 SubExpr->getType()->isBlockPointerType() || 8138 SubExpr->getType()->isObjCQualifiedIdType()) 8139 return EvalAddr(SubExpr, refVars, ParentDecl); 8140 else 8141 return nullptr; 8142 8143 default: 8144 return nullptr; 8145 } 8146 } 8147 8148 case Stmt::MaterializeTemporaryExprClass: 8149 if (const Expr *Result = 8150 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8151 refVars, ParentDecl)) 8152 return Result; 8153 return E; 8154 8155 // Everything else: we simply don't reason about them. 8156 default: 8157 return nullptr; 8158 } 8159 } 8160 8161 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 8162 /// See the comments for EvalAddr for more details. 8163 static const Expr *EvalVal(const Expr *E, 8164 SmallVectorImpl<const DeclRefExpr *> &refVars, 8165 const Decl *ParentDecl) { 8166 do { 8167 // We should only be called for evaluating non-pointer expressions, or 8168 // expressions with a pointer type that are not used as references but 8169 // instead 8170 // are l-values (e.g., DeclRefExpr with a pointer type). 8171 8172 // Our "symbolic interpreter" is just a dispatch off the currently 8173 // viewed AST node. We then recursively traverse the AST by calling 8174 // EvalAddr and EvalVal appropriately. 8175 8176 E = E->IgnoreParens(); 8177 switch (E->getStmtClass()) { 8178 case Stmt::ImplicitCastExprClass: { 8179 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 8180 if (IE->getValueKind() == VK_LValue) { 8181 E = IE->getSubExpr(); 8182 continue; 8183 } 8184 return nullptr; 8185 } 8186 8187 case Stmt::ExprWithCleanupsClass: 8188 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8189 ParentDecl); 8190 8191 case Stmt::DeclRefExprClass: { 8192 // When we hit a DeclRefExpr we are looking at code that refers to a 8193 // variable's name. If it's not a reference variable we check if it has 8194 // local storage within the function, and if so, return the expression. 8195 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8196 8197 // If we leave the immediate function, the lifetime isn't about to end. 8198 if (DR->refersToEnclosingVariableOrCapture()) 8199 return nullptr; 8200 8201 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 8202 // Check if it refers to itself, e.g. "int& i = i;". 8203 if (V == ParentDecl) 8204 return DR; 8205 8206 if (V->hasLocalStorage()) { 8207 if (!V->getType()->isReferenceType()) 8208 return DR; 8209 8210 // Reference variable, follow through to the expression that 8211 // it points to. 8212 if (V->hasInit()) { 8213 // Add the reference variable to the "trail". 8214 refVars.push_back(DR); 8215 return EvalVal(V->getInit(), refVars, V); 8216 } 8217 } 8218 } 8219 8220 return nullptr; 8221 } 8222 8223 case Stmt::UnaryOperatorClass: { 8224 // The only unary operator that make sense to handle here 8225 // is Deref. All others don't resolve to a "name." This includes 8226 // handling all sorts of rvalues passed to a unary operator. 8227 const UnaryOperator *U = cast<UnaryOperator>(E); 8228 8229 if (U->getOpcode() == UO_Deref) 8230 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 8231 8232 return nullptr; 8233 } 8234 8235 case Stmt::ArraySubscriptExprClass: { 8236 // Array subscripts are potential references to data on the stack. We 8237 // retrieve the DeclRefExpr* for the array variable if it indeed 8238 // has local storage. 8239 const auto *ASE = cast<ArraySubscriptExpr>(E); 8240 if (ASE->isTypeDependent()) 8241 return nullptr; 8242 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 8243 } 8244 8245 case Stmt::OMPArraySectionExprClass: { 8246 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 8247 ParentDecl); 8248 } 8249 8250 case Stmt::ConditionalOperatorClass: { 8251 // For conditional operators we need to see if either the LHS or RHS are 8252 // non-NULL Expr's. If one is non-NULL, we return it. 8253 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8254 8255 // Handle the GNU extension for missing LHS. 8256 if (const Expr *LHSExpr = C->getLHS()) { 8257 // In C++, we can have a throw-expression, which has 'void' type. 8258 if (!LHSExpr->getType()->isVoidType()) 8259 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 8260 return LHS; 8261 } 8262 8263 // In C++, we can have a throw-expression, which has 'void' type. 8264 if (C->getRHS()->getType()->isVoidType()) 8265 return nullptr; 8266 8267 return EvalVal(C->getRHS(), refVars, ParentDecl); 8268 } 8269 8270 // Accesses to members are potential references to data on the stack. 8271 case Stmt::MemberExprClass: { 8272 const MemberExpr *M = cast<MemberExpr>(E); 8273 8274 // Check for indirect access. We only want direct field accesses. 8275 if (M->isArrow()) 8276 return nullptr; 8277 8278 // Check whether the member type is itself a reference, in which case 8279 // we're not going to refer to the member, but to what the member refers 8280 // to. 8281 if (M->getMemberDecl()->getType()->isReferenceType()) 8282 return nullptr; 8283 8284 return EvalVal(M->getBase(), refVars, ParentDecl); 8285 } 8286 8287 case Stmt::MaterializeTemporaryExprClass: 8288 if (const Expr *Result = 8289 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8290 refVars, ParentDecl)) 8291 return Result; 8292 return E; 8293 8294 default: 8295 // Check that we don't return or take the address of a reference to a 8296 // temporary. This is only useful in C++. 8297 if (!E->isTypeDependent() && E->isRValue()) 8298 return E; 8299 8300 // Everything else: we simply don't reason about them. 8301 return nullptr; 8302 } 8303 } while (true); 8304 } 8305 8306 void 8307 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8308 SourceLocation ReturnLoc, 8309 bool isObjCMethod, 8310 const AttrVec *Attrs, 8311 const FunctionDecl *FD) { 8312 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8313 8314 // Check if the return value is null but should not be. 8315 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8316 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8317 CheckNonNullExpr(*this, RetValExp)) 8318 Diag(ReturnLoc, diag::warn_null_ret) 8319 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8320 8321 // C++11 [basic.stc.dynamic.allocation]p4: 8322 // If an allocation function declared with a non-throwing 8323 // exception-specification fails to allocate storage, it shall return 8324 // a null pointer. Any other allocation function that fails to allocate 8325 // storage shall indicate failure only by throwing an exception [...] 8326 if (FD) { 8327 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8328 if (Op == OO_New || Op == OO_Array_New) { 8329 const FunctionProtoType *Proto 8330 = FD->getType()->castAs<FunctionProtoType>(); 8331 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 8332 CheckNonNullExpr(*this, RetValExp)) 8333 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8334 << FD << getLangOpts().CPlusPlus11; 8335 } 8336 } 8337 } 8338 8339 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8340 8341 /// Check for comparisons of floating point operands using != and ==. 8342 /// Issue a warning if these are no self-comparisons, as they are not likely 8343 /// to do what the programmer intended. 8344 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8345 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8346 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8347 8348 // Special case: check for x == x (which is OK). 8349 // Do not emit warnings for such cases. 8350 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8351 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8352 if (DRL->getDecl() == DRR->getDecl()) 8353 return; 8354 8355 // Special case: check for comparisons against literals that can be exactly 8356 // represented by APFloat. In such cases, do not emit a warning. This 8357 // is a heuristic: often comparison against such literals are used to 8358 // detect if a value in a variable has not changed. This clearly can 8359 // lead to false negatives. 8360 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8361 if (FLL->isExact()) 8362 return; 8363 } else 8364 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8365 if (FLR->isExact()) 8366 return; 8367 8368 // Check for comparisons with builtin types. 8369 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8370 if (CL->getBuiltinCallee()) 8371 return; 8372 8373 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8374 if (CR->getBuiltinCallee()) 8375 return; 8376 8377 // Emit the diagnostic. 8378 Diag(Loc, diag::warn_floatingpoint_eq) 8379 << LHS->getSourceRange() << RHS->getSourceRange(); 8380 } 8381 8382 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8383 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8384 8385 namespace { 8386 8387 /// Structure recording the 'active' range of an integer-valued 8388 /// expression. 8389 struct IntRange { 8390 /// The number of bits active in the int. 8391 unsigned Width; 8392 8393 /// True if the int is known not to have negative values. 8394 bool NonNegative; 8395 8396 IntRange(unsigned Width, bool NonNegative) 8397 : Width(Width), NonNegative(NonNegative) {} 8398 8399 /// Returns the range of the bool type. 8400 static IntRange forBoolType() { 8401 return IntRange(1, true); 8402 } 8403 8404 /// Returns the range of an opaque value of the given integral type. 8405 static IntRange forValueOfType(ASTContext &C, QualType T) { 8406 return forValueOfCanonicalType(C, 8407 T->getCanonicalTypeInternal().getTypePtr()); 8408 } 8409 8410 /// Returns the range of an opaque value of a canonical integral type. 8411 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8412 assert(T->isCanonicalUnqualified()); 8413 8414 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8415 T = VT->getElementType().getTypePtr(); 8416 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8417 T = CT->getElementType().getTypePtr(); 8418 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8419 T = AT->getValueType().getTypePtr(); 8420 8421 if (!C.getLangOpts().CPlusPlus) { 8422 // For enum types in C code, use the underlying datatype. 8423 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8424 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 8425 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8426 // For enum types in C++, use the known bit width of the enumerators. 8427 EnumDecl *Enum = ET->getDecl(); 8428 // In C++11, enums can have a fixed underlying type. Use this type to 8429 // compute the range. 8430 if (Enum->isFixed()) { 8431 return IntRange(C.getIntWidth(QualType(T, 0)), 8432 !ET->isSignedIntegerOrEnumerationType()); 8433 } 8434 8435 unsigned NumPositive = Enum->getNumPositiveBits(); 8436 unsigned NumNegative = Enum->getNumNegativeBits(); 8437 8438 if (NumNegative == 0) 8439 return IntRange(NumPositive, true/*NonNegative*/); 8440 else 8441 return IntRange(std::max(NumPositive + 1, NumNegative), 8442 false/*NonNegative*/); 8443 } 8444 8445 const BuiltinType *BT = cast<BuiltinType>(T); 8446 assert(BT->isInteger()); 8447 8448 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8449 } 8450 8451 /// Returns the "target" range of a canonical integral type, i.e. 8452 /// the range of values expressible in the type. 8453 /// 8454 /// This matches forValueOfCanonicalType except that enums have the 8455 /// full range of their type, not the range of their enumerators. 8456 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8457 assert(T->isCanonicalUnqualified()); 8458 8459 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8460 T = VT->getElementType().getTypePtr(); 8461 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8462 T = CT->getElementType().getTypePtr(); 8463 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8464 T = AT->getValueType().getTypePtr(); 8465 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8466 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8467 8468 const BuiltinType *BT = cast<BuiltinType>(T); 8469 assert(BT->isInteger()); 8470 8471 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8472 } 8473 8474 /// Returns the supremum of two ranges: i.e. their conservative merge. 8475 static IntRange join(IntRange L, IntRange R) { 8476 return IntRange(std::max(L.Width, R.Width), 8477 L.NonNegative && R.NonNegative); 8478 } 8479 8480 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8481 static IntRange meet(IntRange L, IntRange R) { 8482 return IntRange(std::min(L.Width, R.Width), 8483 L.NonNegative || R.NonNegative); 8484 } 8485 }; 8486 8487 } // namespace 8488 8489 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 8490 unsigned MaxWidth) { 8491 if (value.isSigned() && value.isNegative()) 8492 return IntRange(value.getMinSignedBits(), false); 8493 8494 if (value.getBitWidth() > MaxWidth) 8495 value = value.trunc(MaxWidth); 8496 8497 // isNonNegative() just checks the sign bit without considering 8498 // signedness. 8499 return IntRange(value.getActiveBits(), true); 8500 } 8501 8502 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8503 unsigned MaxWidth) { 8504 if (result.isInt()) 8505 return GetValueRange(C, result.getInt(), MaxWidth); 8506 8507 if (result.isVector()) { 8508 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8509 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8510 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8511 R = IntRange::join(R, El); 8512 } 8513 return R; 8514 } 8515 8516 if (result.isComplexInt()) { 8517 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8518 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8519 return IntRange::join(R, I); 8520 } 8521 8522 // This can happen with lossless casts to intptr_t of "based" lvalues. 8523 // Assume it might use arbitrary bits. 8524 // FIXME: The only reason we need to pass the type in here is to get 8525 // the sign right on this one case. It would be nice if APValue 8526 // preserved this. 8527 assert(result.isLValue() || result.isAddrLabelDiff()); 8528 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8529 } 8530 8531 static QualType GetExprType(const Expr *E) { 8532 QualType Ty = E->getType(); 8533 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8534 Ty = AtomicRHS->getValueType(); 8535 return Ty; 8536 } 8537 8538 /// Pseudo-evaluate the given integer expression, estimating the 8539 /// range of values it might take. 8540 /// 8541 /// \param MaxWidth - the width to which the value will be truncated 8542 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8543 E = E->IgnoreParens(); 8544 8545 // Try a full evaluation first. 8546 Expr::EvalResult result; 8547 if (E->EvaluateAsRValue(result, C)) 8548 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8549 8550 // I think we only want to look through implicit casts here; if the 8551 // user has an explicit widening cast, we should treat the value as 8552 // being of the new, wider type. 8553 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8554 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8555 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8556 8557 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8558 8559 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8560 CE->getCastKind() == CK_BooleanToSignedIntegral; 8561 8562 // Assume that non-integer casts can span the full range of the type. 8563 if (!isIntegerCast) 8564 return OutputTypeRange; 8565 8566 IntRange SubRange 8567 = GetExprRange(C, CE->getSubExpr(), 8568 std::min(MaxWidth, OutputTypeRange.Width)); 8569 8570 // Bail out if the subexpr's range is as wide as the cast type. 8571 if (SubRange.Width >= OutputTypeRange.Width) 8572 return OutputTypeRange; 8573 8574 // Otherwise, we take the smaller width, and we're non-negative if 8575 // either the output type or the subexpr is. 8576 return IntRange(SubRange.Width, 8577 SubRange.NonNegative || OutputTypeRange.NonNegative); 8578 } 8579 8580 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8581 // If we can fold the condition, just take that operand. 8582 bool CondResult; 8583 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8584 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8585 : CO->getFalseExpr(), 8586 MaxWidth); 8587 8588 // Otherwise, conservatively merge. 8589 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8590 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8591 return IntRange::join(L, R); 8592 } 8593 8594 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8595 switch (BO->getOpcode()) { 8596 case BO_Cmp: 8597 llvm_unreachable("builtin <=> should have class type"); 8598 8599 // Boolean-valued operations are single-bit and positive. 8600 case BO_LAnd: 8601 case BO_LOr: 8602 case BO_LT: 8603 case BO_GT: 8604 case BO_LE: 8605 case BO_GE: 8606 case BO_EQ: 8607 case BO_NE: 8608 return IntRange::forBoolType(); 8609 8610 // The type of the assignments is the type of the LHS, so the RHS 8611 // is not necessarily the same type. 8612 case BO_MulAssign: 8613 case BO_DivAssign: 8614 case BO_RemAssign: 8615 case BO_AddAssign: 8616 case BO_SubAssign: 8617 case BO_XorAssign: 8618 case BO_OrAssign: 8619 // TODO: bitfields? 8620 return IntRange::forValueOfType(C, GetExprType(E)); 8621 8622 // Simple assignments just pass through the RHS, which will have 8623 // been coerced to the LHS type. 8624 case BO_Assign: 8625 // TODO: bitfields? 8626 return GetExprRange(C, BO->getRHS(), MaxWidth); 8627 8628 // Operations with opaque sources are black-listed. 8629 case BO_PtrMemD: 8630 case BO_PtrMemI: 8631 return IntRange::forValueOfType(C, GetExprType(E)); 8632 8633 // Bitwise-and uses the *infinum* of the two source ranges. 8634 case BO_And: 8635 case BO_AndAssign: 8636 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8637 GetExprRange(C, BO->getRHS(), MaxWidth)); 8638 8639 // Left shift gets black-listed based on a judgement call. 8640 case BO_Shl: 8641 // ...except that we want to treat '1 << (blah)' as logically 8642 // positive. It's an important idiom. 8643 if (IntegerLiteral *I 8644 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8645 if (I->getValue() == 1) { 8646 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8647 return IntRange(R.Width, /*NonNegative*/ true); 8648 } 8649 } 8650 LLVM_FALLTHROUGH; 8651 8652 case BO_ShlAssign: 8653 return IntRange::forValueOfType(C, GetExprType(E)); 8654 8655 // Right shift by a constant can narrow its left argument. 8656 case BO_Shr: 8657 case BO_ShrAssign: { 8658 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8659 8660 // If the shift amount is a positive constant, drop the width by 8661 // that much. 8662 llvm::APSInt shift; 8663 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8664 shift.isNonNegative()) { 8665 unsigned zext = shift.getZExtValue(); 8666 if (zext >= L.Width) 8667 L.Width = (L.NonNegative ? 0 : 1); 8668 else 8669 L.Width -= zext; 8670 } 8671 8672 return L; 8673 } 8674 8675 // Comma acts as its right operand. 8676 case BO_Comma: 8677 return GetExprRange(C, BO->getRHS(), MaxWidth); 8678 8679 // Black-list pointer subtractions. 8680 case BO_Sub: 8681 if (BO->getLHS()->getType()->isPointerType()) 8682 return IntRange::forValueOfType(C, GetExprType(E)); 8683 break; 8684 8685 // The width of a division result is mostly determined by the size 8686 // of the LHS. 8687 case BO_Div: { 8688 // Don't 'pre-truncate' the operands. 8689 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8690 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8691 8692 // If the divisor is constant, use that. 8693 llvm::APSInt divisor; 8694 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8695 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8696 if (log2 >= L.Width) 8697 L.Width = (L.NonNegative ? 0 : 1); 8698 else 8699 L.Width = std::min(L.Width - log2, MaxWidth); 8700 return L; 8701 } 8702 8703 // Otherwise, just use the LHS's width. 8704 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8705 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8706 } 8707 8708 // The result of a remainder can't be larger than the result of 8709 // either side. 8710 case BO_Rem: { 8711 // Don't 'pre-truncate' the operands. 8712 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8713 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8714 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8715 8716 IntRange meet = IntRange::meet(L, R); 8717 meet.Width = std::min(meet.Width, MaxWidth); 8718 return meet; 8719 } 8720 8721 // The default behavior is okay for these. 8722 case BO_Mul: 8723 case BO_Add: 8724 case BO_Xor: 8725 case BO_Or: 8726 break; 8727 } 8728 8729 // The default case is to treat the operation as if it were closed 8730 // on the narrowest type that encompasses both operands. 8731 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8732 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8733 return IntRange::join(L, R); 8734 } 8735 8736 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8737 switch (UO->getOpcode()) { 8738 // Boolean-valued operations are white-listed. 8739 case UO_LNot: 8740 return IntRange::forBoolType(); 8741 8742 // Operations with opaque sources are black-listed. 8743 case UO_Deref: 8744 case UO_AddrOf: // should be impossible 8745 return IntRange::forValueOfType(C, GetExprType(E)); 8746 8747 default: 8748 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8749 } 8750 } 8751 8752 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8753 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8754 8755 if (const auto *BitField = E->getSourceBitField()) 8756 return IntRange(BitField->getBitWidthValue(C), 8757 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8758 8759 return IntRange::forValueOfType(C, GetExprType(E)); 8760 } 8761 8762 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 8763 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8764 } 8765 8766 /// Checks whether the given value, which currently has the given 8767 /// source semantics, has the same value when coerced through the 8768 /// target semantics. 8769 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 8770 const llvm::fltSemantics &Src, 8771 const llvm::fltSemantics &Tgt) { 8772 llvm::APFloat truncated = value; 8773 8774 bool ignored; 8775 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8776 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8777 8778 return truncated.bitwiseIsEqual(value); 8779 } 8780 8781 /// Checks whether the given value, which currently has the given 8782 /// source semantics, has the same value when coerced through the 8783 /// target semantics. 8784 /// 8785 /// The value might be a vector of floats (or a complex number). 8786 static bool IsSameFloatAfterCast(const APValue &value, 8787 const llvm::fltSemantics &Src, 8788 const llvm::fltSemantics &Tgt) { 8789 if (value.isFloat()) 8790 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8791 8792 if (value.isVector()) { 8793 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8794 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8795 return false; 8796 return true; 8797 } 8798 8799 assert(value.isComplexFloat()); 8800 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8801 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8802 } 8803 8804 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8805 8806 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 8807 // Suppress cases where we are comparing against an enum constant. 8808 if (const DeclRefExpr *DR = 8809 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8810 if (isa<EnumConstantDecl>(DR->getDecl())) 8811 return true; 8812 8813 // Suppress cases where the '0' value is expanded from a macro. 8814 if (E->getLocStart().isMacroID()) 8815 return true; 8816 8817 return false; 8818 } 8819 8820 static bool isKnownToHaveUnsignedValue(Expr *E) { 8821 return E->getType()->isIntegerType() && 8822 (!E->getType()->isSignedIntegerType() || 8823 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 8824 } 8825 8826 namespace { 8827 /// The promoted range of values of a type. In general this has the 8828 /// following structure: 8829 /// 8830 /// |-----------| . . . |-----------| 8831 /// ^ ^ ^ ^ 8832 /// Min HoleMin HoleMax Max 8833 /// 8834 /// ... where there is only a hole if a signed type is promoted to unsigned 8835 /// (in which case Min and Max are the smallest and largest representable 8836 /// values). 8837 struct PromotedRange { 8838 // Min, or HoleMax if there is a hole. 8839 llvm::APSInt PromotedMin; 8840 // Max, or HoleMin if there is a hole. 8841 llvm::APSInt PromotedMax; 8842 8843 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 8844 if (R.Width == 0) 8845 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 8846 else if (R.Width >= BitWidth && !Unsigned) { 8847 // Promotion made the type *narrower*. This happens when promoting 8848 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 8849 // Treat all values of 'signed int' as being in range for now. 8850 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 8851 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 8852 } else { 8853 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 8854 .extOrTrunc(BitWidth); 8855 PromotedMin.setIsUnsigned(Unsigned); 8856 8857 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 8858 .extOrTrunc(BitWidth); 8859 PromotedMax.setIsUnsigned(Unsigned); 8860 } 8861 } 8862 8863 // Determine whether this range is contiguous (has no hole). 8864 bool isContiguous() const { return PromotedMin <= PromotedMax; } 8865 8866 // Where a constant value is within the range. 8867 enum ComparisonResult { 8868 LT = 0x1, 8869 LE = 0x2, 8870 GT = 0x4, 8871 GE = 0x8, 8872 EQ = 0x10, 8873 NE = 0x20, 8874 InRangeFlag = 0x40, 8875 8876 Less = LE | LT | NE, 8877 Min = LE | InRangeFlag, 8878 InRange = InRangeFlag, 8879 Max = GE | InRangeFlag, 8880 Greater = GE | GT | NE, 8881 8882 OnlyValue = LE | GE | EQ | InRangeFlag, 8883 InHole = NE 8884 }; 8885 8886 ComparisonResult compare(const llvm::APSInt &Value) const { 8887 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 8888 Value.isUnsigned() == PromotedMin.isUnsigned()); 8889 if (!isContiguous()) { 8890 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 8891 if (Value.isMinValue()) return Min; 8892 if (Value.isMaxValue()) return Max; 8893 if (Value >= PromotedMin) return InRange; 8894 if (Value <= PromotedMax) return InRange; 8895 return InHole; 8896 } 8897 8898 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 8899 case -1: return Less; 8900 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 8901 case 1: 8902 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 8903 case -1: return InRange; 8904 case 0: return Max; 8905 case 1: return Greater; 8906 } 8907 } 8908 8909 llvm_unreachable("impossible compare result"); 8910 } 8911 8912 static llvm::Optional<StringRef> 8913 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 8914 if (Op == BO_Cmp) { 8915 ComparisonResult LTFlag = LT, GTFlag = GT; 8916 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 8917 8918 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 8919 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 8920 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 8921 return llvm::None; 8922 } 8923 8924 ComparisonResult TrueFlag, FalseFlag; 8925 if (Op == BO_EQ) { 8926 TrueFlag = EQ; 8927 FalseFlag = NE; 8928 } else if (Op == BO_NE) { 8929 TrueFlag = NE; 8930 FalseFlag = EQ; 8931 } else { 8932 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 8933 TrueFlag = LT; 8934 FalseFlag = GE; 8935 } else { 8936 TrueFlag = GT; 8937 FalseFlag = LE; 8938 } 8939 if (Op == BO_GE || Op == BO_LE) 8940 std::swap(TrueFlag, FalseFlag); 8941 } 8942 if (R & TrueFlag) 8943 return StringRef("true"); 8944 if (R & FalseFlag) 8945 return StringRef("false"); 8946 return llvm::None; 8947 } 8948 }; 8949 } 8950 8951 static bool HasEnumType(Expr *E) { 8952 // Strip off implicit integral promotions. 8953 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8954 if (ICE->getCastKind() != CK_IntegralCast && 8955 ICE->getCastKind() != CK_NoOp) 8956 break; 8957 E = ICE->getSubExpr(); 8958 } 8959 8960 return E->getType()->isEnumeralType(); 8961 } 8962 8963 static int classifyConstantValue(Expr *Constant) { 8964 // The values of this enumeration are used in the diagnostics 8965 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 8966 enum ConstantValueKind { 8967 Miscellaneous = 0, 8968 LiteralTrue, 8969 LiteralFalse 8970 }; 8971 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 8972 return BL->getValue() ? ConstantValueKind::LiteralTrue 8973 : ConstantValueKind::LiteralFalse; 8974 return ConstantValueKind::Miscellaneous; 8975 } 8976 8977 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 8978 Expr *Constant, Expr *Other, 8979 const llvm::APSInt &Value, 8980 bool RhsConstant) { 8981 if (S.inTemplateInstantiation()) 8982 return false; 8983 8984 Expr *OriginalOther = Other; 8985 8986 Constant = Constant->IgnoreParenImpCasts(); 8987 Other = Other->IgnoreParenImpCasts(); 8988 8989 // Suppress warnings on tautological comparisons between values of the same 8990 // enumeration type. There are only two ways we could warn on this: 8991 // - If the constant is outside the range of representable values of 8992 // the enumeration. In such a case, we should warn about the cast 8993 // to enumeration type, not about the comparison. 8994 // - If the constant is the maximum / minimum in-range value. For an 8995 // enumeratin type, such comparisons can be meaningful and useful. 8996 if (Constant->getType()->isEnumeralType() && 8997 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 8998 return false; 8999 9000 // TODO: Investigate using GetExprRange() to get tighter bounds 9001 // on the bit ranges. 9002 QualType OtherT = Other->getType(); 9003 if (const auto *AT = OtherT->getAs<AtomicType>()) 9004 OtherT = AT->getValueType(); 9005 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 9006 9007 // Whether we're treating Other as being a bool because of the form of 9008 // expression despite it having another type (typically 'int' in C). 9009 bool OtherIsBooleanDespiteType = 9010 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 9011 if (OtherIsBooleanDespiteType) 9012 OtherRange = IntRange::forBoolType(); 9013 9014 // Determine the promoted range of the other type and see if a comparison of 9015 // the constant against that range is tautological. 9016 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 9017 Value.isUnsigned()); 9018 auto Cmp = OtherPromotedRange.compare(Value); 9019 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 9020 if (!Result) 9021 return false; 9022 9023 // Suppress the diagnostic for an in-range comparison if the constant comes 9024 // from a macro or enumerator. We don't want to diagnose 9025 // 9026 // some_long_value <= INT_MAX 9027 // 9028 // when sizeof(int) == sizeof(long). 9029 bool InRange = Cmp & PromotedRange::InRangeFlag; 9030 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 9031 return false; 9032 9033 // If this is a comparison to an enum constant, include that 9034 // constant in the diagnostic. 9035 const EnumConstantDecl *ED = nullptr; 9036 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 9037 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 9038 9039 // Should be enough for uint128 (39 decimal digits) 9040 SmallString<64> PrettySourceValue; 9041 llvm::raw_svector_ostream OS(PrettySourceValue); 9042 if (ED) 9043 OS << '\'' << *ED << "' (" << Value << ")"; 9044 else 9045 OS << Value; 9046 9047 // FIXME: We use a somewhat different formatting for the in-range cases and 9048 // cases involving boolean values for historical reasons. We should pick a 9049 // consistent way of presenting these diagnostics. 9050 if (!InRange || Other->isKnownToHaveBooleanValue()) { 9051 S.DiagRuntimeBehavior( 9052 E->getOperatorLoc(), E, 9053 S.PDiag(!InRange ? diag::warn_out_of_range_compare 9054 : diag::warn_tautological_bool_compare) 9055 << OS.str() << classifyConstantValue(Constant) 9056 << OtherT << OtherIsBooleanDespiteType << *Result 9057 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 9058 } else { 9059 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 9060 ? (HasEnumType(OriginalOther) 9061 ? diag::warn_unsigned_enum_always_true_comparison 9062 : diag::warn_unsigned_always_true_comparison) 9063 : diag::warn_tautological_constant_compare; 9064 9065 S.Diag(E->getOperatorLoc(), Diag) 9066 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 9067 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 9068 } 9069 9070 return true; 9071 } 9072 9073 /// Analyze the operands of the given comparison. Implements the 9074 /// fallback case from AnalyzeComparison. 9075 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 9076 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9077 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9078 } 9079 9080 /// \brief Implements -Wsign-compare. 9081 /// 9082 /// \param E the binary operator to check for warnings 9083 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 9084 // The type the comparison is being performed in. 9085 QualType T = E->getLHS()->getType(); 9086 9087 // Only analyze comparison operators where both sides have been converted to 9088 // the same type. 9089 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 9090 return AnalyzeImpConvsInComparison(S, E); 9091 9092 // Don't analyze value-dependent comparisons directly. 9093 if (E->isValueDependent()) 9094 return AnalyzeImpConvsInComparison(S, E); 9095 9096 Expr *LHS = E->getLHS(); 9097 Expr *RHS = E->getRHS(); 9098 9099 if (T->isIntegralType(S.Context)) { 9100 llvm::APSInt RHSValue; 9101 llvm::APSInt LHSValue; 9102 9103 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 9104 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 9105 9106 // We don't care about expressions whose result is a constant. 9107 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 9108 return AnalyzeImpConvsInComparison(S, E); 9109 9110 // We only care about expressions where just one side is literal 9111 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 9112 // Is the constant on the RHS or LHS? 9113 const bool RhsConstant = IsRHSIntegralLiteral; 9114 Expr *Const = RhsConstant ? RHS : LHS; 9115 Expr *Other = RhsConstant ? LHS : RHS; 9116 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 9117 9118 // Check whether an integer constant comparison results in a value 9119 // of 'true' or 'false'. 9120 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 9121 return AnalyzeImpConvsInComparison(S, E); 9122 } 9123 } 9124 9125 if (!T->hasUnsignedIntegerRepresentation()) { 9126 // We don't do anything special if this isn't an unsigned integral 9127 // comparison: we're only interested in integral comparisons, and 9128 // signed comparisons only happen in cases we don't care to warn about. 9129 return AnalyzeImpConvsInComparison(S, E); 9130 } 9131 9132 LHS = LHS->IgnoreParenImpCasts(); 9133 RHS = RHS->IgnoreParenImpCasts(); 9134 9135 if (!S.getLangOpts().CPlusPlus) { 9136 // Avoid warning about comparison of integers with different signs when 9137 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 9138 // the type of `E`. 9139 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 9140 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 9141 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 9142 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 9143 } 9144 9145 // Check to see if one of the (unmodified) operands is of different 9146 // signedness. 9147 Expr *signedOperand, *unsignedOperand; 9148 if (LHS->getType()->hasSignedIntegerRepresentation()) { 9149 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 9150 "unsigned comparison between two signed integer expressions?"); 9151 signedOperand = LHS; 9152 unsignedOperand = RHS; 9153 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 9154 signedOperand = RHS; 9155 unsignedOperand = LHS; 9156 } else { 9157 return AnalyzeImpConvsInComparison(S, E); 9158 } 9159 9160 // Otherwise, calculate the effective range of the signed operand. 9161 IntRange signedRange = GetExprRange(S.Context, signedOperand); 9162 9163 // Go ahead and analyze implicit conversions in the operands. Note 9164 // that we skip the implicit conversions on both sides. 9165 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 9166 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 9167 9168 // If the signed range is non-negative, -Wsign-compare won't fire. 9169 if (signedRange.NonNegative) 9170 return; 9171 9172 // For (in)equality comparisons, if the unsigned operand is a 9173 // constant which cannot collide with a overflowed signed operand, 9174 // then reinterpreting the signed operand as unsigned will not 9175 // change the result of the comparison. 9176 if (E->isEqualityOp()) { 9177 unsigned comparisonWidth = S.Context.getIntWidth(T); 9178 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 9179 9180 // We should never be unable to prove that the unsigned operand is 9181 // non-negative. 9182 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 9183 9184 if (unsignedRange.Width < comparisonWidth) 9185 return; 9186 } 9187 9188 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 9189 S.PDiag(diag::warn_mixed_sign_comparison) 9190 << LHS->getType() << RHS->getType() 9191 << LHS->getSourceRange() << RHS->getSourceRange()); 9192 } 9193 9194 /// Analyzes an attempt to assign the given value to a bitfield. 9195 /// 9196 /// Returns true if there was something fishy about the attempt. 9197 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 9198 SourceLocation InitLoc) { 9199 assert(Bitfield->isBitField()); 9200 if (Bitfield->isInvalidDecl()) 9201 return false; 9202 9203 // White-list bool bitfields. 9204 QualType BitfieldType = Bitfield->getType(); 9205 if (BitfieldType->isBooleanType()) 9206 return false; 9207 9208 if (BitfieldType->isEnumeralType()) { 9209 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 9210 // If the underlying enum type was not explicitly specified as an unsigned 9211 // type and the enum contain only positive values, MSVC++ will cause an 9212 // inconsistency by storing this as a signed type. 9213 if (S.getLangOpts().CPlusPlus11 && 9214 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 9215 BitfieldEnumDecl->getNumPositiveBits() > 0 && 9216 BitfieldEnumDecl->getNumNegativeBits() == 0) { 9217 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 9218 << BitfieldEnumDecl->getNameAsString(); 9219 } 9220 } 9221 9222 if (Bitfield->getType()->isBooleanType()) 9223 return false; 9224 9225 // Ignore value- or type-dependent expressions. 9226 if (Bitfield->getBitWidth()->isValueDependent() || 9227 Bitfield->getBitWidth()->isTypeDependent() || 9228 Init->isValueDependent() || 9229 Init->isTypeDependent()) 9230 return false; 9231 9232 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 9233 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 9234 9235 llvm::APSInt Value; 9236 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 9237 Expr::SE_AllowSideEffects)) { 9238 // The RHS is not constant. If the RHS has an enum type, make sure the 9239 // bitfield is wide enough to hold all the values of the enum without 9240 // truncation. 9241 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 9242 EnumDecl *ED = EnumTy->getDecl(); 9243 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 9244 9245 // Enum types are implicitly signed on Windows, so check if there are any 9246 // negative enumerators to see if the enum was intended to be signed or 9247 // not. 9248 bool SignedEnum = ED->getNumNegativeBits() > 0; 9249 9250 // Check for surprising sign changes when assigning enum values to a 9251 // bitfield of different signedness. If the bitfield is signed and we 9252 // have exactly the right number of bits to store this unsigned enum, 9253 // suggest changing the enum to an unsigned type. This typically happens 9254 // on Windows where unfixed enums always use an underlying type of 'int'. 9255 unsigned DiagID = 0; 9256 if (SignedEnum && !SignedBitfield) { 9257 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 9258 } else if (SignedBitfield && !SignedEnum && 9259 ED->getNumPositiveBits() == FieldWidth) { 9260 DiagID = diag::warn_signed_bitfield_enum_conversion; 9261 } 9262 9263 if (DiagID) { 9264 S.Diag(InitLoc, DiagID) << Bitfield << ED; 9265 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 9266 SourceRange TypeRange = 9267 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 9268 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 9269 << SignedEnum << TypeRange; 9270 } 9271 9272 // Compute the required bitwidth. If the enum has negative values, we need 9273 // one more bit than the normal number of positive bits to represent the 9274 // sign bit. 9275 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 9276 ED->getNumNegativeBits()) 9277 : ED->getNumPositiveBits(); 9278 9279 // Check the bitwidth. 9280 if (BitsNeeded > FieldWidth) { 9281 Expr *WidthExpr = Bitfield->getBitWidth(); 9282 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 9283 << Bitfield << ED; 9284 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 9285 << BitsNeeded << ED << WidthExpr->getSourceRange(); 9286 } 9287 } 9288 9289 return false; 9290 } 9291 9292 unsigned OriginalWidth = Value.getBitWidth(); 9293 9294 if (!Value.isSigned() || Value.isNegative()) 9295 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 9296 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 9297 OriginalWidth = Value.getMinSignedBits(); 9298 9299 if (OriginalWidth <= FieldWidth) 9300 return false; 9301 9302 // Compute the value which the bitfield will contain. 9303 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 9304 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 9305 9306 // Check whether the stored value is equal to the original value. 9307 TruncatedValue = TruncatedValue.extend(OriginalWidth); 9308 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 9309 return false; 9310 9311 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9312 // therefore don't strictly fit into a signed bitfield of width 1. 9313 if (FieldWidth == 1 && Value == 1) 9314 return false; 9315 9316 std::string PrettyValue = Value.toString(10); 9317 std::string PrettyTrunc = TruncatedValue.toString(10); 9318 9319 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9320 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9321 << Init->getSourceRange(); 9322 9323 return true; 9324 } 9325 9326 /// Analyze the given simple or compound assignment for warning-worthy 9327 /// operations. 9328 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9329 // Just recurse on the LHS. 9330 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9331 9332 // We want to recurse on the RHS as normal unless we're assigning to 9333 // a bitfield. 9334 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9335 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9336 E->getOperatorLoc())) { 9337 // Recurse, ignoring any implicit conversions on the RHS. 9338 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9339 E->getOperatorLoc()); 9340 } 9341 } 9342 9343 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9344 } 9345 9346 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9347 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9348 SourceLocation CContext, unsigned diag, 9349 bool pruneControlFlow = false) { 9350 if (pruneControlFlow) { 9351 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9352 S.PDiag(diag) 9353 << SourceType << T << E->getSourceRange() 9354 << SourceRange(CContext)); 9355 return; 9356 } 9357 S.Diag(E->getExprLoc(), diag) 9358 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9359 } 9360 9361 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9362 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 9363 SourceLocation CContext, 9364 unsigned diag, bool pruneControlFlow = false) { 9365 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9366 } 9367 9368 /// Analyze the given compound assignment for the possible losing of 9369 /// floating-point precision. 9370 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 9371 assert(isa<CompoundAssignOperator>(E) && 9372 "Must be compound assignment operation"); 9373 // Recurse on the LHS and RHS in here 9374 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9375 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9376 9377 // Now check the outermost expression 9378 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 9379 const auto *RBT = cast<CompoundAssignOperator>(E) 9380 ->getComputationResultType() 9381 ->getAs<BuiltinType>(); 9382 9383 // If both source and target are floating points. 9384 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint()) 9385 // Builtin FP kinds are ordered by increasing FP rank. 9386 if (ResultBT->getKind() < RBT->getKind()) 9387 // We don't want to warn for system macro. 9388 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 9389 // warn about dropping FP rank. 9390 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), 9391 E->getOperatorLoc(), 9392 diag::warn_impcast_float_result_precision); 9393 } 9394 9395 /// Diagnose an implicit cast from a floating point value to an integer value. 9396 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9397 SourceLocation CContext) { 9398 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9399 const bool PruneWarnings = S.inTemplateInstantiation(); 9400 9401 Expr *InnerE = E->IgnoreParenImpCasts(); 9402 // We also want to warn on, e.g., "int i = -1.234" 9403 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9404 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9405 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9406 9407 const bool IsLiteral = 9408 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9409 9410 llvm::APFloat Value(0.0); 9411 bool IsConstant = 9412 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9413 if (!IsConstant) { 9414 return DiagnoseImpCast(S, E, T, CContext, 9415 diag::warn_impcast_float_integer, PruneWarnings); 9416 } 9417 9418 bool isExact = false; 9419 9420 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9421 T->hasUnsignedIntegerRepresentation()); 9422 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 9423 &isExact) == llvm::APFloat::opOK && 9424 isExact) { 9425 if (IsLiteral) return; 9426 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9427 PruneWarnings); 9428 } 9429 9430 unsigned DiagID = 0; 9431 if (IsLiteral) { 9432 // Conversion of a floating-point value to a non-bool integer where the 9433 // integral part cannot be represented by the integer type is undefined. 9434 if (!IsBool && 9435 ((IntegerValue.isSigned() && (IntegerValue.isMaxSignedValue() || 9436 IntegerValue.isMinSignedValue())) || 9437 (IntegerValue.isUnsigned() && 9438 (IntegerValue.isMaxValue() || IntegerValue.isMinValue())))) 9439 return DiagnoseImpCast( 9440 S, E, T, CContext, 9441 diag::warn_impcast_literal_float_to_integer_out_of_range); 9442 // Warn on floating point literal to integer. 9443 DiagID = diag::warn_impcast_literal_float_to_integer; 9444 } else if (IntegerValue == 0) { 9445 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9446 return DiagnoseImpCast(S, E, T, CContext, 9447 diag::warn_impcast_float_integer, PruneWarnings); 9448 } 9449 // Warn on non-zero to zero conversion. 9450 DiagID = diag::warn_impcast_float_to_integer_zero; 9451 } else { 9452 if (IntegerValue.isUnsigned()) { 9453 if (!IntegerValue.isMaxValue()) { 9454 return DiagnoseImpCast(S, E, T, CContext, 9455 diag::warn_impcast_float_integer, PruneWarnings); 9456 } 9457 if (!IsBool && (IntegerValue.isMaxValue() || IntegerValue.isMinValue())) 9458 return DiagnoseImpCast(S, E, T, CContext, 9459 diag::warn_impcast_float_to_integer_out_of_range, 9460 PruneWarnings); 9461 } else { // IntegerValue.isSigned() 9462 if (!IntegerValue.isMaxSignedValue() && 9463 !IntegerValue.isMinSignedValue()) { 9464 return DiagnoseImpCast(S, E, T, CContext, 9465 diag::warn_impcast_float_integer, PruneWarnings); 9466 } 9467 return DiagnoseImpCast(S, E, T, CContext, 9468 diag::warn_impcast_float_to_integer_out_of_range, 9469 PruneWarnings); 9470 } 9471 // Warn on evaluatable floating point expression to integer conversion. 9472 DiagID = diag::warn_impcast_float_to_integer; 9473 } 9474 9475 // FIXME: Force the precision of the source value down so we don't print 9476 // digits which are usually useless (we don't really care here if we 9477 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9478 // would automatically print the shortest representation, but it's a bit 9479 // tricky to implement. 9480 SmallString<16> PrettySourceValue; 9481 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9482 precision = (precision * 59 + 195) / 196; 9483 Value.toString(PrettySourceValue, precision); 9484 9485 SmallString<16> PrettyTargetValue; 9486 if (IsBool) 9487 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9488 else 9489 IntegerValue.toString(PrettyTargetValue); 9490 9491 if (PruneWarnings) { 9492 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9493 S.PDiag(DiagID) 9494 << E->getType() << T.getUnqualifiedType() 9495 << PrettySourceValue << PrettyTargetValue 9496 << E->getSourceRange() << SourceRange(CContext)); 9497 } else { 9498 S.Diag(E->getExprLoc(), DiagID) 9499 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9500 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9501 } 9502 } 9503 9504 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 9505 IntRange Range) { 9506 if (!Range.Width) return "0"; 9507 9508 llvm::APSInt ValueInRange = Value; 9509 ValueInRange.setIsSigned(!Range.NonNegative); 9510 ValueInRange = ValueInRange.trunc(Range.Width); 9511 return ValueInRange.toString(10); 9512 } 9513 9514 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9515 if (!isa<ImplicitCastExpr>(Ex)) 9516 return false; 9517 9518 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9519 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9520 const Type *Source = 9521 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9522 if (Target->isDependentType()) 9523 return false; 9524 9525 const BuiltinType *FloatCandidateBT = 9526 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9527 const Type *BoolCandidateType = ToBool ? Target : Source; 9528 9529 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9530 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9531 } 9532 9533 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9534 SourceLocation CC) { 9535 unsigned NumArgs = TheCall->getNumArgs(); 9536 for (unsigned i = 0; i < NumArgs; ++i) { 9537 Expr *CurrA = TheCall->getArg(i); 9538 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9539 continue; 9540 9541 bool IsSwapped = ((i > 0) && 9542 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9543 IsSwapped |= ((i < (NumArgs - 1)) && 9544 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9545 if (IsSwapped) { 9546 // Warn on this floating-point to bool conversion. 9547 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9548 CurrA->getType(), CC, 9549 diag::warn_impcast_floating_point_to_bool); 9550 } 9551 } 9552 } 9553 9554 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 9555 SourceLocation CC) { 9556 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9557 E->getExprLoc())) 9558 return; 9559 9560 // Don't warn on functions which have return type nullptr_t. 9561 if (isa<CallExpr>(E)) 9562 return; 9563 9564 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9565 const Expr::NullPointerConstantKind NullKind = 9566 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9567 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9568 return; 9569 9570 // Return if target type is a safe conversion. 9571 if (T->isAnyPointerType() || T->isBlockPointerType() || 9572 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9573 return; 9574 9575 SourceLocation Loc = E->getSourceRange().getBegin(); 9576 9577 // Venture through the macro stacks to get to the source of macro arguments. 9578 // The new location is a better location than the complete location that was 9579 // passed in. 9580 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 9581 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 9582 9583 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9584 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9585 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9586 Loc, S.SourceMgr, S.getLangOpts()); 9587 if (MacroName == "NULL") 9588 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 9589 } 9590 9591 // Only warn if the null and context location are in the same macro expansion. 9592 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9593 return; 9594 9595 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9596 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 9597 << FixItHint::CreateReplacement(Loc, 9598 S.getFixItZeroLiteralForType(T, Loc)); 9599 } 9600 9601 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9602 ObjCArrayLiteral *ArrayLiteral); 9603 9604 static void 9605 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9606 ObjCDictionaryLiteral *DictionaryLiteral); 9607 9608 /// Check a single element within a collection literal against the 9609 /// target element type. 9610 static void checkObjCCollectionLiteralElement(Sema &S, 9611 QualType TargetElementType, 9612 Expr *Element, 9613 unsigned ElementKind) { 9614 // Skip a bitcast to 'id' or qualified 'id'. 9615 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9616 if (ICE->getCastKind() == CK_BitCast && 9617 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9618 Element = ICE->getSubExpr(); 9619 } 9620 9621 QualType ElementType = Element->getType(); 9622 ExprResult ElementResult(Element); 9623 if (ElementType->getAs<ObjCObjectPointerType>() && 9624 S.CheckSingleAssignmentConstraints(TargetElementType, 9625 ElementResult, 9626 false, false) 9627 != Sema::Compatible) { 9628 S.Diag(Element->getLocStart(), 9629 diag::warn_objc_collection_literal_element) 9630 << ElementType << ElementKind << TargetElementType 9631 << Element->getSourceRange(); 9632 } 9633 9634 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9635 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9636 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9637 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9638 } 9639 9640 /// Check an Objective-C array literal being converted to the given 9641 /// target type. 9642 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9643 ObjCArrayLiteral *ArrayLiteral) { 9644 if (!S.NSArrayDecl) 9645 return; 9646 9647 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9648 if (!TargetObjCPtr) 9649 return; 9650 9651 if (TargetObjCPtr->isUnspecialized() || 9652 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9653 != S.NSArrayDecl->getCanonicalDecl()) 9654 return; 9655 9656 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9657 if (TypeArgs.size() != 1) 9658 return; 9659 9660 QualType TargetElementType = TypeArgs[0]; 9661 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9662 checkObjCCollectionLiteralElement(S, TargetElementType, 9663 ArrayLiteral->getElement(I), 9664 0); 9665 } 9666 } 9667 9668 /// Check an Objective-C dictionary literal being converted to the given 9669 /// target type. 9670 static void 9671 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9672 ObjCDictionaryLiteral *DictionaryLiteral) { 9673 if (!S.NSDictionaryDecl) 9674 return; 9675 9676 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9677 if (!TargetObjCPtr) 9678 return; 9679 9680 if (TargetObjCPtr->isUnspecialized() || 9681 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9682 != S.NSDictionaryDecl->getCanonicalDecl()) 9683 return; 9684 9685 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9686 if (TypeArgs.size() != 2) 9687 return; 9688 9689 QualType TargetKeyType = TypeArgs[0]; 9690 QualType TargetObjectType = TypeArgs[1]; 9691 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9692 auto Element = DictionaryLiteral->getKeyValueElement(I); 9693 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9694 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9695 } 9696 } 9697 9698 // Helper function to filter out cases for constant width constant conversion. 9699 // Don't warn on char array initialization or for non-decimal values. 9700 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9701 SourceLocation CC) { 9702 // If initializing from a constant, and the constant starts with '0', 9703 // then it is a binary, octal, or hexadecimal. Allow these constants 9704 // to fill all the bits, even if there is a sign change. 9705 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9706 const char FirstLiteralCharacter = 9707 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9708 if (FirstLiteralCharacter == '0') 9709 return false; 9710 } 9711 9712 // If the CC location points to a '{', and the type is char, then assume 9713 // assume it is an array initialization. 9714 if (CC.isValid() && T->isCharType()) { 9715 const char FirstContextCharacter = 9716 S.getSourceManager().getCharacterData(CC)[0]; 9717 if (FirstContextCharacter == '{') 9718 return false; 9719 } 9720 9721 return true; 9722 } 9723 9724 static void 9725 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 9726 bool *ICContext = nullptr) { 9727 if (E->isTypeDependent() || E->isValueDependent()) return; 9728 9729 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9730 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9731 if (Source == Target) return; 9732 if (Target->isDependentType()) return; 9733 9734 // If the conversion context location is invalid don't complain. We also 9735 // don't want to emit a warning if the issue occurs from the expansion of 9736 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9737 // delay this check as long as possible. Once we detect we are in that 9738 // scenario, we just return. 9739 if (CC.isInvalid()) 9740 return; 9741 9742 // Diagnose implicit casts to bool. 9743 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9744 if (isa<StringLiteral>(E)) 9745 // Warn on string literal to bool. Checks for string literals in logical 9746 // and expressions, for instance, assert(0 && "error here"), are 9747 // prevented by a check in AnalyzeImplicitConversions(). 9748 return DiagnoseImpCast(S, E, T, CC, 9749 diag::warn_impcast_string_literal_to_bool); 9750 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9751 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9752 // This covers the literal expressions that evaluate to Objective-C 9753 // objects. 9754 return DiagnoseImpCast(S, E, T, CC, 9755 diag::warn_impcast_objective_c_literal_to_bool); 9756 } 9757 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9758 // Warn on pointer to bool conversion that is always true. 9759 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9760 SourceRange(CC)); 9761 } 9762 } 9763 9764 // Check implicit casts from Objective-C collection literals to specialized 9765 // collection types, e.g., NSArray<NSString *> *. 9766 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9767 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9768 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9769 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9770 9771 // Strip vector types. 9772 if (isa<VectorType>(Source)) { 9773 if (!isa<VectorType>(Target)) { 9774 if (S.SourceMgr.isInSystemMacro(CC)) 9775 return; 9776 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9777 } 9778 9779 // If the vector cast is cast between two vectors of the same size, it is 9780 // a bitcast, not a conversion. 9781 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9782 return; 9783 9784 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9785 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9786 } 9787 if (auto VecTy = dyn_cast<VectorType>(Target)) 9788 Target = VecTy->getElementType().getTypePtr(); 9789 9790 // Strip complex types. 9791 if (isa<ComplexType>(Source)) { 9792 if (!isa<ComplexType>(Target)) { 9793 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 9794 return; 9795 9796 return DiagnoseImpCast(S, E, T, CC, 9797 S.getLangOpts().CPlusPlus 9798 ? diag::err_impcast_complex_scalar 9799 : diag::warn_impcast_complex_scalar); 9800 } 9801 9802 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9803 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9804 } 9805 9806 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9807 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9808 9809 // If the source is floating point... 9810 if (SourceBT && SourceBT->isFloatingPoint()) { 9811 // ...and the target is floating point... 9812 if (TargetBT && TargetBT->isFloatingPoint()) { 9813 // ...then warn if we're dropping FP rank. 9814 9815 // Builtin FP kinds are ordered by increasing FP rank. 9816 if (SourceBT->getKind() > TargetBT->getKind()) { 9817 // Don't warn about float constants that are precisely 9818 // representable in the target type. 9819 Expr::EvalResult result; 9820 if (E->EvaluateAsRValue(result, S.Context)) { 9821 // Value might be a float, a float vector, or a float complex. 9822 if (IsSameFloatAfterCast(result.Val, 9823 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9824 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9825 return; 9826 } 9827 9828 if (S.SourceMgr.isInSystemMacro(CC)) 9829 return; 9830 9831 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9832 } 9833 // ... or possibly if we're increasing rank, too 9834 else if (TargetBT->getKind() > SourceBT->getKind()) { 9835 if (S.SourceMgr.isInSystemMacro(CC)) 9836 return; 9837 9838 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9839 } 9840 return; 9841 } 9842 9843 // If the target is integral, always warn. 9844 if (TargetBT && TargetBT->isInteger()) { 9845 if (S.SourceMgr.isInSystemMacro(CC)) 9846 return; 9847 9848 DiagnoseFloatingImpCast(S, E, T, CC); 9849 } 9850 9851 // Detect the case where a call result is converted from floating-point to 9852 // to bool, and the final argument to the call is converted from bool, to 9853 // discover this typo: 9854 // 9855 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9856 // 9857 // FIXME: This is an incredibly special case; is there some more general 9858 // way to detect this class of misplaced-parentheses bug? 9859 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9860 // Check last argument of function call to see if it is an 9861 // implicit cast from a type matching the type the result 9862 // is being cast to. 9863 CallExpr *CEx = cast<CallExpr>(E); 9864 if (unsigned NumArgs = CEx->getNumArgs()) { 9865 Expr *LastA = CEx->getArg(NumArgs - 1); 9866 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9867 if (isa<ImplicitCastExpr>(LastA) && 9868 InnerE->getType()->isBooleanType()) { 9869 // Warn on this floating-point to bool conversion 9870 DiagnoseImpCast(S, E, T, CC, 9871 diag::warn_impcast_floating_point_to_bool); 9872 } 9873 } 9874 } 9875 return; 9876 } 9877 9878 DiagnoseNullConversion(S, E, T, CC); 9879 9880 S.DiscardMisalignedMemberAddress(Target, E); 9881 9882 if (!Source->isIntegerType() || !Target->isIntegerType()) 9883 return; 9884 9885 // TODO: remove this early return once the false positives for constant->bool 9886 // in templates, macros, etc, are reduced or removed. 9887 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9888 return; 9889 9890 IntRange SourceRange = GetExprRange(S.Context, E); 9891 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9892 9893 if (SourceRange.Width > TargetRange.Width) { 9894 // If the source is a constant, use a default-on diagnostic. 9895 // TODO: this should happen for bitfield stores, too. 9896 llvm::APSInt Value(32); 9897 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9898 if (S.SourceMgr.isInSystemMacro(CC)) 9899 return; 9900 9901 std::string PrettySourceValue = Value.toString(10); 9902 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9903 9904 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9905 S.PDiag(diag::warn_impcast_integer_precision_constant) 9906 << PrettySourceValue << PrettyTargetValue 9907 << E->getType() << T << E->getSourceRange() 9908 << clang::SourceRange(CC)); 9909 return; 9910 } 9911 9912 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9913 if (S.SourceMgr.isInSystemMacro(CC)) 9914 return; 9915 9916 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9917 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9918 /* pruneControlFlow */ true); 9919 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9920 } 9921 9922 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9923 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9924 // Warn when doing a signed to signed conversion, warn if the positive 9925 // source value is exactly the width of the target type, which will 9926 // cause a negative value to be stored. 9927 9928 llvm::APSInt Value; 9929 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9930 !S.SourceMgr.isInSystemMacro(CC)) { 9931 if (isSameWidthConstantConversion(S, E, T, CC)) { 9932 std::string PrettySourceValue = Value.toString(10); 9933 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9934 9935 S.DiagRuntimeBehavior( 9936 E->getExprLoc(), E, 9937 S.PDiag(diag::warn_impcast_integer_precision_constant) 9938 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9939 << E->getSourceRange() << clang::SourceRange(CC)); 9940 return; 9941 } 9942 } 9943 9944 // Fall through for non-constants to give a sign conversion warning. 9945 } 9946 9947 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9948 (!TargetRange.NonNegative && SourceRange.NonNegative && 9949 SourceRange.Width == TargetRange.Width)) { 9950 if (S.SourceMgr.isInSystemMacro(CC)) 9951 return; 9952 9953 unsigned DiagID = diag::warn_impcast_integer_sign; 9954 9955 // Traditionally, gcc has warned about this under -Wsign-compare. 9956 // We also want to warn about it in -Wconversion. 9957 // So if -Wconversion is off, use a completely identical diagnostic 9958 // in the sign-compare group. 9959 // The conditional-checking code will 9960 if (ICContext) { 9961 DiagID = diag::warn_impcast_integer_sign_conditional; 9962 *ICContext = true; 9963 } 9964 9965 return DiagnoseImpCast(S, E, T, CC, DiagID); 9966 } 9967 9968 // Diagnose conversions between different enumeration types. 9969 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9970 // type, to give us better diagnostics. 9971 QualType SourceType = E->getType(); 9972 if (!S.getLangOpts().CPlusPlus) { 9973 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9974 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9975 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9976 SourceType = S.Context.getTypeDeclType(Enum); 9977 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9978 } 9979 } 9980 9981 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9982 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9983 if (SourceEnum->getDecl()->hasNameForLinkage() && 9984 TargetEnum->getDecl()->hasNameForLinkage() && 9985 SourceEnum != TargetEnum) { 9986 if (S.SourceMgr.isInSystemMacro(CC)) 9987 return; 9988 9989 return DiagnoseImpCast(S, E, SourceType, T, CC, 9990 diag::warn_impcast_different_enum_types); 9991 } 9992 } 9993 9994 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9995 SourceLocation CC, QualType T); 9996 9997 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9998 SourceLocation CC, bool &ICContext) { 9999 E = E->IgnoreParenImpCasts(); 10000 10001 if (isa<ConditionalOperator>(E)) 10002 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 10003 10004 AnalyzeImplicitConversions(S, E, CC); 10005 if (E->getType() != T) 10006 return CheckImplicitConversion(S, E, T, CC, &ICContext); 10007 } 10008 10009 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10010 SourceLocation CC, QualType T) { 10011 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 10012 10013 bool Suspicious = false; 10014 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 10015 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 10016 10017 // If -Wconversion would have warned about either of the candidates 10018 // for a signedness conversion to the context type... 10019 if (!Suspicious) return; 10020 10021 // ...but it's currently ignored... 10022 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 10023 return; 10024 10025 // ...then check whether it would have warned about either of the 10026 // candidates for a signedness conversion to the condition type. 10027 if (E->getType() == T) return; 10028 10029 Suspicious = false; 10030 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 10031 E->getType(), CC, &Suspicious); 10032 if (!Suspicious) 10033 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 10034 E->getType(), CC, &Suspicious); 10035 } 10036 10037 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10038 /// Input argument E is a logical expression. 10039 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 10040 if (S.getLangOpts().Bool) 10041 return; 10042 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 10043 } 10044 10045 /// AnalyzeImplicitConversions - Find and report any interesting 10046 /// implicit conversions in the given expression. There are a couple 10047 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 10048 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 10049 SourceLocation CC) { 10050 QualType T = OrigE->getType(); 10051 Expr *E = OrigE->IgnoreParenImpCasts(); 10052 10053 if (E->isTypeDependent() || E->isValueDependent()) 10054 return; 10055 10056 // For conditional operators, we analyze the arguments as if they 10057 // were being fed directly into the output. 10058 if (isa<ConditionalOperator>(E)) { 10059 ConditionalOperator *CO = cast<ConditionalOperator>(E); 10060 CheckConditionalOperator(S, CO, CC, T); 10061 return; 10062 } 10063 10064 // Check implicit argument conversions for function calls. 10065 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 10066 CheckImplicitArgumentConversions(S, Call, CC); 10067 10068 // Go ahead and check any implicit conversions we might have skipped. 10069 // The non-canonical typecheck is just an optimization; 10070 // CheckImplicitConversion will filter out dead implicit conversions. 10071 if (E->getType() != T) 10072 CheckImplicitConversion(S, E, T, CC); 10073 10074 // Now continue drilling into this expression. 10075 10076 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 10077 // The bound subexpressions in a PseudoObjectExpr are not reachable 10078 // as transitive children. 10079 // FIXME: Use a more uniform representation for this. 10080 for (auto *SE : POE->semantics()) 10081 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 10082 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 10083 } 10084 10085 // Skip past explicit casts. 10086 if (isa<ExplicitCastExpr>(E)) { 10087 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 10088 return AnalyzeImplicitConversions(S, E, CC); 10089 } 10090 10091 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10092 // Do a somewhat different check with comparison operators. 10093 if (BO->isComparisonOp()) 10094 return AnalyzeComparison(S, BO); 10095 10096 // And with simple assignments. 10097 if (BO->getOpcode() == BO_Assign) 10098 return AnalyzeAssignment(S, BO); 10099 // And with compound assignments. 10100 if (BO->isAssignmentOp()) 10101 return AnalyzeCompoundAssignment(S, BO); 10102 } 10103 10104 // These break the otherwise-useful invariant below. Fortunately, 10105 // we don't really need to recurse into them, because any internal 10106 // expressions should have been analyzed already when they were 10107 // built into statements. 10108 if (isa<StmtExpr>(E)) return; 10109 10110 // Don't descend into unevaluated contexts. 10111 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 10112 10113 // Now just recurse over the expression's children. 10114 CC = E->getExprLoc(); 10115 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 10116 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 10117 for (Stmt *SubStmt : E->children()) { 10118 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 10119 if (!ChildExpr) 10120 continue; 10121 10122 if (IsLogicalAndOperator && 10123 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 10124 // Ignore checking string literals that are in logical and operators. 10125 // This is a common pattern for asserts. 10126 continue; 10127 AnalyzeImplicitConversions(S, ChildExpr, CC); 10128 } 10129 10130 if (BO && BO->isLogicalOp()) { 10131 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 10132 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 10133 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 10134 10135 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 10136 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 10137 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 10138 } 10139 10140 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 10141 if (U->getOpcode() == UO_LNot) 10142 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 10143 } 10144 10145 /// Diagnose integer type and any valid implicit conversion to it. 10146 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 10147 // Taking into account implicit conversions, 10148 // allow any integer. 10149 if (!E->getType()->isIntegerType()) { 10150 S.Diag(E->getLocStart(), 10151 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 10152 return true; 10153 } 10154 // Potentially emit standard warnings for implicit conversions if enabled 10155 // using -Wconversion. 10156 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 10157 return false; 10158 } 10159 10160 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 10161 // Returns true when emitting a warning about taking the address of a reference. 10162 static bool CheckForReference(Sema &SemaRef, const Expr *E, 10163 const PartialDiagnostic &PD) { 10164 E = E->IgnoreParenImpCasts(); 10165 10166 const FunctionDecl *FD = nullptr; 10167 10168 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10169 if (!DRE->getDecl()->getType()->isReferenceType()) 10170 return false; 10171 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10172 if (!M->getMemberDecl()->getType()->isReferenceType()) 10173 return false; 10174 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 10175 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 10176 return false; 10177 FD = Call->getDirectCallee(); 10178 } else { 10179 return false; 10180 } 10181 10182 SemaRef.Diag(E->getExprLoc(), PD); 10183 10184 // If possible, point to location of function. 10185 if (FD) { 10186 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 10187 } 10188 10189 return true; 10190 } 10191 10192 // Returns true if the SourceLocation is expanded from any macro body. 10193 // Returns false if the SourceLocation is invalid, is from not in a macro 10194 // expansion, or is from expanded from a top-level macro argument. 10195 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 10196 if (Loc.isInvalid()) 10197 return false; 10198 10199 while (Loc.isMacroID()) { 10200 if (SM.isMacroBodyExpansion(Loc)) 10201 return true; 10202 Loc = SM.getImmediateMacroCallerLoc(Loc); 10203 } 10204 10205 return false; 10206 } 10207 10208 /// \brief Diagnose pointers that are always non-null. 10209 /// \param E the expression containing the pointer 10210 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 10211 /// compared to a null pointer 10212 /// \param IsEqual True when the comparison is equal to a null pointer 10213 /// \param Range Extra SourceRange to highlight in the diagnostic 10214 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 10215 Expr::NullPointerConstantKind NullKind, 10216 bool IsEqual, SourceRange Range) { 10217 if (!E) 10218 return; 10219 10220 // Don't warn inside macros. 10221 if (E->getExprLoc().isMacroID()) { 10222 const SourceManager &SM = getSourceManager(); 10223 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 10224 IsInAnyMacroBody(SM, Range.getBegin())) 10225 return; 10226 } 10227 E = E->IgnoreImpCasts(); 10228 10229 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 10230 10231 if (isa<CXXThisExpr>(E)) { 10232 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 10233 : diag::warn_this_bool_conversion; 10234 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 10235 return; 10236 } 10237 10238 bool IsAddressOf = false; 10239 10240 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10241 if (UO->getOpcode() != UO_AddrOf) 10242 return; 10243 IsAddressOf = true; 10244 E = UO->getSubExpr(); 10245 } 10246 10247 if (IsAddressOf) { 10248 unsigned DiagID = IsCompare 10249 ? diag::warn_address_of_reference_null_compare 10250 : diag::warn_address_of_reference_bool_conversion; 10251 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 10252 << IsEqual; 10253 if (CheckForReference(*this, E, PD)) { 10254 return; 10255 } 10256 } 10257 10258 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 10259 bool IsParam = isa<NonNullAttr>(NonnullAttr); 10260 std::string Str; 10261 llvm::raw_string_ostream S(Str); 10262 E->printPretty(S, nullptr, getPrintingPolicy()); 10263 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 10264 : diag::warn_cast_nonnull_to_bool; 10265 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 10266 << E->getSourceRange() << Range << IsEqual; 10267 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 10268 }; 10269 10270 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 10271 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 10272 if (auto *Callee = Call->getDirectCallee()) { 10273 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 10274 ComplainAboutNonnullParamOrCall(A); 10275 return; 10276 } 10277 } 10278 } 10279 10280 // Expect to find a single Decl. Skip anything more complicated. 10281 ValueDecl *D = nullptr; 10282 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 10283 D = R->getDecl(); 10284 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10285 D = M->getMemberDecl(); 10286 } 10287 10288 // Weak Decls can be null. 10289 if (!D || D->isWeak()) 10290 return; 10291 10292 // Check for parameter decl with nonnull attribute 10293 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 10294 if (getCurFunction() && 10295 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 10296 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 10297 ComplainAboutNonnullParamOrCall(A); 10298 return; 10299 } 10300 10301 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 10302 auto ParamIter = llvm::find(FD->parameters(), PV); 10303 assert(ParamIter != FD->param_end()); 10304 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 10305 10306 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 10307 if (!NonNull->args_size()) { 10308 ComplainAboutNonnullParamOrCall(NonNull); 10309 return; 10310 } 10311 10312 for (const ParamIdx &ArgNo : NonNull->args()) { 10313 if (ArgNo.getASTIndex() == ParamNo) { 10314 ComplainAboutNonnullParamOrCall(NonNull); 10315 return; 10316 } 10317 } 10318 } 10319 } 10320 } 10321 } 10322 10323 QualType T = D->getType(); 10324 const bool IsArray = T->isArrayType(); 10325 const bool IsFunction = T->isFunctionType(); 10326 10327 // Address of function is used to silence the function warning. 10328 if (IsAddressOf && IsFunction) { 10329 return; 10330 } 10331 10332 // Found nothing. 10333 if (!IsAddressOf && !IsFunction && !IsArray) 10334 return; 10335 10336 // Pretty print the expression for the diagnostic. 10337 std::string Str; 10338 llvm::raw_string_ostream S(Str); 10339 E->printPretty(S, nullptr, getPrintingPolicy()); 10340 10341 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 10342 : diag::warn_impcast_pointer_to_bool; 10343 enum { 10344 AddressOf, 10345 FunctionPointer, 10346 ArrayPointer 10347 } DiagType; 10348 if (IsAddressOf) 10349 DiagType = AddressOf; 10350 else if (IsFunction) 10351 DiagType = FunctionPointer; 10352 else if (IsArray) 10353 DiagType = ArrayPointer; 10354 else 10355 llvm_unreachable("Could not determine diagnostic."); 10356 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 10357 << Range << IsEqual; 10358 10359 if (!IsFunction) 10360 return; 10361 10362 // Suggest '&' to silence the function warning. 10363 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10364 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10365 10366 // Check to see if '()' fixit should be emitted. 10367 QualType ReturnType; 10368 UnresolvedSet<4> NonTemplateOverloads; 10369 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10370 if (ReturnType.isNull()) 10371 return; 10372 10373 if (IsCompare) { 10374 // There are two cases here. If there is null constant, the only suggest 10375 // for a pointer return type. If the null is 0, then suggest if the return 10376 // type is a pointer or an integer type. 10377 if (!ReturnType->isPointerType()) { 10378 if (NullKind == Expr::NPCK_ZeroExpression || 10379 NullKind == Expr::NPCK_ZeroLiteral) { 10380 if (!ReturnType->isIntegerType()) 10381 return; 10382 } else { 10383 return; 10384 } 10385 } 10386 } else { // !IsCompare 10387 // For function to bool, only suggest if the function pointer has bool 10388 // return type. 10389 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10390 return; 10391 } 10392 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10393 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10394 } 10395 10396 /// Diagnoses "dangerous" implicit conversions within the given 10397 /// expression (which is a full expression). Implements -Wconversion 10398 /// and -Wsign-compare. 10399 /// 10400 /// \param CC the "context" location of the implicit conversion, i.e. 10401 /// the most location of the syntactic entity requiring the implicit 10402 /// conversion 10403 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10404 // Don't diagnose in unevaluated contexts. 10405 if (isUnevaluatedContext()) 10406 return; 10407 10408 // Don't diagnose for value- or type-dependent expressions. 10409 if (E->isTypeDependent() || E->isValueDependent()) 10410 return; 10411 10412 // Check for array bounds violations in cases where the check isn't triggered 10413 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10414 // ArraySubscriptExpr is on the RHS of a variable initialization. 10415 CheckArrayAccess(E); 10416 10417 // This is not the right CC for (e.g.) a variable initialization. 10418 AnalyzeImplicitConversions(*this, E, CC); 10419 } 10420 10421 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10422 /// Input argument E is a logical expression. 10423 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10424 ::CheckBoolLikeConversion(*this, E, CC); 10425 } 10426 10427 /// Diagnose when expression is an integer constant expression and its evaluation 10428 /// results in integer overflow 10429 void Sema::CheckForIntOverflow (Expr *E) { 10430 // Use a work list to deal with nested struct initializers. 10431 SmallVector<Expr *, 2> Exprs(1, E); 10432 10433 do { 10434 Expr *OriginalE = Exprs.pop_back_val(); 10435 Expr *E = OriginalE->IgnoreParenCasts(); 10436 10437 if (isa<BinaryOperator>(E)) { 10438 E->EvaluateForOverflow(Context); 10439 continue; 10440 } 10441 10442 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 10443 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10444 else if (isa<ObjCBoxedExpr>(OriginalE)) 10445 E->EvaluateForOverflow(Context); 10446 else if (auto Call = dyn_cast<CallExpr>(E)) 10447 Exprs.append(Call->arg_begin(), Call->arg_end()); 10448 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 10449 Exprs.append(Message->arg_begin(), Message->arg_end()); 10450 } while (!Exprs.empty()); 10451 } 10452 10453 namespace { 10454 10455 /// \brief Visitor for expressions which looks for unsequenced operations on the 10456 /// same object. 10457 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10458 using Base = EvaluatedExprVisitor<SequenceChecker>; 10459 10460 /// \brief A tree of sequenced regions within an expression. Two regions are 10461 /// unsequenced if one is an ancestor or a descendent of the other. When we 10462 /// finish processing an expression with sequencing, such as a comma 10463 /// expression, we fold its tree nodes into its parent, since they are 10464 /// unsequenced with respect to nodes we will visit later. 10465 class SequenceTree { 10466 struct Value { 10467 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10468 unsigned Parent : 31; 10469 unsigned Merged : 1; 10470 }; 10471 SmallVector<Value, 8> Values; 10472 10473 public: 10474 /// \brief A region within an expression which may be sequenced with respect 10475 /// to some other region. 10476 class Seq { 10477 friend class SequenceTree; 10478 10479 unsigned Index = 0; 10480 10481 explicit Seq(unsigned N) : Index(N) {} 10482 10483 public: 10484 Seq() = default; 10485 }; 10486 10487 SequenceTree() { Values.push_back(Value(0)); } 10488 Seq root() const { return Seq(0); } 10489 10490 /// \brief Create a new sequence of operations, which is an unsequenced 10491 /// subset of \p Parent. This sequence of operations is sequenced with 10492 /// respect to other children of \p Parent. 10493 Seq allocate(Seq Parent) { 10494 Values.push_back(Value(Parent.Index)); 10495 return Seq(Values.size() - 1); 10496 } 10497 10498 /// \brief Merge a sequence of operations into its parent. 10499 void merge(Seq S) { 10500 Values[S.Index].Merged = true; 10501 } 10502 10503 /// \brief Determine whether two operations are unsequenced. This operation 10504 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10505 /// should have been merged into its parent as appropriate. 10506 bool isUnsequenced(Seq Cur, Seq Old) { 10507 unsigned C = representative(Cur.Index); 10508 unsigned Target = representative(Old.Index); 10509 while (C >= Target) { 10510 if (C == Target) 10511 return true; 10512 C = Values[C].Parent; 10513 } 10514 return false; 10515 } 10516 10517 private: 10518 /// \brief Pick a representative for a sequence. 10519 unsigned representative(unsigned K) { 10520 if (Values[K].Merged) 10521 // Perform path compression as we go. 10522 return Values[K].Parent = representative(Values[K].Parent); 10523 return K; 10524 } 10525 }; 10526 10527 /// An object for which we can track unsequenced uses. 10528 using Object = NamedDecl *; 10529 10530 /// Different flavors of object usage which we track. We only track the 10531 /// least-sequenced usage of each kind. 10532 enum UsageKind { 10533 /// A read of an object. Multiple unsequenced reads are OK. 10534 UK_Use, 10535 10536 /// A modification of an object which is sequenced before the value 10537 /// computation of the expression, such as ++n in C++. 10538 UK_ModAsValue, 10539 10540 /// A modification of an object which is not sequenced before the value 10541 /// computation of the expression, such as n++. 10542 UK_ModAsSideEffect, 10543 10544 UK_Count = UK_ModAsSideEffect + 1 10545 }; 10546 10547 struct Usage { 10548 Expr *Use = nullptr; 10549 SequenceTree::Seq Seq; 10550 10551 Usage() = default; 10552 }; 10553 10554 struct UsageInfo { 10555 Usage Uses[UK_Count]; 10556 10557 /// Have we issued a diagnostic for this variable already? 10558 bool Diagnosed = false; 10559 10560 UsageInfo() = default; 10561 }; 10562 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 10563 10564 Sema &SemaRef; 10565 10566 /// Sequenced regions within the expression. 10567 SequenceTree Tree; 10568 10569 /// Declaration modifications and references which we have seen. 10570 UsageInfoMap UsageMap; 10571 10572 /// The region we are currently within. 10573 SequenceTree::Seq Region; 10574 10575 /// Filled in with declarations which were modified as a side-effect 10576 /// (that is, post-increment operations). 10577 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 10578 10579 /// Expressions to check later. We defer checking these to reduce 10580 /// stack usage. 10581 SmallVectorImpl<Expr *> &WorkList; 10582 10583 /// RAII object wrapping the visitation of a sequenced subexpression of an 10584 /// expression. At the end of this process, the side-effects of the evaluation 10585 /// become sequenced with respect to the value computation of the result, so 10586 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10587 /// UK_ModAsValue. 10588 struct SequencedSubexpression { 10589 SequencedSubexpression(SequenceChecker &Self) 10590 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 10591 Self.ModAsSideEffect = &ModAsSideEffect; 10592 } 10593 10594 ~SequencedSubexpression() { 10595 for (auto &M : llvm::reverse(ModAsSideEffect)) { 10596 UsageInfo &U = Self.UsageMap[M.first]; 10597 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 10598 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 10599 SideEffectUsage = M.second; 10600 } 10601 Self.ModAsSideEffect = OldModAsSideEffect; 10602 } 10603 10604 SequenceChecker &Self; 10605 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 10606 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 10607 }; 10608 10609 /// RAII object wrapping the visitation of a subexpression which we might 10610 /// choose to evaluate as a constant. If any subexpression is evaluated and 10611 /// found to be non-constant, this allows us to suppress the evaluation of 10612 /// the outer expression. 10613 class EvaluationTracker { 10614 public: 10615 EvaluationTracker(SequenceChecker &Self) 10616 : Self(Self), Prev(Self.EvalTracker) { 10617 Self.EvalTracker = this; 10618 } 10619 10620 ~EvaluationTracker() { 10621 Self.EvalTracker = Prev; 10622 if (Prev) 10623 Prev->EvalOK &= EvalOK; 10624 } 10625 10626 bool evaluate(const Expr *E, bool &Result) { 10627 if (!EvalOK || E->isValueDependent()) 10628 return false; 10629 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 10630 return EvalOK; 10631 } 10632 10633 private: 10634 SequenceChecker &Self; 10635 EvaluationTracker *Prev; 10636 bool EvalOK = true; 10637 } *EvalTracker = nullptr; 10638 10639 /// \brief Find the object which is produced by the specified expression, 10640 /// if any. 10641 Object getObject(Expr *E, bool Mod) const { 10642 E = E->IgnoreParenCasts(); 10643 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10644 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 10645 return getObject(UO->getSubExpr(), Mod); 10646 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10647 if (BO->getOpcode() == BO_Comma) 10648 return getObject(BO->getRHS(), Mod); 10649 if (Mod && BO->isAssignmentOp()) 10650 return getObject(BO->getLHS(), Mod); 10651 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10652 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 10653 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 10654 return ME->getMemberDecl(); 10655 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10656 // FIXME: If this is a reference, map through to its value. 10657 return DRE->getDecl(); 10658 return nullptr; 10659 } 10660 10661 /// \brief Note that an object was modified or used by an expression. 10662 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 10663 Usage &U = UI.Uses[UK]; 10664 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 10665 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 10666 ModAsSideEffect->push_back(std::make_pair(O, U)); 10667 U.Use = Ref; 10668 U.Seq = Region; 10669 } 10670 } 10671 10672 /// \brief Check whether a modification or use conflicts with a prior usage. 10673 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 10674 bool IsModMod) { 10675 if (UI.Diagnosed) 10676 return; 10677 10678 const Usage &U = UI.Uses[OtherKind]; 10679 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 10680 return; 10681 10682 Expr *Mod = U.Use; 10683 Expr *ModOrUse = Ref; 10684 if (OtherKind == UK_Use) 10685 std::swap(Mod, ModOrUse); 10686 10687 SemaRef.Diag(Mod->getExprLoc(), 10688 IsModMod ? diag::warn_unsequenced_mod_mod 10689 : diag::warn_unsequenced_mod_use) 10690 << O << SourceRange(ModOrUse->getExprLoc()); 10691 UI.Diagnosed = true; 10692 } 10693 10694 void notePreUse(Object O, Expr *Use) { 10695 UsageInfo &U = UsageMap[O]; 10696 // Uses conflict with other modifications. 10697 checkUsage(O, U, Use, UK_ModAsValue, false); 10698 } 10699 10700 void notePostUse(Object O, Expr *Use) { 10701 UsageInfo &U = UsageMap[O]; 10702 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 10703 addUsage(U, O, Use, UK_Use); 10704 } 10705 10706 void notePreMod(Object O, Expr *Mod) { 10707 UsageInfo &U = UsageMap[O]; 10708 // Modifications conflict with other modifications and with uses. 10709 checkUsage(O, U, Mod, UK_ModAsValue, true); 10710 checkUsage(O, U, Mod, UK_Use, false); 10711 } 10712 10713 void notePostMod(Object O, Expr *Use, UsageKind UK) { 10714 UsageInfo &U = UsageMap[O]; 10715 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 10716 addUsage(U, O, Use, UK); 10717 } 10718 10719 public: 10720 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 10721 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 10722 Visit(E); 10723 } 10724 10725 void VisitStmt(Stmt *S) { 10726 // Skip all statements which aren't expressions for now. 10727 } 10728 10729 void VisitExpr(Expr *E) { 10730 // By default, just recurse to evaluated subexpressions. 10731 Base::VisitStmt(E); 10732 } 10733 10734 void VisitCastExpr(CastExpr *E) { 10735 Object O = Object(); 10736 if (E->getCastKind() == CK_LValueToRValue) 10737 O = getObject(E->getSubExpr(), false); 10738 10739 if (O) 10740 notePreUse(O, E); 10741 VisitExpr(E); 10742 if (O) 10743 notePostUse(O, E); 10744 } 10745 10746 void VisitBinComma(BinaryOperator *BO) { 10747 // C++11 [expr.comma]p1: 10748 // Every value computation and side effect associated with the left 10749 // expression is sequenced before every value computation and side 10750 // effect associated with the right expression. 10751 SequenceTree::Seq LHS = Tree.allocate(Region); 10752 SequenceTree::Seq RHS = Tree.allocate(Region); 10753 SequenceTree::Seq OldRegion = Region; 10754 10755 { 10756 SequencedSubexpression SeqLHS(*this); 10757 Region = LHS; 10758 Visit(BO->getLHS()); 10759 } 10760 10761 Region = RHS; 10762 Visit(BO->getRHS()); 10763 10764 Region = OldRegion; 10765 10766 // Forget that LHS and RHS are sequenced. They are both unsequenced 10767 // with respect to other stuff. 10768 Tree.merge(LHS); 10769 Tree.merge(RHS); 10770 } 10771 10772 void VisitBinAssign(BinaryOperator *BO) { 10773 // The modification is sequenced after the value computation of the LHS 10774 // and RHS, so check it before inspecting the operands and update the 10775 // map afterwards. 10776 Object O = getObject(BO->getLHS(), true); 10777 if (!O) 10778 return VisitExpr(BO); 10779 10780 notePreMod(O, BO); 10781 10782 // C++11 [expr.ass]p7: 10783 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 10784 // only once. 10785 // 10786 // Therefore, for a compound assignment operator, O is considered used 10787 // everywhere except within the evaluation of E1 itself. 10788 if (isa<CompoundAssignOperator>(BO)) 10789 notePreUse(O, BO); 10790 10791 Visit(BO->getLHS()); 10792 10793 if (isa<CompoundAssignOperator>(BO)) 10794 notePostUse(O, BO); 10795 10796 Visit(BO->getRHS()); 10797 10798 // C++11 [expr.ass]p1: 10799 // the assignment is sequenced [...] before the value computation of the 10800 // assignment expression. 10801 // C11 6.5.16/3 has no such rule. 10802 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10803 : UK_ModAsSideEffect); 10804 } 10805 10806 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 10807 VisitBinAssign(CAO); 10808 } 10809 10810 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10811 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10812 void VisitUnaryPreIncDec(UnaryOperator *UO) { 10813 Object O = getObject(UO->getSubExpr(), true); 10814 if (!O) 10815 return VisitExpr(UO); 10816 10817 notePreMod(O, UO); 10818 Visit(UO->getSubExpr()); 10819 // C++11 [expr.pre.incr]p1: 10820 // the expression ++x is equivalent to x+=1 10821 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10822 : UK_ModAsSideEffect); 10823 } 10824 10825 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10826 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10827 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10828 Object O = getObject(UO->getSubExpr(), true); 10829 if (!O) 10830 return VisitExpr(UO); 10831 10832 notePreMod(O, UO); 10833 Visit(UO->getSubExpr()); 10834 notePostMod(O, UO, UK_ModAsSideEffect); 10835 } 10836 10837 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10838 void VisitBinLOr(BinaryOperator *BO) { 10839 // The side-effects of the LHS of an '&&' are sequenced before the 10840 // value computation of the RHS, and hence before the value computation 10841 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10842 // as if they were unconditionally sequenced. 10843 EvaluationTracker Eval(*this); 10844 { 10845 SequencedSubexpression Sequenced(*this); 10846 Visit(BO->getLHS()); 10847 } 10848 10849 bool Result; 10850 if (Eval.evaluate(BO->getLHS(), Result)) { 10851 if (!Result) 10852 Visit(BO->getRHS()); 10853 } else { 10854 // Check for unsequenced operations in the RHS, treating it as an 10855 // entirely separate evaluation. 10856 // 10857 // FIXME: If there are operations in the RHS which are unsequenced 10858 // with respect to operations outside the RHS, and those operations 10859 // are unconditionally evaluated, diagnose them. 10860 WorkList.push_back(BO->getRHS()); 10861 } 10862 } 10863 void VisitBinLAnd(BinaryOperator *BO) { 10864 EvaluationTracker Eval(*this); 10865 { 10866 SequencedSubexpression Sequenced(*this); 10867 Visit(BO->getLHS()); 10868 } 10869 10870 bool Result; 10871 if (Eval.evaluate(BO->getLHS(), Result)) { 10872 if (Result) 10873 Visit(BO->getRHS()); 10874 } else { 10875 WorkList.push_back(BO->getRHS()); 10876 } 10877 } 10878 10879 // Only visit the condition, unless we can be sure which subexpression will 10880 // be chosen. 10881 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10882 EvaluationTracker Eval(*this); 10883 { 10884 SequencedSubexpression Sequenced(*this); 10885 Visit(CO->getCond()); 10886 } 10887 10888 bool Result; 10889 if (Eval.evaluate(CO->getCond(), Result)) 10890 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10891 else { 10892 WorkList.push_back(CO->getTrueExpr()); 10893 WorkList.push_back(CO->getFalseExpr()); 10894 } 10895 } 10896 10897 void VisitCallExpr(CallExpr *CE) { 10898 // C++11 [intro.execution]p15: 10899 // When calling a function [...], every value computation and side effect 10900 // associated with any argument expression, or with the postfix expression 10901 // designating the called function, is sequenced before execution of every 10902 // expression or statement in the body of the function [and thus before 10903 // the value computation of its result]. 10904 SequencedSubexpression Sequenced(*this); 10905 Base::VisitCallExpr(CE); 10906 10907 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10908 } 10909 10910 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10911 // This is a call, so all subexpressions are sequenced before the result. 10912 SequencedSubexpression Sequenced(*this); 10913 10914 if (!CCE->isListInitialization()) 10915 return VisitExpr(CCE); 10916 10917 // In C++11, list initializations are sequenced. 10918 SmallVector<SequenceTree::Seq, 32> Elts; 10919 SequenceTree::Seq Parent = Region; 10920 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10921 E = CCE->arg_end(); 10922 I != E; ++I) { 10923 Region = Tree.allocate(Parent); 10924 Elts.push_back(Region); 10925 Visit(*I); 10926 } 10927 10928 // Forget that the initializers are sequenced. 10929 Region = Parent; 10930 for (unsigned I = 0; I < Elts.size(); ++I) 10931 Tree.merge(Elts[I]); 10932 } 10933 10934 void VisitInitListExpr(InitListExpr *ILE) { 10935 if (!SemaRef.getLangOpts().CPlusPlus11) 10936 return VisitExpr(ILE); 10937 10938 // In C++11, list initializations are sequenced. 10939 SmallVector<SequenceTree::Seq, 32> Elts; 10940 SequenceTree::Seq Parent = Region; 10941 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10942 Expr *E = ILE->getInit(I); 10943 if (!E) continue; 10944 Region = Tree.allocate(Parent); 10945 Elts.push_back(Region); 10946 Visit(E); 10947 } 10948 10949 // Forget that the initializers are sequenced. 10950 Region = Parent; 10951 for (unsigned I = 0; I < Elts.size(); ++I) 10952 Tree.merge(Elts[I]); 10953 } 10954 }; 10955 10956 } // namespace 10957 10958 void Sema::CheckUnsequencedOperations(Expr *E) { 10959 SmallVector<Expr *, 8> WorkList; 10960 WorkList.push_back(E); 10961 while (!WorkList.empty()) { 10962 Expr *Item = WorkList.pop_back_val(); 10963 SequenceChecker(*this, Item, WorkList); 10964 } 10965 } 10966 10967 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10968 bool IsConstexpr) { 10969 CheckImplicitConversions(E, CheckLoc); 10970 if (!E->isInstantiationDependent()) 10971 CheckUnsequencedOperations(E); 10972 if (!IsConstexpr && !E->isValueDependent()) 10973 CheckForIntOverflow(E); 10974 DiagnoseMisalignedMembers(); 10975 } 10976 10977 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10978 FieldDecl *BitField, 10979 Expr *Init) { 10980 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10981 } 10982 10983 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10984 SourceLocation Loc) { 10985 if (!PType->isVariablyModifiedType()) 10986 return; 10987 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10988 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10989 return; 10990 } 10991 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10992 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10993 return; 10994 } 10995 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10996 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10997 return; 10998 } 10999 11000 const ArrayType *AT = S.Context.getAsArrayType(PType); 11001 if (!AT) 11002 return; 11003 11004 if (AT->getSizeModifier() != ArrayType::Star) { 11005 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 11006 return; 11007 } 11008 11009 S.Diag(Loc, diag::err_array_star_in_function_definition); 11010 } 11011 11012 /// CheckParmsForFunctionDef - Check that the parameters of the given 11013 /// function are appropriate for the definition of a function. This 11014 /// takes care of any checks that cannot be performed on the 11015 /// declaration itself, e.g., that the types of each of the function 11016 /// parameters are complete. 11017 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 11018 bool CheckParameterNames) { 11019 bool HasInvalidParm = false; 11020 for (ParmVarDecl *Param : Parameters) { 11021 // C99 6.7.5.3p4: the parameters in a parameter type list in a 11022 // function declarator that is part of a function definition of 11023 // that function shall not have incomplete type. 11024 // 11025 // This is also C++ [dcl.fct]p6. 11026 if (!Param->isInvalidDecl() && 11027 RequireCompleteType(Param->getLocation(), Param->getType(), 11028 diag::err_typecheck_decl_incomplete_type)) { 11029 Param->setInvalidDecl(); 11030 HasInvalidParm = true; 11031 } 11032 11033 // C99 6.9.1p5: If the declarator includes a parameter type list, the 11034 // declaration of each parameter shall include an identifier. 11035 if (CheckParameterNames && 11036 Param->getIdentifier() == nullptr && 11037 !Param->isImplicit() && 11038 !getLangOpts().CPlusPlus) 11039 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11040 11041 // C99 6.7.5.3p12: 11042 // If the function declarator is not part of a definition of that 11043 // function, parameters may have incomplete type and may use the [*] 11044 // notation in their sequences of declarator specifiers to specify 11045 // variable length array types. 11046 QualType PType = Param->getOriginalType(); 11047 // FIXME: This diagnostic should point the '[*]' if source-location 11048 // information is added for it. 11049 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 11050 11051 // If the parameter is a c++ class type and it has to be destructed in the 11052 // callee function, declare the destructor so that it can be called by the 11053 // callee function. Do not perform any direct access check on the dtor here. 11054 if (!Param->isInvalidDecl()) { 11055 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 11056 if (!ClassDecl->isInvalidDecl() && 11057 !ClassDecl->hasIrrelevantDestructor() && 11058 !ClassDecl->isDependentContext() && 11059 Context.isParamDestroyedInCallee(Param->getType())) { 11060 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11061 MarkFunctionReferenced(Param->getLocation(), Destructor); 11062 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 11063 } 11064 } 11065 } 11066 11067 // Parameters with the pass_object_size attribute only need to be marked 11068 // constant at function definitions. Because we lack information about 11069 // whether we're on a declaration or definition when we're instantiating the 11070 // attribute, we need to check for constness here. 11071 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 11072 if (!Param->getType().isConstQualified()) 11073 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 11074 << Attr->getSpelling() << 1; 11075 } 11076 11077 return HasInvalidParm; 11078 } 11079 11080 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 11081 /// or MemberExpr. 11082 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 11083 ASTContext &Context) { 11084 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 11085 return Context.getDeclAlign(DRE->getDecl()); 11086 11087 if (const auto *ME = dyn_cast<MemberExpr>(E)) 11088 return Context.getDeclAlign(ME->getMemberDecl()); 11089 11090 return TypeAlign; 11091 } 11092 11093 /// CheckCastAlign - Implements -Wcast-align, which warns when a 11094 /// pointer cast increases the alignment requirements. 11095 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 11096 // This is actually a lot of work to potentially be doing on every 11097 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 11098 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 11099 return; 11100 11101 // Ignore dependent types. 11102 if (T->isDependentType() || Op->getType()->isDependentType()) 11103 return; 11104 11105 // Require that the destination be a pointer type. 11106 const PointerType *DestPtr = T->getAs<PointerType>(); 11107 if (!DestPtr) return; 11108 11109 // If the destination has alignment 1, we're done. 11110 QualType DestPointee = DestPtr->getPointeeType(); 11111 if (DestPointee->isIncompleteType()) return; 11112 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 11113 if (DestAlign.isOne()) return; 11114 11115 // Require that the source be a pointer type. 11116 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 11117 if (!SrcPtr) return; 11118 QualType SrcPointee = SrcPtr->getPointeeType(); 11119 11120 // Whitelist casts from cv void*. We already implicitly 11121 // whitelisted casts to cv void*, since they have alignment 1. 11122 // Also whitelist casts involving incomplete types, which implicitly 11123 // includes 'void'. 11124 if (SrcPointee->isIncompleteType()) return; 11125 11126 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 11127 11128 if (auto *CE = dyn_cast<CastExpr>(Op)) { 11129 if (CE->getCastKind() == CK_ArrayToPointerDecay) 11130 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 11131 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 11132 if (UO->getOpcode() == UO_AddrOf) 11133 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 11134 } 11135 11136 if (SrcAlign >= DestAlign) return; 11137 11138 Diag(TRange.getBegin(), diag::warn_cast_align) 11139 << Op->getType() << T 11140 << static_cast<unsigned>(SrcAlign.getQuantity()) 11141 << static_cast<unsigned>(DestAlign.getQuantity()) 11142 << TRange << Op->getSourceRange(); 11143 } 11144 11145 /// \brief Check whether this array fits the idiom of a size-one tail padded 11146 /// array member of a struct. 11147 /// 11148 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 11149 /// commonly used to emulate flexible arrays in C89 code. 11150 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 11151 const NamedDecl *ND) { 11152 if (Size != 1 || !ND) return false; 11153 11154 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 11155 if (!FD) return false; 11156 11157 // Don't consider sizes resulting from macro expansions or template argument 11158 // substitution to form C89 tail-padded arrays. 11159 11160 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 11161 while (TInfo) { 11162 TypeLoc TL = TInfo->getTypeLoc(); 11163 // Look through typedefs. 11164 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 11165 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 11166 TInfo = TDL->getTypeSourceInfo(); 11167 continue; 11168 } 11169 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 11170 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 11171 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 11172 return false; 11173 } 11174 break; 11175 } 11176 11177 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 11178 if (!RD) return false; 11179 if (RD->isUnion()) return false; 11180 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11181 if (!CRD->isStandardLayout()) return false; 11182 } 11183 11184 // See if this is the last field decl in the record. 11185 const Decl *D = FD; 11186 while ((D = D->getNextDeclInContext())) 11187 if (isa<FieldDecl>(D)) 11188 return false; 11189 return true; 11190 } 11191 11192 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 11193 const ArraySubscriptExpr *ASE, 11194 bool AllowOnePastEnd, bool IndexNegated) { 11195 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 11196 if (IndexExpr->isValueDependent()) 11197 return; 11198 11199 const Type *EffectiveType = 11200 BaseExpr->getType()->getPointeeOrArrayElementType(); 11201 BaseExpr = BaseExpr->IgnoreParenCasts(); 11202 const ConstantArrayType *ArrayTy = 11203 Context.getAsConstantArrayType(BaseExpr->getType()); 11204 if (!ArrayTy) 11205 return; 11206 11207 llvm::APSInt index; 11208 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 11209 return; 11210 if (IndexNegated) 11211 index = -index; 11212 11213 const NamedDecl *ND = nullptr; 11214 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11215 ND = DRE->getDecl(); 11216 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11217 ND = ME->getMemberDecl(); 11218 11219 if (index.isUnsigned() || !index.isNegative()) { 11220 llvm::APInt size = ArrayTy->getSize(); 11221 if (!size.isStrictlyPositive()) 11222 return; 11223 11224 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 11225 if (BaseType != EffectiveType) { 11226 // Make sure we're comparing apples to apples when comparing index to size 11227 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 11228 uint64_t array_typesize = Context.getTypeSize(BaseType); 11229 // Handle ptrarith_typesize being zero, such as when casting to void* 11230 if (!ptrarith_typesize) ptrarith_typesize = 1; 11231 if (ptrarith_typesize != array_typesize) { 11232 // There's a cast to a different size type involved 11233 uint64_t ratio = array_typesize / ptrarith_typesize; 11234 // TODO: Be smarter about handling cases where array_typesize is not a 11235 // multiple of ptrarith_typesize 11236 if (ptrarith_typesize * ratio == array_typesize) 11237 size *= llvm::APInt(size.getBitWidth(), ratio); 11238 } 11239 } 11240 11241 if (size.getBitWidth() > index.getBitWidth()) 11242 index = index.zext(size.getBitWidth()); 11243 else if (size.getBitWidth() < index.getBitWidth()) 11244 size = size.zext(index.getBitWidth()); 11245 11246 // For array subscripting the index must be less than size, but for pointer 11247 // arithmetic also allow the index (offset) to be equal to size since 11248 // computing the next address after the end of the array is legal and 11249 // commonly done e.g. in C++ iterators and range-based for loops. 11250 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 11251 return; 11252 11253 // Also don't warn for arrays of size 1 which are members of some 11254 // structure. These are often used to approximate flexible arrays in C89 11255 // code. 11256 if (IsTailPaddedMemberArray(*this, size, ND)) 11257 return; 11258 11259 // Suppress the warning if the subscript expression (as identified by the 11260 // ']' location) and the index expression are both from macro expansions 11261 // within a system header. 11262 if (ASE) { 11263 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 11264 ASE->getRBracketLoc()); 11265 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 11266 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 11267 IndexExpr->getLocStart()); 11268 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 11269 return; 11270 } 11271 } 11272 11273 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 11274 if (ASE) 11275 DiagID = diag::warn_array_index_exceeds_bounds; 11276 11277 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11278 PDiag(DiagID) << index.toString(10, true) 11279 << size.toString(10, true) 11280 << (unsigned)size.getLimitedValue(~0U) 11281 << IndexExpr->getSourceRange()); 11282 } else { 11283 unsigned DiagID = diag::warn_array_index_precedes_bounds; 11284 if (!ASE) { 11285 DiagID = diag::warn_ptr_arith_precedes_bounds; 11286 if (index.isNegative()) index = -index; 11287 } 11288 11289 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11290 PDiag(DiagID) << index.toString(10, true) 11291 << IndexExpr->getSourceRange()); 11292 } 11293 11294 if (!ND) { 11295 // Try harder to find a NamedDecl to point at in the note. 11296 while (const ArraySubscriptExpr *ASE = 11297 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 11298 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 11299 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11300 ND = DRE->getDecl(); 11301 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11302 ND = ME->getMemberDecl(); 11303 } 11304 11305 if (ND) 11306 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 11307 PDiag(diag::note_array_index_out_of_bounds) 11308 << ND->getDeclName()); 11309 } 11310 11311 void Sema::CheckArrayAccess(const Expr *expr) { 11312 int AllowOnePastEnd = 0; 11313 while (expr) { 11314 expr = expr->IgnoreParenImpCasts(); 11315 switch (expr->getStmtClass()) { 11316 case Stmt::ArraySubscriptExprClass: { 11317 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 11318 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 11319 AllowOnePastEnd > 0); 11320 expr = ASE->getBase(); 11321 break; 11322 } 11323 case Stmt::MemberExprClass: { 11324 expr = cast<MemberExpr>(expr)->getBase(); 11325 break; 11326 } 11327 case Stmt::OMPArraySectionExprClass: { 11328 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 11329 if (ASE->getLowerBound()) 11330 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 11331 /*ASE=*/nullptr, AllowOnePastEnd > 0); 11332 return; 11333 } 11334 case Stmt::UnaryOperatorClass: { 11335 // Only unwrap the * and & unary operators 11336 const UnaryOperator *UO = cast<UnaryOperator>(expr); 11337 expr = UO->getSubExpr(); 11338 switch (UO->getOpcode()) { 11339 case UO_AddrOf: 11340 AllowOnePastEnd++; 11341 break; 11342 case UO_Deref: 11343 AllowOnePastEnd--; 11344 break; 11345 default: 11346 return; 11347 } 11348 break; 11349 } 11350 case Stmt::ConditionalOperatorClass: { 11351 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 11352 if (const Expr *lhs = cond->getLHS()) 11353 CheckArrayAccess(lhs); 11354 if (const Expr *rhs = cond->getRHS()) 11355 CheckArrayAccess(rhs); 11356 return; 11357 } 11358 case Stmt::CXXOperatorCallExprClass: { 11359 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 11360 for (const auto *Arg : OCE->arguments()) 11361 CheckArrayAccess(Arg); 11362 return; 11363 } 11364 default: 11365 return; 11366 } 11367 } 11368 } 11369 11370 //===--- CHECK: Objective-C retain cycles ----------------------------------// 11371 11372 namespace { 11373 11374 struct RetainCycleOwner { 11375 VarDecl *Variable = nullptr; 11376 SourceRange Range; 11377 SourceLocation Loc; 11378 bool Indirect = false; 11379 11380 RetainCycleOwner() = default; 11381 11382 void setLocsFrom(Expr *e) { 11383 Loc = e->getExprLoc(); 11384 Range = e->getSourceRange(); 11385 } 11386 }; 11387 11388 } // namespace 11389 11390 /// Consider whether capturing the given variable can possibly lead to 11391 /// a retain cycle. 11392 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11393 // In ARC, it's captured strongly iff the variable has __strong 11394 // lifetime. In MRR, it's captured strongly if the variable is 11395 // __block and has an appropriate type. 11396 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11397 return false; 11398 11399 owner.Variable = var; 11400 if (ref) 11401 owner.setLocsFrom(ref); 11402 return true; 11403 } 11404 11405 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11406 while (true) { 11407 e = e->IgnoreParens(); 11408 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11409 switch (cast->getCastKind()) { 11410 case CK_BitCast: 11411 case CK_LValueBitCast: 11412 case CK_LValueToRValue: 11413 case CK_ARCReclaimReturnedObject: 11414 e = cast->getSubExpr(); 11415 continue; 11416 11417 default: 11418 return false; 11419 } 11420 } 11421 11422 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11423 ObjCIvarDecl *ivar = ref->getDecl(); 11424 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11425 return false; 11426 11427 // Try to find a retain cycle in the base. 11428 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11429 return false; 11430 11431 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11432 owner.Indirect = true; 11433 return true; 11434 } 11435 11436 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11437 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11438 if (!var) return false; 11439 return considerVariable(var, ref, owner); 11440 } 11441 11442 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11443 if (member->isArrow()) return false; 11444 11445 // Don't count this as an indirect ownership. 11446 e = member->getBase(); 11447 continue; 11448 } 11449 11450 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11451 // Only pay attention to pseudo-objects on property references. 11452 ObjCPropertyRefExpr *pre 11453 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11454 ->IgnoreParens()); 11455 if (!pre) return false; 11456 if (pre->isImplicitProperty()) return false; 11457 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11458 if (!property->isRetaining() && 11459 !(property->getPropertyIvarDecl() && 11460 property->getPropertyIvarDecl()->getType() 11461 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11462 return false; 11463 11464 owner.Indirect = true; 11465 if (pre->isSuperReceiver()) { 11466 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11467 if (!owner.Variable) 11468 return false; 11469 owner.Loc = pre->getLocation(); 11470 owner.Range = pre->getSourceRange(); 11471 return true; 11472 } 11473 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11474 ->getSourceExpr()); 11475 continue; 11476 } 11477 11478 // Array ivars? 11479 11480 return false; 11481 } 11482 } 11483 11484 namespace { 11485 11486 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11487 ASTContext &Context; 11488 VarDecl *Variable; 11489 Expr *Capturer = nullptr; 11490 bool VarWillBeReased = false; 11491 11492 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11493 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11494 Context(Context), Variable(variable) {} 11495 11496 void VisitDeclRefExpr(DeclRefExpr *ref) { 11497 if (ref->getDecl() == Variable && !Capturer) 11498 Capturer = ref; 11499 } 11500 11501 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11502 if (Capturer) return; 11503 Visit(ref->getBase()); 11504 if (Capturer && ref->isFreeIvar()) 11505 Capturer = ref; 11506 } 11507 11508 void VisitBlockExpr(BlockExpr *block) { 11509 // Look inside nested blocks 11510 if (block->getBlockDecl()->capturesVariable(Variable)) 11511 Visit(block->getBlockDecl()->getBody()); 11512 } 11513 11514 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11515 if (Capturer) return; 11516 if (OVE->getSourceExpr()) 11517 Visit(OVE->getSourceExpr()); 11518 } 11519 11520 void VisitBinaryOperator(BinaryOperator *BinOp) { 11521 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11522 return; 11523 Expr *LHS = BinOp->getLHS(); 11524 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11525 if (DRE->getDecl() != Variable) 11526 return; 11527 if (Expr *RHS = BinOp->getRHS()) { 11528 RHS = RHS->IgnoreParenCasts(); 11529 llvm::APSInt Value; 11530 VarWillBeReased = 11531 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11532 } 11533 } 11534 } 11535 }; 11536 11537 } // namespace 11538 11539 /// Check whether the given argument is a block which captures a 11540 /// variable. 11541 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11542 assert(owner.Variable && owner.Loc.isValid()); 11543 11544 e = e->IgnoreParenCasts(); 11545 11546 // Look through [^{...} copy] and Block_copy(^{...}). 11547 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11548 Selector Cmd = ME->getSelector(); 11549 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11550 e = ME->getInstanceReceiver(); 11551 if (!e) 11552 return nullptr; 11553 e = e->IgnoreParenCasts(); 11554 } 11555 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11556 if (CE->getNumArgs() == 1) { 11557 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11558 if (Fn) { 11559 const IdentifierInfo *FnI = Fn->getIdentifier(); 11560 if (FnI && FnI->isStr("_Block_copy")) { 11561 e = CE->getArg(0)->IgnoreParenCasts(); 11562 } 11563 } 11564 } 11565 } 11566 11567 BlockExpr *block = dyn_cast<BlockExpr>(e); 11568 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11569 return nullptr; 11570 11571 FindCaptureVisitor visitor(S.Context, owner.Variable); 11572 visitor.Visit(block->getBlockDecl()->getBody()); 11573 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11574 } 11575 11576 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11577 RetainCycleOwner &owner) { 11578 assert(capturer); 11579 assert(owner.Variable && owner.Loc.isValid()); 11580 11581 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11582 << owner.Variable << capturer->getSourceRange(); 11583 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11584 << owner.Indirect << owner.Range; 11585 } 11586 11587 /// Check for a keyword selector that starts with the word 'add' or 11588 /// 'set'. 11589 static bool isSetterLikeSelector(Selector sel) { 11590 if (sel.isUnarySelector()) return false; 11591 11592 StringRef str = sel.getNameForSlot(0); 11593 while (!str.empty() && str.front() == '_') str = str.substr(1); 11594 if (str.startswith("set")) 11595 str = str.substr(3); 11596 else if (str.startswith("add")) { 11597 // Specially whitelist 'addOperationWithBlock:'. 11598 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 11599 return false; 11600 str = str.substr(3); 11601 } 11602 else 11603 return false; 11604 11605 if (str.empty()) return true; 11606 return !isLowercase(str.front()); 11607 } 11608 11609 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 11610 ObjCMessageExpr *Message) { 11611 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 11612 Message->getReceiverInterface(), 11613 NSAPI::ClassId_NSMutableArray); 11614 if (!IsMutableArray) { 11615 return None; 11616 } 11617 11618 Selector Sel = Message->getSelector(); 11619 11620 Optional<NSAPI::NSArrayMethodKind> MKOpt = 11621 S.NSAPIObj->getNSArrayMethodKind(Sel); 11622 if (!MKOpt) { 11623 return None; 11624 } 11625 11626 NSAPI::NSArrayMethodKind MK = *MKOpt; 11627 11628 switch (MK) { 11629 case NSAPI::NSMutableArr_addObject: 11630 case NSAPI::NSMutableArr_insertObjectAtIndex: 11631 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 11632 return 0; 11633 case NSAPI::NSMutableArr_replaceObjectAtIndex: 11634 return 1; 11635 11636 default: 11637 return None; 11638 } 11639 11640 return None; 11641 } 11642 11643 static 11644 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 11645 ObjCMessageExpr *Message) { 11646 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 11647 Message->getReceiverInterface(), 11648 NSAPI::ClassId_NSMutableDictionary); 11649 if (!IsMutableDictionary) { 11650 return None; 11651 } 11652 11653 Selector Sel = Message->getSelector(); 11654 11655 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 11656 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 11657 if (!MKOpt) { 11658 return None; 11659 } 11660 11661 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 11662 11663 switch (MK) { 11664 case NSAPI::NSMutableDict_setObjectForKey: 11665 case NSAPI::NSMutableDict_setValueForKey: 11666 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 11667 return 0; 11668 11669 default: 11670 return None; 11671 } 11672 11673 return None; 11674 } 11675 11676 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 11677 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 11678 Message->getReceiverInterface(), 11679 NSAPI::ClassId_NSMutableSet); 11680 11681 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 11682 Message->getReceiverInterface(), 11683 NSAPI::ClassId_NSMutableOrderedSet); 11684 if (!IsMutableSet && !IsMutableOrderedSet) { 11685 return None; 11686 } 11687 11688 Selector Sel = Message->getSelector(); 11689 11690 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 11691 if (!MKOpt) { 11692 return None; 11693 } 11694 11695 NSAPI::NSSetMethodKind MK = *MKOpt; 11696 11697 switch (MK) { 11698 case NSAPI::NSMutableSet_addObject: 11699 case NSAPI::NSOrderedSet_setObjectAtIndex: 11700 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 11701 case NSAPI::NSOrderedSet_insertObjectAtIndex: 11702 return 0; 11703 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 11704 return 1; 11705 } 11706 11707 return None; 11708 } 11709 11710 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 11711 if (!Message->isInstanceMessage()) { 11712 return; 11713 } 11714 11715 Optional<int> ArgOpt; 11716 11717 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 11718 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 11719 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 11720 return; 11721 } 11722 11723 int ArgIndex = *ArgOpt; 11724 11725 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 11726 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 11727 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 11728 } 11729 11730 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 11731 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11732 if (ArgRE->isObjCSelfExpr()) { 11733 Diag(Message->getSourceRange().getBegin(), 11734 diag::warn_objc_circular_container) 11735 << ArgRE->getDecl() << StringRef("'super'"); 11736 } 11737 } 11738 } else { 11739 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 11740 11741 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 11742 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 11743 } 11744 11745 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 11746 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11747 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 11748 ValueDecl *Decl = ReceiverRE->getDecl(); 11749 Diag(Message->getSourceRange().getBegin(), 11750 diag::warn_objc_circular_container) 11751 << Decl << Decl; 11752 if (!ArgRE->isObjCSelfExpr()) { 11753 Diag(Decl->getLocation(), 11754 diag::note_objc_circular_container_declared_here) 11755 << Decl; 11756 } 11757 } 11758 } 11759 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 11760 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 11761 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 11762 ObjCIvarDecl *Decl = IvarRE->getDecl(); 11763 Diag(Message->getSourceRange().getBegin(), 11764 diag::warn_objc_circular_container) 11765 << Decl << Decl; 11766 Diag(Decl->getLocation(), 11767 diag::note_objc_circular_container_declared_here) 11768 << Decl; 11769 } 11770 } 11771 } 11772 } 11773 } 11774 11775 /// Check a message send to see if it's likely to cause a retain cycle. 11776 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11777 // Only check instance methods whose selector looks like a setter. 11778 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 11779 return; 11780 11781 // Try to find a variable that the receiver is strongly owned by. 11782 RetainCycleOwner owner; 11783 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 11784 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 11785 return; 11786 } else { 11787 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 11788 owner.Variable = getCurMethodDecl()->getSelfDecl(); 11789 owner.Loc = msg->getSuperLoc(); 11790 owner.Range = msg->getSuperLoc(); 11791 } 11792 11793 // Check whether the receiver is captured by any of the arguments. 11794 const ObjCMethodDecl *MD = msg->getMethodDecl(); 11795 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 11796 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 11797 // noescape blocks should not be retained by the method. 11798 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 11799 continue; 11800 return diagnoseRetainCycle(*this, capturer, owner); 11801 } 11802 } 11803 } 11804 11805 /// Check a property assign to see if it's likely to cause a retain cycle. 11806 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 11807 RetainCycleOwner owner; 11808 if (!findRetainCycleOwner(*this, receiver, owner)) 11809 return; 11810 11811 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 11812 diagnoseRetainCycle(*this, capturer, owner); 11813 } 11814 11815 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 11816 RetainCycleOwner Owner; 11817 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 11818 return; 11819 11820 // Because we don't have an expression for the variable, we have to set the 11821 // location explicitly here. 11822 Owner.Loc = Var->getLocation(); 11823 Owner.Range = Var->getSourceRange(); 11824 11825 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 11826 diagnoseRetainCycle(*this, Capturer, Owner); 11827 } 11828 11829 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 11830 Expr *RHS, bool isProperty) { 11831 // Check if RHS is an Objective-C object literal, which also can get 11832 // immediately zapped in a weak reference. Note that we explicitly 11833 // allow ObjCStringLiterals, since those are designed to never really die. 11834 RHS = RHS->IgnoreParenImpCasts(); 11835 11836 // This enum needs to match with the 'select' in 11837 // warn_objc_arc_literal_assign (off-by-1). 11838 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 11839 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 11840 return false; 11841 11842 S.Diag(Loc, diag::warn_arc_literal_assign) 11843 << (unsigned) Kind 11844 << (isProperty ? 0 : 1) 11845 << RHS->getSourceRange(); 11846 11847 return true; 11848 } 11849 11850 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 11851 Qualifiers::ObjCLifetime LT, 11852 Expr *RHS, bool isProperty) { 11853 // Strip off any implicit cast added to get to the one ARC-specific. 11854 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11855 if (cast->getCastKind() == CK_ARCConsumeObject) { 11856 S.Diag(Loc, diag::warn_arc_retained_assign) 11857 << (LT == Qualifiers::OCL_ExplicitNone) 11858 << (isProperty ? 0 : 1) 11859 << RHS->getSourceRange(); 11860 return true; 11861 } 11862 RHS = cast->getSubExpr(); 11863 } 11864 11865 if (LT == Qualifiers::OCL_Weak && 11866 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11867 return true; 11868 11869 return false; 11870 } 11871 11872 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11873 QualType LHS, Expr *RHS) { 11874 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11875 11876 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11877 return false; 11878 11879 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11880 return true; 11881 11882 return false; 11883 } 11884 11885 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11886 Expr *LHS, Expr *RHS) { 11887 QualType LHSType; 11888 // PropertyRef on LHS type need be directly obtained from 11889 // its declaration as it has a PseudoType. 11890 ObjCPropertyRefExpr *PRE 11891 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11892 if (PRE && !PRE->isImplicitProperty()) { 11893 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11894 if (PD) 11895 LHSType = PD->getType(); 11896 } 11897 11898 if (LHSType.isNull()) 11899 LHSType = LHS->getType(); 11900 11901 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11902 11903 if (LT == Qualifiers::OCL_Weak) { 11904 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11905 getCurFunction()->markSafeWeakUse(LHS); 11906 } 11907 11908 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11909 return; 11910 11911 // FIXME. Check for other life times. 11912 if (LT != Qualifiers::OCL_None) 11913 return; 11914 11915 if (PRE) { 11916 if (PRE->isImplicitProperty()) 11917 return; 11918 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11919 if (!PD) 11920 return; 11921 11922 unsigned Attributes = PD->getPropertyAttributes(); 11923 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11924 // when 'assign' attribute was not explicitly specified 11925 // by user, ignore it and rely on property type itself 11926 // for lifetime info. 11927 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11928 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11929 LHSType->isObjCRetainableType()) 11930 return; 11931 11932 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11933 if (cast->getCastKind() == CK_ARCConsumeObject) { 11934 Diag(Loc, diag::warn_arc_retained_property_assign) 11935 << RHS->getSourceRange(); 11936 return; 11937 } 11938 RHS = cast->getSubExpr(); 11939 } 11940 } 11941 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11942 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11943 return; 11944 } 11945 } 11946 } 11947 11948 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11949 11950 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11951 SourceLocation StmtLoc, 11952 const NullStmt *Body) { 11953 // Do not warn if the body is a macro that expands to nothing, e.g: 11954 // 11955 // #define CALL(x) 11956 // if (condition) 11957 // CALL(0); 11958 if (Body->hasLeadingEmptyMacro()) 11959 return false; 11960 11961 // Get line numbers of statement and body. 11962 bool StmtLineInvalid; 11963 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11964 &StmtLineInvalid); 11965 if (StmtLineInvalid) 11966 return false; 11967 11968 bool BodyLineInvalid; 11969 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11970 &BodyLineInvalid); 11971 if (BodyLineInvalid) 11972 return false; 11973 11974 // Warn if null statement and body are on the same line. 11975 if (StmtLine != BodyLine) 11976 return false; 11977 11978 return true; 11979 } 11980 11981 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11982 const Stmt *Body, 11983 unsigned DiagID) { 11984 // Since this is a syntactic check, don't emit diagnostic for template 11985 // instantiations, this just adds noise. 11986 if (CurrentInstantiationScope) 11987 return; 11988 11989 // The body should be a null statement. 11990 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11991 if (!NBody) 11992 return; 11993 11994 // Do the usual checks. 11995 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11996 return; 11997 11998 Diag(NBody->getSemiLoc(), DiagID); 11999 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12000 } 12001 12002 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 12003 const Stmt *PossibleBody) { 12004 assert(!CurrentInstantiationScope); // Ensured by caller 12005 12006 SourceLocation StmtLoc; 12007 const Stmt *Body; 12008 unsigned DiagID; 12009 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 12010 StmtLoc = FS->getRParenLoc(); 12011 Body = FS->getBody(); 12012 DiagID = diag::warn_empty_for_body; 12013 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 12014 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 12015 Body = WS->getBody(); 12016 DiagID = diag::warn_empty_while_body; 12017 } else 12018 return; // Neither `for' nor `while'. 12019 12020 // The body should be a null statement. 12021 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12022 if (!NBody) 12023 return; 12024 12025 // Skip expensive checks if diagnostic is disabled. 12026 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 12027 return; 12028 12029 // Do the usual checks. 12030 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12031 return; 12032 12033 // `for(...);' and `while(...);' are popular idioms, so in order to keep 12034 // noise level low, emit diagnostics only if for/while is followed by a 12035 // CompoundStmt, e.g.: 12036 // for (int i = 0; i < n; i++); 12037 // { 12038 // a(i); 12039 // } 12040 // or if for/while is followed by a statement with more indentation 12041 // than for/while itself: 12042 // for (int i = 0; i < n; i++); 12043 // a(i); 12044 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 12045 if (!ProbableTypo) { 12046 bool BodyColInvalid; 12047 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 12048 PossibleBody->getLocStart(), 12049 &BodyColInvalid); 12050 if (BodyColInvalid) 12051 return; 12052 12053 bool StmtColInvalid; 12054 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 12055 S->getLocStart(), 12056 &StmtColInvalid); 12057 if (StmtColInvalid) 12058 return; 12059 12060 if (BodyCol > StmtCol) 12061 ProbableTypo = true; 12062 } 12063 12064 if (ProbableTypo) { 12065 Diag(NBody->getSemiLoc(), DiagID); 12066 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12067 } 12068 } 12069 12070 //===--- CHECK: Warn on self move with std::move. -------------------------===// 12071 12072 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 12073 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 12074 SourceLocation OpLoc) { 12075 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 12076 return; 12077 12078 if (inTemplateInstantiation()) 12079 return; 12080 12081 // Strip parens and casts away. 12082 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12083 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12084 12085 // Check for a call expression 12086 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 12087 if (!CE || CE->getNumArgs() != 1) 12088 return; 12089 12090 // Check for a call to std::move 12091 if (!CE->isCallToStdMove()) 12092 return; 12093 12094 // Get argument from std::move 12095 RHSExpr = CE->getArg(0); 12096 12097 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12098 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12099 12100 // Two DeclRefExpr's, check that the decls are the same. 12101 if (LHSDeclRef && RHSDeclRef) { 12102 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 12103 return; 12104 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 12105 RHSDeclRef->getDecl()->getCanonicalDecl()) 12106 return; 12107 12108 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12109 << LHSExpr->getSourceRange() 12110 << RHSExpr->getSourceRange(); 12111 return; 12112 } 12113 12114 // Member variables require a different approach to check for self moves. 12115 // MemberExpr's are the same if every nested MemberExpr refers to the same 12116 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 12117 // the base Expr's are CXXThisExpr's. 12118 const Expr *LHSBase = LHSExpr; 12119 const Expr *RHSBase = RHSExpr; 12120 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 12121 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 12122 if (!LHSME || !RHSME) 12123 return; 12124 12125 while (LHSME && RHSME) { 12126 if (LHSME->getMemberDecl()->getCanonicalDecl() != 12127 RHSME->getMemberDecl()->getCanonicalDecl()) 12128 return; 12129 12130 LHSBase = LHSME->getBase(); 12131 RHSBase = RHSME->getBase(); 12132 LHSME = dyn_cast<MemberExpr>(LHSBase); 12133 RHSME = dyn_cast<MemberExpr>(RHSBase); 12134 } 12135 12136 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 12137 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 12138 if (LHSDeclRef && RHSDeclRef) { 12139 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 12140 return; 12141 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 12142 RHSDeclRef->getDecl()->getCanonicalDecl()) 12143 return; 12144 12145 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12146 << LHSExpr->getSourceRange() 12147 << RHSExpr->getSourceRange(); 12148 return; 12149 } 12150 12151 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 12152 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12153 << LHSExpr->getSourceRange() 12154 << RHSExpr->getSourceRange(); 12155 } 12156 12157 //===--- Layout compatibility ----------------------------------------------// 12158 12159 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 12160 12161 /// \brief Check if two enumeration types are layout-compatible. 12162 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 12163 // C++11 [dcl.enum] p8: 12164 // Two enumeration types are layout-compatible if they have the same 12165 // underlying type. 12166 return ED1->isComplete() && ED2->isComplete() && 12167 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 12168 } 12169 12170 /// \brief Check if two fields are layout-compatible. 12171 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 12172 FieldDecl *Field2) { 12173 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 12174 return false; 12175 12176 if (Field1->isBitField() != Field2->isBitField()) 12177 return false; 12178 12179 if (Field1->isBitField()) { 12180 // Make sure that the bit-fields are the same length. 12181 unsigned Bits1 = Field1->getBitWidthValue(C); 12182 unsigned Bits2 = Field2->getBitWidthValue(C); 12183 12184 if (Bits1 != Bits2) 12185 return false; 12186 } 12187 12188 return true; 12189 } 12190 12191 /// \brief Check if two standard-layout structs are layout-compatible. 12192 /// (C++11 [class.mem] p17) 12193 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 12194 RecordDecl *RD2) { 12195 // If both records are C++ classes, check that base classes match. 12196 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 12197 // If one of records is a CXXRecordDecl we are in C++ mode, 12198 // thus the other one is a CXXRecordDecl, too. 12199 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 12200 // Check number of base classes. 12201 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 12202 return false; 12203 12204 // Check the base classes. 12205 for (CXXRecordDecl::base_class_const_iterator 12206 Base1 = D1CXX->bases_begin(), 12207 BaseEnd1 = D1CXX->bases_end(), 12208 Base2 = D2CXX->bases_begin(); 12209 Base1 != BaseEnd1; 12210 ++Base1, ++Base2) { 12211 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 12212 return false; 12213 } 12214 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 12215 // If only RD2 is a C++ class, it should have zero base classes. 12216 if (D2CXX->getNumBases() > 0) 12217 return false; 12218 } 12219 12220 // Check the fields. 12221 RecordDecl::field_iterator Field2 = RD2->field_begin(), 12222 Field2End = RD2->field_end(), 12223 Field1 = RD1->field_begin(), 12224 Field1End = RD1->field_end(); 12225 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 12226 if (!isLayoutCompatible(C, *Field1, *Field2)) 12227 return false; 12228 } 12229 if (Field1 != Field1End || Field2 != Field2End) 12230 return false; 12231 12232 return true; 12233 } 12234 12235 /// \brief Check if two standard-layout unions are layout-compatible. 12236 /// (C++11 [class.mem] p18) 12237 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 12238 RecordDecl *RD2) { 12239 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 12240 for (auto *Field2 : RD2->fields()) 12241 UnmatchedFields.insert(Field2); 12242 12243 for (auto *Field1 : RD1->fields()) { 12244 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 12245 I = UnmatchedFields.begin(), 12246 E = UnmatchedFields.end(); 12247 12248 for ( ; I != E; ++I) { 12249 if (isLayoutCompatible(C, Field1, *I)) { 12250 bool Result = UnmatchedFields.erase(*I); 12251 (void) Result; 12252 assert(Result); 12253 break; 12254 } 12255 } 12256 if (I == E) 12257 return false; 12258 } 12259 12260 return UnmatchedFields.empty(); 12261 } 12262 12263 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 12264 RecordDecl *RD2) { 12265 if (RD1->isUnion() != RD2->isUnion()) 12266 return false; 12267 12268 if (RD1->isUnion()) 12269 return isLayoutCompatibleUnion(C, RD1, RD2); 12270 else 12271 return isLayoutCompatibleStruct(C, RD1, RD2); 12272 } 12273 12274 /// \brief Check if two types are layout-compatible in C++11 sense. 12275 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 12276 if (T1.isNull() || T2.isNull()) 12277 return false; 12278 12279 // C++11 [basic.types] p11: 12280 // If two types T1 and T2 are the same type, then T1 and T2 are 12281 // layout-compatible types. 12282 if (C.hasSameType(T1, T2)) 12283 return true; 12284 12285 T1 = T1.getCanonicalType().getUnqualifiedType(); 12286 T2 = T2.getCanonicalType().getUnqualifiedType(); 12287 12288 const Type::TypeClass TC1 = T1->getTypeClass(); 12289 const Type::TypeClass TC2 = T2->getTypeClass(); 12290 12291 if (TC1 != TC2) 12292 return false; 12293 12294 if (TC1 == Type::Enum) { 12295 return isLayoutCompatible(C, 12296 cast<EnumType>(T1)->getDecl(), 12297 cast<EnumType>(T2)->getDecl()); 12298 } else if (TC1 == Type::Record) { 12299 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 12300 return false; 12301 12302 return isLayoutCompatible(C, 12303 cast<RecordType>(T1)->getDecl(), 12304 cast<RecordType>(T2)->getDecl()); 12305 } 12306 12307 return false; 12308 } 12309 12310 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 12311 12312 /// \brief Given a type tag expression find the type tag itself. 12313 /// 12314 /// \param TypeExpr Type tag expression, as it appears in user's code. 12315 /// 12316 /// \param VD Declaration of an identifier that appears in a type tag. 12317 /// 12318 /// \param MagicValue Type tag magic value. 12319 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 12320 const ValueDecl **VD, uint64_t *MagicValue) { 12321 while(true) { 12322 if (!TypeExpr) 12323 return false; 12324 12325 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 12326 12327 switch (TypeExpr->getStmtClass()) { 12328 case Stmt::UnaryOperatorClass: { 12329 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 12330 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 12331 TypeExpr = UO->getSubExpr(); 12332 continue; 12333 } 12334 return false; 12335 } 12336 12337 case Stmt::DeclRefExprClass: { 12338 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 12339 *VD = DRE->getDecl(); 12340 return true; 12341 } 12342 12343 case Stmt::IntegerLiteralClass: { 12344 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 12345 llvm::APInt MagicValueAPInt = IL->getValue(); 12346 if (MagicValueAPInt.getActiveBits() <= 64) { 12347 *MagicValue = MagicValueAPInt.getZExtValue(); 12348 return true; 12349 } else 12350 return false; 12351 } 12352 12353 case Stmt::BinaryConditionalOperatorClass: 12354 case Stmt::ConditionalOperatorClass: { 12355 const AbstractConditionalOperator *ACO = 12356 cast<AbstractConditionalOperator>(TypeExpr); 12357 bool Result; 12358 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 12359 if (Result) 12360 TypeExpr = ACO->getTrueExpr(); 12361 else 12362 TypeExpr = ACO->getFalseExpr(); 12363 continue; 12364 } 12365 return false; 12366 } 12367 12368 case Stmt::BinaryOperatorClass: { 12369 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 12370 if (BO->getOpcode() == BO_Comma) { 12371 TypeExpr = BO->getRHS(); 12372 continue; 12373 } 12374 return false; 12375 } 12376 12377 default: 12378 return false; 12379 } 12380 } 12381 } 12382 12383 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 12384 /// 12385 /// \param TypeExpr Expression that specifies a type tag. 12386 /// 12387 /// \param MagicValues Registered magic values. 12388 /// 12389 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12390 /// kind. 12391 /// 12392 /// \param TypeInfo Information about the corresponding C type. 12393 /// 12394 /// \returns true if the corresponding C type was found. 12395 static bool GetMatchingCType( 12396 const IdentifierInfo *ArgumentKind, 12397 const Expr *TypeExpr, const ASTContext &Ctx, 12398 const llvm::DenseMap<Sema::TypeTagMagicValue, 12399 Sema::TypeTagData> *MagicValues, 12400 bool &FoundWrongKind, 12401 Sema::TypeTagData &TypeInfo) { 12402 FoundWrongKind = false; 12403 12404 // Variable declaration that has type_tag_for_datatype attribute. 12405 const ValueDecl *VD = nullptr; 12406 12407 uint64_t MagicValue; 12408 12409 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12410 return false; 12411 12412 if (VD) { 12413 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12414 if (I->getArgumentKind() != ArgumentKind) { 12415 FoundWrongKind = true; 12416 return false; 12417 } 12418 TypeInfo.Type = I->getMatchingCType(); 12419 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12420 TypeInfo.MustBeNull = I->getMustBeNull(); 12421 return true; 12422 } 12423 return false; 12424 } 12425 12426 if (!MagicValues) 12427 return false; 12428 12429 llvm::DenseMap<Sema::TypeTagMagicValue, 12430 Sema::TypeTagData>::const_iterator I = 12431 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12432 if (I == MagicValues->end()) 12433 return false; 12434 12435 TypeInfo = I->second; 12436 return true; 12437 } 12438 12439 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12440 uint64_t MagicValue, QualType Type, 12441 bool LayoutCompatible, 12442 bool MustBeNull) { 12443 if (!TypeTagForDatatypeMagicValues) 12444 TypeTagForDatatypeMagicValues.reset( 12445 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12446 12447 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12448 (*TypeTagForDatatypeMagicValues)[Magic] = 12449 TypeTagData(Type, LayoutCompatible, MustBeNull); 12450 } 12451 12452 static bool IsSameCharType(QualType T1, QualType T2) { 12453 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12454 if (!BT1) 12455 return false; 12456 12457 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12458 if (!BT2) 12459 return false; 12460 12461 BuiltinType::Kind T1Kind = BT1->getKind(); 12462 BuiltinType::Kind T2Kind = BT2->getKind(); 12463 12464 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12465 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12466 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12467 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12468 } 12469 12470 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12471 const ArrayRef<const Expr *> ExprArgs, 12472 SourceLocation CallSiteLoc) { 12473 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12474 bool IsPointerAttr = Attr->getIsPointer(); 12475 12476 // Retrieve the argument representing the 'type_tag'. 12477 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 12478 if (TypeTagIdxAST >= ExprArgs.size()) { 12479 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12480 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 12481 return; 12482 } 12483 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 12484 bool FoundWrongKind; 12485 TypeTagData TypeInfo; 12486 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12487 TypeTagForDatatypeMagicValues.get(), 12488 FoundWrongKind, TypeInfo)) { 12489 if (FoundWrongKind) 12490 Diag(TypeTagExpr->getExprLoc(), 12491 diag::warn_type_tag_for_datatype_wrong_kind) 12492 << TypeTagExpr->getSourceRange(); 12493 return; 12494 } 12495 12496 // Retrieve the argument representing the 'arg_idx'. 12497 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 12498 if (ArgumentIdxAST >= ExprArgs.size()) { 12499 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12500 << 1 << Attr->getArgumentIdx().getSourceIndex(); 12501 return; 12502 } 12503 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 12504 if (IsPointerAttr) { 12505 // Skip implicit cast of pointer to `void *' (as a function argument). 12506 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12507 if (ICE->getType()->isVoidPointerType() && 12508 ICE->getCastKind() == CK_BitCast) 12509 ArgumentExpr = ICE->getSubExpr(); 12510 } 12511 QualType ArgumentType = ArgumentExpr->getType(); 12512 12513 // Passing a `void*' pointer shouldn't trigger a warning. 12514 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12515 return; 12516 12517 if (TypeInfo.MustBeNull) { 12518 // Type tag with matching void type requires a null pointer. 12519 if (!ArgumentExpr->isNullPointerConstant(Context, 12520 Expr::NPC_ValueDependentIsNotNull)) { 12521 Diag(ArgumentExpr->getExprLoc(), 12522 diag::warn_type_safety_null_pointer_required) 12523 << ArgumentKind->getName() 12524 << ArgumentExpr->getSourceRange() 12525 << TypeTagExpr->getSourceRange(); 12526 } 12527 return; 12528 } 12529 12530 QualType RequiredType = TypeInfo.Type; 12531 if (IsPointerAttr) 12532 RequiredType = Context.getPointerType(RequiredType); 12533 12534 bool mismatch = false; 12535 if (!TypeInfo.LayoutCompatible) { 12536 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12537 12538 // C++11 [basic.fundamental] p1: 12539 // Plain char, signed char, and unsigned char are three distinct types. 12540 // 12541 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12542 // char' depending on the current char signedness mode. 12543 if (mismatch) 12544 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12545 RequiredType->getPointeeType())) || 12546 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12547 mismatch = false; 12548 } else 12549 if (IsPointerAttr) 12550 mismatch = !isLayoutCompatible(Context, 12551 ArgumentType->getPointeeType(), 12552 RequiredType->getPointeeType()); 12553 else 12554 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12555 12556 if (mismatch) 12557 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12558 << ArgumentType << ArgumentKind 12559 << TypeInfo.LayoutCompatible << RequiredType 12560 << ArgumentExpr->getSourceRange() 12561 << TypeTagExpr->getSourceRange(); 12562 } 12563 12564 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12565 CharUnits Alignment) { 12566 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12567 } 12568 12569 void Sema::DiagnoseMisalignedMembers() { 12570 for (MisalignedMember &m : MisalignedMembers) { 12571 const NamedDecl *ND = m.RD; 12572 if (ND->getName().empty()) { 12573 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12574 ND = TD; 12575 } 12576 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12577 << m.MD << ND << m.E->getSourceRange(); 12578 } 12579 MisalignedMembers.clear(); 12580 } 12581 12582 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12583 E = E->IgnoreParens(); 12584 if (!T->isPointerType() && !T->isIntegerType()) 12585 return; 12586 if (isa<UnaryOperator>(E) && 12587 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 12588 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 12589 if (isa<MemberExpr>(Op)) { 12590 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 12591 MisalignedMember(Op)); 12592 if (MA != MisalignedMembers.end() && 12593 (T->isIntegerType() || 12594 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 12595 Context.getTypeAlignInChars( 12596 T->getPointeeType()) <= MA->Alignment)))) 12597 MisalignedMembers.erase(MA); 12598 } 12599 } 12600 } 12601 12602 void Sema::RefersToMemberWithReducedAlignment( 12603 Expr *E, 12604 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12605 Action) { 12606 const auto *ME = dyn_cast<MemberExpr>(E); 12607 if (!ME) 12608 return; 12609 12610 // No need to check expressions with an __unaligned-qualified type. 12611 if (E->getType().getQualifiers().hasUnaligned()) 12612 return; 12613 12614 // For a chain of MemberExpr like "a.b.c.d" this list 12615 // will keep FieldDecl's like [d, c, b]. 12616 SmallVector<FieldDecl *, 4> ReverseMemberChain; 12617 const MemberExpr *TopME = nullptr; 12618 bool AnyIsPacked = false; 12619 do { 12620 QualType BaseType = ME->getBase()->getType(); 12621 if (ME->isArrow()) 12622 BaseType = BaseType->getPointeeType(); 12623 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 12624 if (RD->isInvalidDecl()) 12625 return; 12626 12627 ValueDecl *MD = ME->getMemberDecl(); 12628 auto *FD = dyn_cast<FieldDecl>(MD); 12629 // We do not care about non-data members. 12630 if (!FD || FD->isInvalidDecl()) 12631 return; 12632 12633 AnyIsPacked = 12634 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 12635 ReverseMemberChain.push_back(FD); 12636 12637 TopME = ME; 12638 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 12639 } while (ME); 12640 assert(TopME && "We did not compute a topmost MemberExpr!"); 12641 12642 // Not the scope of this diagnostic. 12643 if (!AnyIsPacked) 12644 return; 12645 12646 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 12647 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 12648 // TODO: The innermost base of the member expression may be too complicated. 12649 // For now, just disregard these cases. This is left for future 12650 // improvement. 12651 if (!DRE && !isa<CXXThisExpr>(TopBase)) 12652 return; 12653 12654 // Alignment expected by the whole expression. 12655 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 12656 12657 // No need to do anything else with this case. 12658 if (ExpectedAlignment.isOne()) 12659 return; 12660 12661 // Synthesize offset of the whole access. 12662 CharUnits Offset; 12663 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 12664 I++) { 12665 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 12666 } 12667 12668 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 12669 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 12670 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 12671 12672 // The base expression of the innermost MemberExpr may give 12673 // stronger guarantees than the class containing the member. 12674 if (DRE && !TopME->isArrow()) { 12675 const ValueDecl *VD = DRE->getDecl(); 12676 if (!VD->getType()->isReferenceType()) 12677 CompleteObjectAlignment = 12678 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 12679 } 12680 12681 // Check if the synthesized offset fulfills the alignment. 12682 if (Offset % ExpectedAlignment != 0 || 12683 // It may fulfill the offset it but the effective alignment may still be 12684 // lower than the expected expression alignment. 12685 CompleteObjectAlignment < ExpectedAlignment) { 12686 // If this happens, we want to determine a sensible culprit of this. 12687 // Intuitively, watching the chain of member expressions from right to 12688 // left, we start with the required alignment (as required by the field 12689 // type) but some packed attribute in that chain has reduced the alignment. 12690 // It may happen that another packed structure increases it again. But if 12691 // we are here such increase has not been enough. So pointing the first 12692 // FieldDecl that either is packed or else its RecordDecl is, 12693 // seems reasonable. 12694 FieldDecl *FD = nullptr; 12695 CharUnits Alignment; 12696 for (FieldDecl *FDI : ReverseMemberChain) { 12697 if (FDI->hasAttr<PackedAttr>() || 12698 FDI->getParent()->hasAttr<PackedAttr>()) { 12699 FD = FDI; 12700 Alignment = std::min( 12701 Context.getTypeAlignInChars(FD->getType()), 12702 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 12703 break; 12704 } 12705 } 12706 assert(FD && "We did not find a packed FieldDecl!"); 12707 Action(E, FD->getParent(), FD, Alignment); 12708 } 12709 } 12710 12711 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 12712 using namespace std::placeholders; 12713 12714 RefersToMemberWithReducedAlignment( 12715 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 12716 _2, _3, _4)); 12717 } 12718