1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements extra semantic analysis beyond what is enforced
11 // by the C type system.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallBitVector.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/Support/ConvertUTF.h"
39 #include "llvm/Support/raw_ostream.h"
41 using namespace clang;
44 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
46 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
50 /// Checks that a call expression's argument count is the desired number.
51 /// This is useful when doing custom type-checking. Returns true on error.
52 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
70 /// Check that the first argument to __builtin_annotation is an integer
71 /// and the second argument is a non-wide string literal.
72 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
98 /// Check that the argument to __builtin_addressof is a glvalue, and set the
99 /// result type to the corresponding pointer type.
100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
104 ExprResult Arg(TheCall->getArg(0));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
109 TheCall->setArg(0, Arg.get());
110 TheCall->setType(ResultType);
114 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
124 llvm::APSInt Size, DstSize;
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
131 if (Size.ule(DstSize))
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
142 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143 if (checkArgCount(S, BuiltinCall, 2))
146 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148 Expr *Call = BuiltinCall->getArg(0);
149 Expr *Chain = BuiltinCall->getArg(1);
151 if (Call->getStmtClass() != Stmt::CallExprClass) {
152 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153 << Call->getSourceRange();
157 auto CE = cast<CallExpr>(Call);
158 if (CE->getCallee()->getType()->isBlockPointerType()) {
159 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160 << Call->getSourceRange();
164 const Decl *TargetDecl = CE->getCalleeDecl();
165 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166 if (FD->getBuiltinID()) {
167 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168 << Call->getSourceRange();
172 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174 << Call->getSourceRange();
178 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179 if (ChainResult.isInvalid())
181 if (!ChainResult.get()->getType()->isPointerType()) {
182 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183 << Chain->getSourceRange();
187 QualType ReturnTy = CE->getCallReturnType(S.Context);
188 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
189 QualType BuiltinTy = S.Context.getFunctionType(
190 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
191 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
194 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
196 BuiltinCall->setType(CE->getType());
197 BuiltinCall->setValueKind(CE->getValueKind());
198 BuiltinCall->setObjectKind(CE->getObjectKind());
199 BuiltinCall->setCallee(Builtin);
200 BuiltinCall->setArg(1, ChainResult.get());
205 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
206 Scope::ScopeFlags NeededScopeFlags,
208 // Scopes aren't available during instantiation. Fortunately, builtin
209 // functions cannot be template args so they cannot be formed through template
210 // instantiation. Therefore checking once during the parse is sufficient.
211 if (!SemaRef.ActiveTemplateInstantiations.empty())
214 Scope *S = SemaRef.getCurScope();
215 while (S && !S->isSEHExceptScope())
217 if (!S || !(S->getFlags() & NeededScopeFlags)) {
218 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
219 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
220 << DRE->getDecl()->getIdentifier();
228 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
230 ExprResult TheCallResult(TheCall);
232 // Find out if any arguments are required to be integer constant expressions.
233 unsigned ICEArguments = 0;
234 ASTContext::GetBuiltinTypeError Error;
235 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
236 if (Error != ASTContext::GE_None)
237 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
239 // If any arguments are required to be ICE's, check and diagnose.
240 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
241 // Skip arguments not required to be ICE's.
242 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
247 ICEArguments &= ~(1 << ArgNo);
251 case Builtin::BI__builtin___CFStringMakeConstantString:
252 assert(TheCall->getNumArgs() == 1 &&
253 "Wrong # arguments to builtin CFStringMakeConstantString");
254 if (CheckObjCString(TheCall->getArg(0)))
257 case Builtin::BI__builtin_stdarg_start:
258 case Builtin::BI__builtin_va_start:
259 if (SemaBuiltinVAStart(TheCall))
262 case Builtin::BI__va_start: {
263 switch (Context.getTargetInfo().getTriple().getArch()) {
264 case llvm::Triple::arm:
265 case llvm::Triple::thumb:
266 if (SemaBuiltinVAStartARM(TheCall))
270 if (SemaBuiltinVAStart(TheCall))
276 case Builtin::BI__builtin_isgreater:
277 case Builtin::BI__builtin_isgreaterequal:
278 case Builtin::BI__builtin_isless:
279 case Builtin::BI__builtin_islessequal:
280 case Builtin::BI__builtin_islessgreater:
281 case Builtin::BI__builtin_isunordered:
282 if (SemaBuiltinUnorderedCompare(TheCall))
285 case Builtin::BI__builtin_fpclassify:
286 if (SemaBuiltinFPClassification(TheCall, 6))
289 case Builtin::BI__builtin_isfinite:
290 case Builtin::BI__builtin_isinf:
291 case Builtin::BI__builtin_isinf_sign:
292 case Builtin::BI__builtin_isnan:
293 case Builtin::BI__builtin_isnormal:
294 if (SemaBuiltinFPClassification(TheCall, 1))
297 case Builtin::BI__builtin_shufflevector:
298 return SemaBuiltinShuffleVector(TheCall);
299 // TheCall will be freed by the smart pointer here, but that's fine, since
300 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
301 case Builtin::BI__builtin_prefetch:
302 if (SemaBuiltinPrefetch(TheCall))
305 case Builtin::BI__assume:
306 case Builtin::BI__builtin_assume:
307 if (SemaBuiltinAssume(TheCall))
310 case Builtin::BI__builtin_assume_aligned:
311 if (SemaBuiltinAssumeAligned(TheCall))
314 case Builtin::BI__builtin_object_size:
315 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
318 case Builtin::BI__builtin_longjmp:
319 if (SemaBuiltinLongjmp(TheCall))
322 case Builtin::BI__builtin_setjmp:
323 if (SemaBuiltinSetjmp(TheCall))
326 case Builtin::BI_setjmp:
327 case Builtin::BI_setjmpex:
328 if (checkArgCount(*this, TheCall, 1))
332 case Builtin::BI__builtin_classify_type:
333 if (checkArgCount(*this, TheCall, 1)) return true;
334 TheCall->setType(Context.IntTy);
336 case Builtin::BI__builtin_constant_p:
337 if (checkArgCount(*this, TheCall, 1)) return true;
338 TheCall->setType(Context.IntTy);
340 case Builtin::BI__sync_fetch_and_add:
341 case Builtin::BI__sync_fetch_and_add_1:
342 case Builtin::BI__sync_fetch_and_add_2:
343 case Builtin::BI__sync_fetch_and_add_4:
344 case Builtin::BI__sync_fetch_and_add_8:
345 case Builtin::BI__sync_fetch_and_add_16:
346 case Builtin::BI__sync_fetch_and_sub:
347 case Builtin::BI__sync_fetch_and_sub_1:
348 case Builtin::BI__sync_fetch_and_sub_2:
349 case Builtin::BI__sync_fetch_and_sub_4:
350 case Builtin::BI__sync_fetch_and_sub_8:
351 case Builtin::BI__sync_fetch_and_sub_16:
352 case Builtin::BI__sync_fetch_and_or:
353 case Builtin::BI__sync_fetch_and_or_1:
354 case Builtin::BI__sync_fetch_and_or_2:
355 case Builtin::BI__sync_fetch_and_or_4:
356 case Builtin::BI__sync_fetch_and_or_8:
357 case Builtin::BI__sync_fetch_and_or_16:
358 case Builtin::BI__sync_fetch_and_and:
359 case Builtin::BI__sync_fetch_and_and_1:
360 case Builtin::BI__sync_fetch_and_and_2:
361 case Builtin::BI__sync_fetch_and_and_4:
362 case Builtin::BI__sync_fetch_and_and_8:
363 case Builtin::BI__sync_fetch_and_and_16:
364 case Builtin::BI__sync_fetch_and_xor:
365 case Builtin::BI__sync_fetch_and_xor_1:
366 case Builtin::BI__sync_fetch_and_xor_2:
367 case Builtin::BI__sync_fetch_and_xor_4:
368 case Builtin::BI__sync_fetch_and_xor_8:
369 case Builtin::BI__sync_fetch_and_xor_16:
370 case Builtin::BI__sync_fetch_and_nand:
371 case Builtin::BI__sync_fetch_and_nand_1:
372 case Builtin::BI__sync_fetch_and_nand_2:
373 case Builtin::BI__sync_fetch_and_nand_4:
374 case Builtin::BI__sync_fetch_and_nand_8:
375 case Builtin::BI__sync_fetch_and_nand_16:
376 case Builtin::BI__sync_add_and_fetch:
377 case Builtin::BI__sync_add_and_fetch_1:
378 case Builtin::BI__sync_add_and_fetch_2:
379 case Builtin::BI__sync_add_and_fetch_4:
380 case Builtin::BI__sync_add_and_fetch_8:
381 case Builtin::BI__sync_add_and_fetch_16:
382 case Builtin::BI__sync_sub_and_fetch:
383 case Builtin::BI__sync_sub_and_fetch_1:
384 case Builtin::BI__sync_sub_and_fetch_2:
385 case Builtin::BI__sync_sub_and_fetch_4:
386 case Builtin::BI__sync_sub_and_fetch_8:
387 case Builtin::BI__sync_sub_and_fetch_16:
388 case Builtin::BI__sync_and_and_fetch:
389 case Builtin::BI__sync_and_and_fetch_1:
390 case Builtin::BI__sync_and_and_fetch_2:
391 case Builtin::BI__sync_and_and_fetch_4:
392 case Builtin::BI__sync_and_and_fetch_8:
393 case Builtin::BI__sync_and_and_fetch_16:
394 case Builtin::BI__sync_or_and_fetch:
395 case Builtin::BI__sync_or_and_fetch_1:
396 case Builtin::BI__sync_or_and_fetch_2:
397 case Builtin::BI__sync_or_and_fetch_4:
398 case Builtin::BI__sync_or_and_fetch_8:
399 case Builtin::BI__sync_or_and_fetch_16:
400 case Builtin::BI__sync_xor_and_fetch:
401 case Builtin::BI__sync_xor_and_fetch_1:
402 case Builtin::BI__sync_xor_and_fetch_2:
403 case Builtin::BI__sync_xor_and_fetch_4:
404 case Builtin::BI__sync_xor_and_fetch_8:
405 case Builtin::BI__sync_xor_and_fetch_16:
406 case Builtin::BI__sync_nand_and_fetch:
407 case Builtin::BI__sync_nand_and_fetch_1:
408 case Builtin::BI__sync_nand_and_fetch_2:
409 case Builtin::BI__sync_nand_and_fetch_4:
410 case Builtin::BI__sync_nand_and_fetch_8:
411 case Builtin::BI__sync_nand_and_fetch_16:
412 case Builtin::BI__sync_val_compare_and_swap:
413 case Builtin::BI__sync_val_compare_and_swap_1:
414 case Builtin::BI__sync_val_compare_and_swap_2:
415 case Builtin::BI__sync_val_compare_and_swap_4:
416 case Builtin::BI__sync_val_compare_and_swap_8:
417 case Builtin::BI__sync_val_compare_and_swap_16:
418 case Builtin::BI__sync_bool_compare_and_swap:
419 case Builtin::BI__sync_bool_compare_and_swap_1:
420 case Builtin::BI__sync_bool_compare_and_swap_2:
421 case Builtin::BI__sync_bool_compare_and_swap_4:
422 case Builtin::BI__sync_bool_compare_and_swap_8:
423 case Builtin::BI__sync_bool_compare_and_swap_16:
424 case Builtin::BI__sync_lock_test_and_set:
425 case Builtin::BI__sync_lock_test_and_set_1:
426 case Builtin::BI__sync_lock_test_and_set_2:
427 case Builtin::BI__sync_lock_test_and_set_4:
428 case Builtin::BI__sync_lock_test_and_set_8:
429 case Builtin::BI__sync_lock_test_and_set_16:
430 case Builtin::BI__sync_lock_release:
431 case Builtin::BI__sync_lock_release_1:
432 case Builtin::BI__sync_lock_release_2:
433 case Builtin::BI__sync_lock_release_4:
434 case Builtin::BI__sync_lock_release_8:
435 case Builtin::BI__sync_lock_release_16:
436 case Builtin::BI__sync_swap:
437 case Builtin::BI__sync_swap_1:
438 case Builtin::BI__sync_swap_2:
439 case Builtin::BI__sync_swap_4:
440 case Builtin::BI__sync_swap_8:
441 case Builtin::BI__sync_swap_16:
442 return SemaBuiltinAtomicOverloaded(TheCallResult);
443 #define BUILTIN(ID, TYPE, ATTRS)
444 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
445 case Builtin::BI##ID: \
446 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
447 #include "clang/Basic/Builtins.def"
448 case Builtin::BI__builtin_annotation:
449 if (SemaBuiltinAnnotation(*this, TheCall))
452 case Builtin::BI__builtin_addressof:
453 if (SemaBuiltinAddressof(*this, TheCall))
456 case Builtin::BI__builtin_operator_new:
457 case Builtin::BI__builtin_operator_delete:
458 if (!getLangOpts().CPlusPlus) {
459 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
460 << (BuiltinID == Builtin::BI__builtin_operator_new
461 ? "__builtin_operator_new"
462 : "__builtin_operator_delete")
466 // CodeGen assumes it can find the global new and delete to call,
467 // so ensure that they are declared.
468 DeclareGlobalNewDelete();
471 // check secure string manipulation functions where overflows
472 // are detectable at compile time
473 case Builtin::BI__builtin___memcpy_chk:
474 case Builtin::BI__builtin___memmove_chk:
475 case Builtin::BI__builtin___memset_chk:
476 case Builtin::BI__builtin___strlcat_chk:
477 case Builtin::BI__builtin___strlcpy_chk:
478 case Builtin::BI__builtin___strncat_chk:
479 case Builtin::BI__builtin___strncpy_chk:
480 case Builtin::BI__builtin___stpncpy_chk:
481 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
483 case Builtin::BI__builtin___memccpy_chk:
484 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
486 case Builtin::BI__builtin___snprintf_chk:
487 case Builtin::BI__builtin___vsnprintf_chk:
488 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
491 case Builtin::BI__builtin_call_with_static_chain:
492 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
496 case Builtin::BI__exception_code:
497 case Builtin::BI_exception_code: {
498 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
499 diag::err_seh___except_block))
503 case Builtin::BI__exception_info:
504 case Builtin::BI_exception_info: {
505 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
506 diag::err_seh___except_filter))
511 case Builtin::BI__GetExceptionInfo:
512 if (checkArgCount(*this, TheCall, 1))
515 if (CheckCXXThrowOperand(
516 TheCall->getLocStart(),
517 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
521 TheCall->setType(Context.VoidPtrTy);
526 // Since the target specific builtins for each arch overlap, only check those
527 // of the arch we are compiling for.
528 if (BuiltinID >= Builtin::FirstTSBuiltin) {
529 switch (Context.getTargetInfo().getTriple().getArch()) {
530 case llvm::Triple::arm:
531 case llvm::Triple::armeb:
532 case llvm::Triple::thumb:
533 case llvm::Triple::thumbeb:
534 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
537 case llvm::Triple::aarch64:
538 case llvm::Triple::aarch64_be:
539 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
542 case llvm::Triple::mips:
543 case llvm::Triple::mipsel:
544 case llvm::Triple::mips64:
545 case llvm::Triple::mips64el:
546 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
549 case llvm::Triple::systemz:
550 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
553 case llvm::Triple::x86:
554 case llvm::Triple::x86_64:
555 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
558 case llvm::Triple::ppc:
559 case llvm::Triple::ppc64:
560 case llvm::Triple::ppc64le:
561 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
569 return TheCallResult;
572 // Get the valid immediate range for the specified NEON type code.
573 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
574 NeonTypeFlags Type(t);
575 int IsQuad = ForceQuad ? true : Type.isQuad();
576 switch (Type.getEltType()) {
577 case NeonTypeFlags::Int8:
578 case NeonTypeFlags::Poly8:
579 return shift ? 7 : (8 << IsQuad) - 1;
580 case NeonTypeFlags::Int16:
581 case NeonTypeFlags::Poly16:
582 return shift ? 15 : (4 << IsQuad) - 1;
583 case NeonTypeFlags::Int32:
584 return shift ? 31 : (2 << IsQuad) - 1;
585 case NeonTypeFlags::Int64:
586 case NeonTypeFlags::Poly64:
587 return shift ? 63 : (1 << IsQuad) - 1;
588 case NeonTypeFlags::Poly128:
589 return shift ? 127 : (1 << IsQuad) - 1;
590 case NeonTypeFlags::Float16:
591 assert(!shift && "cannot shift float types!");
592 return (4 << IsQuad) - 1;
593 case NeonTypeFlags::Float32:
594 assert(!shift && "cannot shift float types!");
595 return (2 << IsQuad) - 1;
596 case NeonTypeFlags::Float64:
597 assert(!shift && "cannot shift float types!");
598 return (1 << IsQuad) - 1;
600 llvm_unreachable("Invalid NeonTypeFlag!");
603 /// getNeonEltType - Return the QualType corresponding to the elements of
604 /// the vector type specified by the NeonTypeFlags. This is used to check
605 /// the pointer arguments for Neon load/store intrinsics.
606 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
607 bool IsPolyUnsigned, bool IsInt64Long) {
608 switch (Flags.getEltType()) {
609 case NeonTypeFlags::Int8:
610 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
611 case NeonTypeFlags::Int16:
612 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
613 case NeonTypeFlags::Int32:
614 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
615 case NeonTypeFlags::Int64:
617 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
619 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
620 : Context.LongLongTy;
621 case NeonTypeFlags::Poly8:
622 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
623 case NeonTypeFlags::Poly16:
624 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
625 case NeonTypeFlags::Poly64:
627 return Context.UnsignedLongTy;
629 return Context.UnsignedLongLongTy;
630 case NeonTypeFlags::Poly128:
632 case NeonTypeFlags::Float16:
633 return Context.HalfTy;
634 case NeonTypeFlags::Float32:
635 return Context.FloatTy;
636 case NeonTypeFlags::Float64:
637 return Context.DoubleTy;
639 llvm_unreachable("Invalid NeonTypeFlag!");
642 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
647 bool HasConstPtr = false;
649 #define GET_NEON_OVERLOAD_CHECK
650 #include "clang/Basic/arm_neon.inc"
651 #undef GET_NEON_OVERLOAD_CHECK
654 // For NEON intrinsics which are overloaded on vector element type, validate
655 // the immediate which specifies which variant to emit.
656 unsigned ImmArg = TheCall->getNumArgs()-1;
658 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
661 TV = Result.getLimitedValue(64);
662 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
663 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
664 << TheCall->getArg(ImmArg)->getSourceRange();
667 if (PtrArgNum >= 0) {
668 // Check that pointer arguments have the specified type.
669 Expr *Arg = TheCall->getArg(PtrArgNum);
670 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
671 Arg = ICE->getSubExpr();
672 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
673 QualType RHSTy = RHS.get()->getType();
675 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
676 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
678 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
680 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
682 EltTy = EltTy.withConst();
683 QualType LHSTy = Context.getPointerType(EltTy);
684 AssignConvertType ConvTy;
685 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
688 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
689 RHS.get(), AA_Assigning))
693 // For NEON intrinsics which take an immediate value as part of the
694 // instruction, range check them here.
695 unsigned i = 0, l = 0, u = 0;
699 #define GET_NEON_IMMEDIATE_CHECK
700 #include "clang/Basic/arm_neon.inc"
701 #undef GET_NEON_IMMEDIATE_CHECK
704 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
707 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
709 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
710 BuiltinID == ARM::BI__builtin_arm_ldaex ||
711 BuiltinID == ARM::BI__builtin_arm_strex ||
712 BuiltinID == ARM::BI__builtin_arm_stlex ||
713 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
714 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
715 BuiltinID == AArch64::BI__builtin_arm_strex ||
716 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
717 "unexpected ARM builtin");
718 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
719 BuiltinID == ARM::BI__builtin_arm_ldaex ||
720 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
721 BuiltinID == AArch64::BI__builtin_arm_ldaex;
723 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
725 // Ensure that we have the proper number of arguments.
726 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
729 // Inspect the pointer argument of the atomic builtin. This should always be
730 // a pointer type, whose element is an integral scalar or pointer type.
731 // Because it is a pointer type, we don't have to worry about any implicit
733 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
734 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
735 if (PointerArgRes.isInvalid())
737 PointerArg = PointerArgRes.get();
739 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
741 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
742 << PointerArg->getType() << PointerArg->getSourceRange();
746 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
747 // task is to insert the appropriate casts into the AST. First work out just
748 // what the appropriate type is.
749 QualType ValType = pointerType->getPointeeType();
750 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
754 // Issue a warning if the cast is dodgy.
755 CastKind CastNeeded = CK_NoOp;
756 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
757 CastNeeded = CK_BitCast;
758 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
759 << PointerArg->getType()
760 << Context.getPointerType(AddrType)
761 << AA_Passing << PointerArg->getSourceRange();
764 // Finally, do the cast and replace the argument with the corrected version.
765 AddrType = Context.getPointerType(AddrType);
766 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
767 if (PointerArgRes.isInvalid())
769 PointerArg = PointerArgRes.get();
771 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
773 // In general, we allow ints, floats and pointers to be loaded and stored.
774 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
775 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
776 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
777 << PointerArg->getType() << PointerArg->getSourceRange();
781 // But ARM doesn't have instructions to deal with 128-bit versions.
782 if (Context.getTypeSize(ValType) > MaxWidth) {
783 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
784 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
785 << PointerArg->getType() << PointerArg->getSourceRange();
789 switch (ValType.getObjCLifetime()) {
790 case Qualifiers::OCL_None:
791 case Qualifiers::OCL_ExplicitNone:
795 case Qualifiers::OCL_Weak:
796 case Qualifiers::OCL_Strong:
797 case Qualifiers::OCL_Autoreleasing:
798 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
799 << ValType << PointerArg->getSourceRange();
805 TheCall->setType(ValType);
809 // Initialize the argument to be stored.
810 ExprResult ValArg = TheCall->getArg(0);
811 InitializedEntity Entity = InitializedEntity::InitializeParameter(
812 Context, ValType, /*consume*/ false);
813 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
814 if (ValArg.isInvalid())
816 TheCall->setArg(0, ValArg.get());
818 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
819 // but the custom checker bypasses all default analysis.
820 TheCall->setType(Context.IntTy);
824 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
827 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
828 BuiltinID == ARM::BI__builtin_arm_ldaex ||
829 BuiltinID == ARM::BI__builtin_arm_strex ||
830 BuiltinID == ARM::BI__builtin_arm_stlex) {
831 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
834 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
835 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
836 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
839 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
840 BuiltinID == ARM::BI__builtin_arm_wsr64)
841 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
843 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
844 BuiltinID == ARM::BI__builtin_arm_rsrp ||
845 BuiltinID == ARM::BI__builtin_arm_wsr ||
846 BuiltinID == ARM::BI__builtin_arm_wsrp)
847 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
849 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
852 // For intrinsics which take an immediate value as part of the instruction,
853 // range check them here.
854 unsigned i = 0, l = 0, u = 0;
856 default: return false;
857 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
858 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
859 case ARM::BI__builtin_arm_vcvtr_f:
860 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
861 case ARM::BI__builtin_arm_dmb:
862 case ARM::BI__builtin_arm_dsb:
863 case ARM::BI__builtin_arm_isb:
864 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
867 // FIXME: VFP Intrinsics should error if VFP not present.
868 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
871 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
875 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
876 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
877 BuiltinID == AArch64::BI__builtin_arm_strex ||
878 BuiltinID == AArch64::BI__builtin_arm_stlex) {
879 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
882 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
883 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
884 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
885 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
886 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
889 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
890 BuiltinID == AArch64::BI__builtin_arm_wsr64)
891 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
893 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
894 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
895 BuiltinID == AArch64::BI__builtin_arm_wsr ||
896 BuiltinID == AArch64::BI__builtin_arm_wsrp)
897 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
899 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
902 // For intrinsics which take an immediate value as part of the instruction,
903 // range check them here.
904 unsigned i = 0, l = 0, u = 0;
906 default: return false;
907 case AArch64::BI__builtin_arm_dmb:
908 case AArch64::BI__builtin_arm_dsb:
909 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
912 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
915 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
916 unsigned i = 0, l = 0, u = 0;
918 default: return false;
919 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
920 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
921 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
922 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
923 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
924 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
925 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
928 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
931 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
932 unsigned i = 0, l = 0, u = 0;
933 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
934 BuiltinID == PPC::BI__builtin_divdeu ||
935 BuiltinID == PPC::BI__builtin_bpermd;
936 bool IsTarget64Bit = Context.getTargetInfo()
937 .getTypeWidth(Context
939 .getIntPtrType()) == 64;
940 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
941 BuiltinID == PPC::BI__builtin_divweu ||
942 BuiltinID == PPC::BI__builtin_divde ||
943 BuiltinID == PPC::BI__builtin_divdeu;
945 if (Is64BitBltin && !IsTarget64Bit)
946 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
947 << TheCall->getSourceRange();
949 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
950 (BuiltinID == PPC::BI__builtin_bpermd &&
951 !Context.getTargetInfo().hasFeature("bpermd")))
952 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
953 << TheCall->getSourceRange();
956 default: return false;
957 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
958 case PPC::BI__builtin_altivec_crypto_vshasigmad:
959 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
960 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
961 case PPC::BI__builtin_tbegin:
962 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
963 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
964 case PPC::BI__builtin_tabortwc:
965 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
966 case PPC::BI__builtin_tabortwci:
967 case PPC::BI__builtin_tabortdci:
968 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
969 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
971 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
974 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
976 if (BuiltinID == SystemZ::BI__builtin_tabort) {
977 Expr *Arg = TheCall->getArg(0);
978 llvm::APSInt AbortCode(32);
979 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
980 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
981 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
982 << Arg->getSourceRange();
985 // For intrinsics which take an immediate value as part of the instruction,
986 // range check them here.
987 unsigned i = 0, l = 0, u = 0;
989 default: return false;
990 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
991 case SystemZ::BI__builtin_s390_verimb:
992 case SystemZ::BI__builtin_s390_verimh:
993 case SystemZ::BI__builtin_s390_verimf:
994 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
995 case SystemZ::BI__builtin_s390_vfaeb:
996 case SystemZ::BI__builtin_s390_vfaeh:
997 case SystemZ::BI__builtin_s390_vfaef:
998 case SystemZ::BI__builtin_s390_vfaebs:
999 case SystemZ::BI__builtin_s390_vfaehs:
1000 case SystemZ::BI__builtin_s390_vfaefs:
1001 case SystemZ::BI__builtin_s390_vfaezb:
1002 case SystemZ::BI__builtin_s390_vfaezh:
1003 case SystemZ::BI__builtin_s390_vfaezf:
1004 case SystemZ::BI__builtin_s390_vfaezbs:
1005 case SystemZ::BI__builtin_s390_vfaezhs:
1006 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1007 case SystemZ::BI__builtin_s390_vfidb:
1008 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1009 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1010 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1011 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1012 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1013 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1014 case SystemZ::BI__builtin_s390_vstrcb:
1015 case SystemZ::BI__builtin_s390_vstrch:
1016 case SystemZ::BI__builtin_s390_vstrcf:
1017 case SystemZ::BI__builtin_s390_vstrczb:
1018 case SystemZ::BI__builtin_s390_vstrczh:
1019 case SystemZ::BI__builtin_s390_vstrczf:
1020 case SystemZ::BI__builtin_s390_vstrcbs:
1021 case SystemZ::BI__builtin_s390_vstrchs:
1022 case SystemZ::BI__builtin_s390_vstrcfs:
1023 case SystemZ::BI__builtin_s390_vstrczbs:
1024 case SystemZ::BI__builtin_s390_vstrczhs:
1025 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1027 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1030 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1031 unsigned i = 0, l = 0, u = 0;
1032 switch (BuiltinID) {
1033 default: return false;
1034 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
1035 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
1036 case X86::BI__builtin_ia32_vpermil2pd:
1037 case X86::BI__builtin_ia32_vpermil2pd256:
1038 case X86::BI__builtin_ia32_vpermil2ps:
1039 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
1040 case X86::BI__builtin_ia32_cmpb128_mask:
1041 case X86::BI__builtin_ia32_cmpw128_mask:
1042 case X86::BI__builtin_ia32_cmpd128_mask:
1043 case X86::BI__builtin_ia32_cmpq128_mask:
1044 case X86::BI__builtin_ia32_cmpb256_mask:
1045 case X86::BI__builtin_ia32_cmpw256_mask:
1046 case X86::BI__builtin_ia32_cmpd256_mask:
1047 case X86::BI__builtin_ia32_cmpq256_mask:
1048 case X86::BI__builtin_ia32_cmpb512_mask:
1049 case X86::BI__builtin_ia32_cmpw512_mask:
1050 case X86::BI__builtin_ia32_cmpd512_mask:
1051 case X86::BI__builtin_ia32_cmpq512_mask:
1052 case X86::BI__builtin_ia32_ucmpb128_mask:
1053 case X86::BI__builtin_ia32_ucmpw128_mask:
1054 case X86::BI__builtin_ia32_ucmpd128_mask:
1055 case X86::BI__builtin_ia32_ucmpq128_mask:
1056 case X86::BI__builtin_ia32_ucmpb256_mask:
1057 case X86::BI__builtin_ia32_ucmpw256_mask:
1058 case X86::BI__builtin_ia32_ucmpd256_mask:
1059 case X86::BI__builtin_ia32_ucmpq256_mask:
1060 case X86::BI__builtin_ia32_ucmpb512_mask:
1061 case X86::BI__builtin_ia32_ucmpw512_mask:
1062 case X86::BI__builtin_ia32_ucmpd512_mask:
1063 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
1064 case X86::BI__builtin_ia32_roundps:
1065 case X86::BI__builtin_ia32_roundpd:
1066 case X86::BI__builtin_ia32_roundps256:
1067 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1068 case X86::BI__builtin_ia32_roundss:
1069 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1070 case X86::BI__builtin_ia32_cmpps:
1071 case X86::BI__builtin_ia32_cmpss:
1072 case X86::BI__builtin_ia32_cmppd:
1073 case X86::BI__builtin_ia32_cmpsd:
1074 case X86::BI__builtin_ia32_cmpps256:
1075 case X86::BI__builtin_ia32_cmppd256:
1076 case X86::BI__builtin_ia32_cmpps512_mask:
1077 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
1078 case X86::BI__builtin_ia32_vpcomub:
1079 case X86::BI__builtin_ia32_vpcomuw:
1080 case X86::BI__builtin_ia32_vpcomud:
1081 case X86::BI__builtin_ia32_vpcomuq:
1082 case X86::BI__builtin_ia32_vpcomb:
1083 case X86::BI__builtin_ia32_vpcomw:
1084 case X86::BI__builtin_ia32_vpcomd:
1085 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
1087 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1090 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1091 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
1092 /// Returns true when the format fits the function and the FormatStringInfo has
1094 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1095 FormatStringInfo *FSI) {
1096 FSI->HasVAListArg = Format->getFirstArg() == 0;
1097 FSI->FormatIdx = Format->getFormatIdx() - 1;
1098 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
1100 // The way the format attribute works in GCC, the implicit this argument
1101 // of member functions is counted. However, it doesn't appear in our own
1102 // lists, so decrement format_idx in that case.
1104 if(FSI->FormatIdx == 0)
1107 if (FSI->FirstDataArg != 0)
1108 --FSI->FirstDataArg;
1113 /// Checks if a the given expression evaluates to null.
1115 /// \brief Returns true if the value evaluates to null.
1116 static bool CheckNonNullExpr(Sema &S,
1118 // If the expression has non-null type, it doesn't evaluate to null.
1119 if (auto nullability
1120 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1121 if (*nullability == NullabilityKind::NonNull)
1125 // As a special case, transparent unions initialized with zero are
1126 // considered null for the purposes of the nonnull attribute.
1127 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
1128 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1129 if (const CompoundLiteralExpr *CLE =
1130 dyn_cast<CompoundLiteralExpr>(Expr))
1131 if (const InitListExpr *ILE =
1132 dyn_cast<InitListExpr>(CLE->getInitializer()))
1133 Expr = ILE->getInit(0);
1137 return (!Expr->isValueDependent() &&
1138 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1142 static void CheckNonNullArgument(Sema &S,
1143 const Expr *ArgExpr,
1144 SourceLocation CallSiteLoc) {
1145 if (CheckNonNullExpr(S, ArgExpr))
1146 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1149 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1150 FormatStringInfo FSI;
1151 if ((GetFormatStringType(Format) == FST_NSString) &&
1152 getFormatStringInfo(Format, false, &FSI)) {
1153 Idx = FSI.FormatIdx;
1158 /// \brief Diagnose use of %s directive in an NSString which is being passed
1159 /// as formatting string to formatting method.
1161 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1162 const NamedDecl *FDecl,
1166 bool Format = false;
1167 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1168 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
1173 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1174 if (S.GetFormatNSStringIdx(I, Idx)) {
1179 if (!Format || NumArgs <= Idx)
1181 const Expr *FormatExpr = Args[Idx];
1182 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1183 FormatExpr = CSCE->getSubExpr();
1184 const StringLiteral *FormatString;
1185 if (const ObjCStringLiteral *OSL =
1186 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1187 FormatString = OSL->getString();
1189 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1192 if (S.FormatStringHasSArg(FormatString)) {
1193 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1195 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1196 << FDecl->getDeclName();
1200 /// Determine whether the given type has a non-null nullability annotation.
1201 static bool isNonNullType(ASTContext &ctx, QualType type) {
1202 if (auto nullability = type->getNullability(ctx))
1203 return *nullability == NullabilityKind::NonNull;
1208 static void CheckNonNullArguments(Sema &S,
1209 const NamedDecl *FDecl,
1210 const FunctionProtoType *Proto,
1211 ArrayRef<const Expr *> Args,
1212 SourceLocation CallSiteLoc) {
1213 assert((FDecl || Proto) && "Need a function declaration or prototype");
1215 // Check the attributes attached to the method/function itself.
1216 llvm::SmallBitVector NonNullArgs;
1218 // Handle the nonnull attribute on the function/method declaration itself.
1219 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1220 if (!NonNull->args_size()) {
1221 // Easy case: all pointer arguments are nonnull.
1222 for (const auto *Arg : Args)
1223 if (S.isValidPointerAttrType(Arg->getType()))
1224 CheckNonNullArgument(S, Arg, CallSiteLoc);
1228 for (unsigned Val : NonNull->args()) {
1229 if (Val >= Args.size())
1231 if (NonNullArgs.empty())
1232 NonNullArgs.resize(Args.size());
1233 NonNullArgs.set(Val);
1238 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1239 // Handle the nonnull attribute on the parameters of the
1241 ArrayRef<ParmVarDecl*> parms;
1242 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1243 parms = FD->parameters();
1245 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1247 unsigned ParamIndex = 0;
1248 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1249 I != E; ++I, ++ParamIndex) {
1250 const ParmVarDecl *PVD = *I;
1251 if (PVD->hasAttr<NonNullAttr>() ||
1252 isNonNullType(S.Context, PVD->getType())) {
1253 if (NonNullArgs.empty())
1254 NonNullArgs.resize(Args.size());
1256 NonNullArgs.set(ParamIndex);
1260 // If we have a non-function, non-method declaration but no
1261 // function prototype, try to dig out the function prototype.
1263 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1264 QualType type = VD->getType().getNonReferenceType();
1265 if (auto pointerType = type->getAs<PointerType>())
1266 type = pointerType->getPointeeType();
1267 else if (auto blockType = type->getAs<BlockPointerType>())
1268 type = blockType->getPointeeType();
1269 // FIXME: data member pointers?
1271 // Dig out the function prototype, if there is one.
1272 Proto = type->getAs<FunctionProtoType>();
1276 // Fill in non-null argument information from the nullability
1277 // information on the parameter types (if we have them).
1280 for (auto paramType : Proto->getParamTypes()) {
1281 if (isNonNullType(S.Context, paramType)) {
1282 if (NonNullArgs.empty())
1283 NonNullArgs.resize(Args.size());
1285 NonNullArgs.set(Index);
1293 // Check for non-null arguments.
1294 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1295 ArgIndex != ArgIndexEnd; ++ArgIndex) {
1296 if (NonNullArgs[ArgIndex])
1297 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
1301 /// Handles the checks for format strings, non-POD arguments to vararg
1302 /// functions, and NULL arguments passed to non-NULL parameters.
1303 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1304 ArrayRef<const Expr *> Args, bool IsMemberFunction,
1305 SourceLocation Loc, SourceRange Range,
1306 VariadicCallType CallType) {
1307 // FIXME: We should check as much as we can in the template definition.
1308 if (CurContext->isDependentContext())
1311 // Printf and scanf checking.
1312 llvm::SmallBitVector CheckedVarArgs;
1314 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1315 // Only create vector if there are format attributes.
1316 CheckedVarArgs.resize(Args.size());
1318 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
1323 // Refuse POD arguments that weren't caught by the format string
1325 if (CallType != VariadicDoesNotApply) {
1326 unsigned NumParams = Proto ? Proto->getNumParams()
1327 : FDecl && isa<FunctionDecl>(FDecl)
1328 ? cast<FunctionDecl>(FDecl)->getNumParams()
1329 : FDecl && isa<ObjCMethodDecl>(FDecl)
1330 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1333 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
1334 // Args[ArgIdx] can be null in malformed code.
1335 if (const Expr *Arg = Args[ArgIdx]) {
1336 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1337 checkVariadicArgument(Arg, CallType);
1342 if (FDecl || Proto) {
1343 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
1345 // Type safety checking.
1347 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1348 CheckArgumentWithTypeTag(I, Args.data());
1353 /// CheckConstructorCall - Check a constructor call for correctness and safety
1354 /// properties not enforced by the C type system.
1355 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1356 ArrayRef<const Expr *> Args,
1357 const FunctionProtoType *Proto,
1358 SourceLocation Loc) {
1359 VariadicCallType CallType =
1360 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
1361 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1365 /// CheckFunctionCall - Check a direct function call for various correctness
1366 /// and safety properties not strictly enforced by the C type system.
1367 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1368 const FunctionProtoType *Proto) {
1369 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1370 isa<CXXMethodDecl>(FDecl);
1371 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1372 IsMemberOperatorCall;
1373 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1374 TheCall->getCallee());
1375 Expr** Args = TheCall->getArgs();
1376 unsigned NumArgs = TheCall->getNumArgs();
1377 if (IsMemberOperatorCall) {
1378 // If this is a call to a member operator, hide the first argument
1380 // FIXME: Our choice of AST representation here is less than ideal.
1384 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
1385 IsMemberFunction, TheCall->getRParenLoc(),
1386 TheCall->getCallee()->getSourceRange(), CallType);
1388 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1389 // None of the checks below are needed for functions that don't have
1390 // simple names (e.g., C++ conversion functions).
1394 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
1395 if (getLangOpts().ObjC1)
1396 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
1398 unsigned CMId = FDecl->getMemoryFunctionKind();
1402 // Handle memory setting and copying functions.
1403 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
1404 CheckStrlcpycatArguments(TheCall, FnInfo);
1405 else if (CMId == Builtin::BIstrncat)
1406 CheckStrncatArguments(TheCall, FnInfo);
1408 CheckMemaccessArguments(TheCall, CMId, FnInfo);
1413 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
1414 ArrayRef<const Expr *> Args) {
1415 VariadicCallType CallType =
1416 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
1418 checkCall(Method, nullptr, Args,
1419 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1425 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1426 const FunctionProtoType *Proto) {
1428 if (const auto *V = dyn_cast<VarDecl>(NDecl))
1429 Ty = V->getType().getNonReferenceType();
1430 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
1431 Ty = F->getType().getNonReferenceType();
1435 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1436 !Ty->isFunctionProtoType())
1439 VariadicCallType CallType;
1440 if (!Proto || !Proto->isVariadic()) {
1441 CallType = VariadicDoesNotApply;
1442 } else if (Ty->isBlockPointerType()) {
1443 CallType = VariadicBlock;
1444 } else { // Ty->isFunctionPointerType()
1445 CallType = VariadicFunction;
1448 checkCall(NDecl, Proto,
1449 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1450 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1451 TheCall->getCallee()->getSourceRange(), CallType);
1456 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1457 /// such as function pointers returned from functions.
1458 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
1459 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
1460 TheCall->getCallee());
1461 checkCall(/*FDecl=*/nullptr, Proto,
1462 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1463 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1464 TheCall->getCallee()->getSourceRange(), CallType);
1469 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1470 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1471 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1475 case AtomicExpr::AO__c11_atomic_init:
1476 llvm_unreachable("There is no ordering argument for an init");
1478 case AtomicExpr::AO__c11_atomic_load:
1479 case AtomicExpr::AO__atomic_load_n:
1480 case AtomicExpr::AO__atomic_load:
1481 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1482 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1484 case AtomicExpr::AO__c11_atomic_store:
1485 case AtomicExpr::AO__atomic_store:
1486 case AtomicExpr::AO__atomic_store_n:
1487 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1488 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1489 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1496 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1497 AtomicExpr::AtomicOp Op) {
1498 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1499 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1501 // All these operations take one of the following forms:
1503 // C __c11_atomic_init(A *, C)
1505 // C __c11_atomic_load(A *, int)
1507 // void __atomic_load(A *, CP, int)
1509 // C __c11_atomic_add(A *, M, int)
1511 // C __atomic_exchange_n(A *, CP, int)
1513 // void __atomic_exchange(A *, C *, CP, int)
1515 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1517 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1520 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1521 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1523 // C is an appropriate type,
1524 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1525 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1526 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1527 // the int parameters are for orderings.
1529 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1530 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1531 AtomicExpr::AO__atomic_load,
1532 "need to update code for modified C11 atomics");
1533 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1534 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1535 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1536 Op == AtomicExpr::AO__atomic_store_n ||
1537 Op == AtomicExpr::AO__atomic_exchange_n ||
1538 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1539 bool IsAddSub = false;
1542 case AtomicExpr::AO__c11_atomic_init:
1546 case AtomicExpr::AO__c11_atomic_load:
1547 case AtomicExpr::AO__atomic_load_n:
1551 case AtomicExpr::AO__c11_atomic_store:
1552 case AtomicExpr::AO__atomic_load:
1553 case AtomicExpr::AO__atomic_store:
1554 case AtomicExpr::AO__atomic_store_n:
1558 case AtomicExpr::AO__c11_atomic_fetch_add:
1559 case AtomicExpr::AO__c11_atomic_fetch_sub:
1560 case AtomicExpr::AO__atomic_fetch_add:
1561 case AtomicExpr::AO__atomic_fetch_sub:
1562 case AtomicExpr::AO__atomic_add_fetch:
1563 case AtomicExpr::AO__atomic_sub_fetch:
1566 case AtomicExpr::AO__c11_atomic_fetch_and:
1567 case AtomicExpr::AO__c11_atomic_fetch_or:
1568 case AtomicExpr::AO__c11_atomic_fetch_xor:
1569 case AtomicExpr::AO__atomic_fetch_and:
1570 case AtomicExpr::AO__atomic_fetch_or:
1571 case AtomicExpr::AO__atomic_fetch_xor:
1572 case AtomicExpr::AO__atomic_fetch_nand:
1573 case AtomicExpr::AO__atomic_and_fetch:
1574 case AtomicExpr::AO__atomic_or_fetch:
1575 case AtomicExpr::AO__atomic_xor_fetch:
1576 case AtomicExpr::AO__atomic_nand_fetch:
1580 case AtomicExpr::AO__c11_atomic_exchange:
1581 case AtomicExpr::AO__atomic_exchange_n:
1585 case AtomicExpr::AO__atomic_exchange:
1589 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1590 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1594 case AtomicExpr::AO__atomic_compare_exchange:
1595 case AtomicExpr::AO__atomic_compare_exchange_n:
1600 // Check we have the right number of arguments.
1601 if (TheCall->getNumArgs() < NumArgs[Form]) {
1602 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1603 << 0 << NumArgs[Form] << TheCall->getNumArgs()
1604 << TheCall->getCallee()->getSourceRange();
1606 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1607 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1608 diag::err_typecheck_call_too_many_args)
1609 << 0 << NumArgs[Form] << TheCall->getNumArgs()
1610 << TheCall->getCallee()->getSourceRange();
1614 // Inspect the first argument of the atomic operation.
1615 Expr *Ptr = TheCall->getArg(0);
1616 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1617 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1619 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1620 << Ptr->getType() << Ptr->getSourceRange();
1624 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1625 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1626 QualType ValType = AtomTy; // 'C'
1628 if (!AtomTy->isAtomicType()) {
1629 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1630 << Ptr->getType() << Ptr->getSourceRange();
1633 if (AtomTy.isConstQualified()) {
1634 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1635 << Ptr->getType() << Ptr->getSourceRange();
1638 ValType = AtomTy->getAs<AtomicType>()->getValueType();
1641 // For an arithmetic operation, the implied arithmetic must be well-formed.
1642 if (Form == Arithmetic) {
1643 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1644 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1645 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1646 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1649 if (!IsAddSub && !ValType->isIntegerType()) {
1650 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1651 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1654 if (IsC11 && ValType->isPointerType() &&
1655 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1656 diag::err_incomplete_type)) {
1659 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1660 // For __atomic_*_n operations, the value type must be a scalar integral or
1661 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1662 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1663 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1667 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1668 !AtomTy->isScalarType()) {
1669 // For GNU atomics, require a trivially-copyable type. This is not part of
1670 // the GNU atomics specification, but we enforce it for sanity.
1671 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1672 << Ptr->getType() << Ptr->getSourceRange();
1676 // FIXME: For any builtin other than a load, the ValType must not be
1679 switch (ValType.getObjCLifetime()) {
1680 case Qualifiers::OCL_None:
1681 case Qualifiers::OCL_ExplicitNone:
1685 case Qualifiers::OCL_Weak:
1686 case Qualifiers::OCL_Strong:
1687 case Qualifiers::OCL_Autoreleasing:
1688 // FIXME: Can this happen? By this point, ValType should be known
1689 // to be trivially copyable.
1690 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1691 << ValType << Ptr->getSourceRange();
1695 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1696 // volatile-ness of the pointee-type inject itself into the result or the
1698 ValType.removeLocalVolatile();
1699 QualType ResultType = ValType;
1700 if (Form == Copy || Form == GNUXchg || Form == Init)
1701 ResultType = Context.VoidTy;
1702 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1703 ResultType = Context.BoolTy;
1705 // The type of a parameter passed 'by value'. In the GNU atomics, such
1706 // arguments are actually passed as pointers.
1707 QualType ByValType = ValType; // 'CP'
1709 ByValType = Ptr->getType();
1711 // The first argument --- the pointer --- has a fixed type; we
1712 // deduce the types of the rest of the arguments accordingly. Walk
1713 // the remaining arguments, converting them to the deduced value type.
1714 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1716 if (i < NumVals[Form] + 1) {
1719 // The second argument is the non-atomic operand. For arithmetic, this
1720 // is always passed by value, and for a compare_exchange it is always
1721 // passed by address. For the rest, GNU uses by-address and C11 uses
1723 assert(Form != Load);
1724 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1726 else if (Form == Copy || Form == Xchg)
1728 else if (Form == Arithmetic)
1729 Ty = Context.getPointerDiffType();
1731 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1734 // The third argument to compare_exchange / GNU exchange is a
1735 // (pointer to a) desired value.
1739 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1740 Ty = Context.BoolTy;
1744 // The order(s) are always converted to int.
1748 InitializedEntity Entity =
1749 InitializedEntity::InitializeParameter(Context, Ty, false);
1750 ExprResult Arg = TheCall->getArg(i);
1751 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1752 if (Arg.isInvalid())
1754 TheCall->setArg(i, Arg.get());
1757 // Permute the arguments into a 'consistent' order.
1758 SmallVector<Expr*, 5> SubExprs;
1759 SubExprs.push_back(Ptr);
1762 // Note, AtomicExpr::getVal1() has a special case for this atomic.
1763 SubExprs.push_back(TheCall->getArg(1)); // Val1
1766 SubExprs.push_back(TheCall->getArg(1)); // Order
1771 SubExprs.push_back(TheCall->getArg(2)); // Order
1772 SubExprs.push_back(TheCall->getArg(1)); // Val1
1775 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1776 SubExprs.push_back(TheCall->getArg(3)); // Order
1777 SubExprs.push_back(TheCall->getArg(1)); // Val1
1778 SubExprs.push_back(TheCall->getArg(2)); // Val2
1781 SubExprs.push_back(TheCall->getArg(3)); // Order
1782 SubExprs.push_back(TheCall->getArg(1)); // Val1
1783 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1784 SubExprs.push_back(TheCall->getArg(2)); // Val2
1787 SubExprs.push_back(TheCall->getArg(4)); // Order
1788 SubExprs.push_back(TheCall->getArg(1)); // Val1
1789 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1790 SubExprs.push_back(TheCall->getArg(2)); // Val2
1791 SubExprs.push_back(TheCall->getArg(3)); // Weak
1795 if (SubExprs.size() >= 2 && Form != Init) {
1796 llvm::APSInt Result(32);
1797 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1798 !isValidOrderingForOp(Result.getSExtValue(), Op))
1799 Diag(SubExprs[1]->getLocStart(),
1800 diag::warn_atomic_op_has_invalid_memory_order)
1801 << SubExprs[1]->getSourceRange();
1804 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1805 SubExprs, ResultType, Op,
1806 TheCall->getRParenLoc());
1808 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1809 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1810 Context.AtomicUsesUnsupportedLibcall(AE))
1811 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1812 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1818 /// checkBuiltinArgument - Given a call to a builtin function, perform
1819 /// normal type-checking on the given argument, updating the call in
1820 /// place. This is useful when a builtin function requires custom
1821 /// type-checking for some of its arguments but not necessarily all of
1824 /// Returns true on error.
1825 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1826 FunctionDecl *Fn = E->getDirectCallee();
1827 assert(Fn && "builtin call without direct callee!");
1829 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1830 InitializedEntity Entity =
1831 InitializedEntity::InitializeParameter(S.Context, Param);
1833 ExprResult Arg = E->getArg(0);
1834 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1835 if (Arg.isInvalid())
1838 E->setArg(ArgIndex, Arg.get());
1842 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1843 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1844 /// type of its first argument. The main ActOnCallExpr routines have already
1845 /// promoted the types of arguments because all of these calls are prototyped as
1848 /// This function goes through and does final semantic checking for these
1851 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1852 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1853 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1854 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1856 // Ensure that we have at least one argument to do type inference from.
1857 if (TheCall->getNumArgs() < 1) {
1858 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1859 << 0 << 1 << TheCall->getNumArgs()
1860 << TheCall->getCallee()->getSourceRange();
1864 // Inspect the first argument of the atomic builtin. This should always be
1865 // a pointer type, whose element is an integral scalar or pointer type.
1866 // Because it is a pointer type, we don't have to worry about any implicit
1868 // FIXME: We don't allow floating point scalars as input.
1869 Expr *FirstArg = TheCall->getArg(0);
1870 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1871 if (FirstArgResult.isInvalid())
1873 FirstArg = FirstArgResult.get();
1874 TheCall->setArg(0, FirstArg);
1876 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1878 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1879 << FirstArg->getType() << FirstArg->getSourceRange();
1883 QualType ValType = pointerType->getPointeeType();
1884 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1885 !ValType->isBlockPointerType()) {
1886 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1887 << FirstArg->getType() << FirstArg->getSourceRange();
1891 switch (ValType.getObjCLifetime()) {
1892 case Qualifiers::OCL_None:
1893 case Qualifiers::OCL_ExplicitNone:
1897 case Qualifiers::OCL_Weak:
1898 case Qualifiers::OCL_Strong:
1899 case Qualifiers::OCL_Autoreleasing:
1900 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1901 << ValType << FirstArg->getSourceRange();
1905 // Strip any qualifiers off ValType.
1906 ValType = ValType.getUnqualifiedType();
1908 // The majority of builtins return a value, but a few have special return
1909 // types, so allow them to override appropriately below.
1910 QualType ResultType = ValType;
1912 // We need to figure out which concrete builtin this maps onto. For example,
1913 // __sync_fetch_and_add with a 2 byte object turns into
1914 // __sync_fetch_and_add_2.
1915 #define BUILTIN_ROW(x) \
1916 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1917 Builtin::BI##x##_8, Builtin::BI##x##_16 }
1919 static const unsigned BuiltinIndices[][5] = {
1920 BUILTIN_ROW(__sync_fetch_and_add),
1921 BUILTIN_ROW(__sync_fetch_and_sub),
1922 BUILTIN_ROW(__sync_fetch_and_or),
1923 BUILTIN_ROW(__sync_fetch_and_and),
1924 BUILTIN_ROW(__sync_fetch_and_xor),
1925 BUILTIN_ROW(__sync_fetch_and_nand),
1927 BUILTIN_ROW(__sync_add_and_fetch),
1928 BUILTIN_ROW(__sync_sub_and_fetch),
1929 BUILTIN_ROW(__sync_and_and_fetch),
1930 BUILTIN_ROW(__sync_or_and_fetch),
1931 BUILTIN_ROW(__sync_xor_and_fetch),
1932 BUILTIN_ROW(__sync_nand_and_fetch),
1934 BUILTIN_ROW(__sync_val_compare_and_swap),
1935 BUILTIN_ROW(__sync_bool_compare_and_swap),
1936 BUILTIN_ROW(__sync_lock_test_and_set),
1937 BUILTIN_ROW(__sync_lock_release),
1938 BUILTIN_ROW(__sync_swap)
1942 // Determine the index of the size.
1944 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1945 case 1: SizeIndex = 0; break;
1946 case 2: SizeIndex = 1; break;
1947 case 4: SizeIndex = 2; break;
1948 case 8: SizeIndex = 3; break;
1949 case 16: SizeIndex = 4; break;
1951 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1952 << FirstArg->getType() << FirstArg->getSourceRange();
1956 // Each of these builtins has one pointer argument, followed by some number of
1957 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1958 // that we ignore. Find out which row of BuiltinIndices to read from as well
1959 // as the number of fixed args.
1960 unsigned BuiltinID = FDecl->getBuiltinID();
1961 unsigned BuiltinIndex, NumFixed = 1;
1962 bool WarnAboutSemanticsChange = false;
1963 switch (BuiltinID) {
1964 default: llvm_unreachable("Unknown overloaded atomic builtin!");
1965 case Builtin::BI__sync_fetch_and_add:
1966 case Builtin::BI__sync_fetch_and_add_1:
1967 case Builtin::BI__sync_fetch_and_add_2:
1968 case Builtin::BI__sync_fetch_and_add_4:
1969 case Builtin::BI__sync_fetch_and_add_8:
1970 case Builtin::BI__sync_fetch_and_add_16:
1974 case Builtin::BI__sync_fetch_and_sub:
1975 case Builtin::BI__sync_fetch_and_sub_1:
1976 case Builtin::BI__sync_fetch_and_sub_2:
1977 case Builtin::BI__sync_fetch_and_sub_4:
1978 case Builtin::BI__sync_fetch_and_sub_8:
1979 case Builtin::BI__sync_fetch_and_sub_16:
1983 case Builtin::BI__sync_fetch_and_or:
1984 case Builtin::BI__sync_fetch_and_or_1:
1985 case Builtin::BI__sync_fetch_and_or_2:
1986 case Builtin::BI__sync_fetch_and_or_4:
1987 case Builtin::BI__sync_fetch_and_or_8:
1988 case Builtin::BI__sync_fetch_and_or_16:
1992 case Builtin::BI__sync_fetch_and_and:
1993 case Builtin::BI__sync_fetch_and_and_1:
1994 case Builtin::BI__sync_fetch_and_and_2:
1995 case Builtin::BI__sync_fetch_and_and_4:
1996 case Builtin::BI__sync_fetch_and_and_8:
1997 case Builtin::BI__sync_fetch_and_and_16:
2001 case Builtin::BI__sync_fetch_and_xor:
2002 case Builtin::BI__sync_fetch_and_xor_1:
2003 case Builtin::BI__sync_fetch_and_xor_2:
2004 case Builtin::BI__sync_fetch_and_xor_4:
2005 case Builtin::BI__sync_fetch_and_xor_8:
2006 case Builtin::BI__sync_fetch_and_xor_16:
2010 case Builtin::BI__sync_fetch_and_nand:
2011 case Builtin::BI__sync_fetch_and_nand_1:
2012 case Builtin::BI__sync_fetch_and_nand_2:
2013 case Builtin::BI__sync_fetch_and_nand_4:
2014 case Builtin::BI__sync_fetch_and_nand_8:
2015 case Builtin::BI__sync_fetch_and_nand_16:
2017 WarnAboutSemanticsChange = true;
2020 case Builtin::BI__sync_add_and_fetch:
2021 case Builtin::BI__sync_add_and_fetch_1:
2022 case Builtin::BI__sync_add_and_fetch_2:
2023 case Builtin::BI__sync_add_and_fetch_4:
2024 case Builtin::BI__sync_add_and_fetch_8:
2025 case Builtin::BI__sync_add_and_fetch_16:
2029 case Builtin::BI__sync_sub_and_fetch:
2030 case Builtin::BI__sync_sub_and_fetch_1:
2031 case Builtin::BI__sync_sub_and_fetch_2:
2032 case Builtin::BI__sync_sub_and_fetch_4:
2033 case Builtin::BI__sync_sub_and_fetch_8:
2034 case Builtin::BI__sync_sub_and_fetch_16:
2038 case Builtin::BI__sync_and_and_fetch:
2039 case Builtin::BI__sync_and_and_fetch_1:
2040 case Builtin::BI__sync_and_and_fetch_2:
2041 case Builtin::BI__sync_and_and_fetch_4:
2042 case Builtin::BI__sync_and_and_fetch_8:
2043 case Builtin::BI__sync_and_and_fetch_16:
2047 case Builtin::BI__sync_or_and_fetch:
2048 case Builtin::BI__sync_or_and_fetch_1:
2049 case Builtin::BI__sync_or_and_fetch_2:
2050 case Builtin::BI__sync_or_and_fetch_4:
2051 case Builtin::BI__sync_or_and_fetch_8:
2052 case Builtin::BI__sync_or_and_fetch_16:
2056 case Builtin::BI__sync_xor_and_fetch:
2057 case Builtin::BI__sync_xor_and_fetch_1:
2058 case Builtin::BI__sync_xor_and_fetch_2:
2059 case Builtin::BI__sync_xor_and_fetch_4:
2060 case Builtin::BI__sync_xor_and_fetch_8:
2061 case Builtin::BI__sync_xor_and_fetch_16:
2065 case Builtin::BI__sync_nand_and_fetch:
2066 case Builtin::BI__sync_nand_and_fetch_1:
2067 case Builtin::BI__sync_nand_and_fetch_2:
2068 case Builtin::BI__sync_nand_and_fetch_4:
2069 case Builtin::BI__sync_nand_and_fetch_8:
2070 case Builtin::BI__sync_nand_and_fetch_16:
2072 WarnAboutSemanticsChange = true;
2075 case Builtin::BI__sync_val_compare_and_swap:
2076 case Builtin::BI__sync_val_compare_and_swap_1:
2077 case Builtin::BI__sync_val_compare_and_swap_2:
2078 case Builtin::BI__sync_val_compare_and_swap_4:
2079 case Builtin::BI__sync_val_compare_and_swap_8:
2080 case Builtin::BI__sync_val_compare_and_swap_16:
2085 case Builtin::BI__sync_bool_compare_and_swap:
2086 case Builtin::BI__sync_bool_compare_and_swap_1:
2087 case Builtin::BI__sync_bool_compare_and_swap_2:
2088 case Builtin::BI__sync_bool_compare_and_swap_4:
2089 case Builtin::BI__sync_bool_compare_and_swap_8:
2090 case Builtin::BI__sync_bool_compare_and_swap_16:
2093 ResultType = Context.BoolTy;
2096 case Builtin::BI__sync_lock_test_and_set:
2097 case Builtin::BI__sync_lock_test_and_set_1:
2098 case Builtin::BI__sync_lock_test_and_set_2:
2099 case Builtin::BI__sync_lock_test_and_set_4:
2100 case Builtin::BI__sync_lock_test_and_set_8:
2101 case Builtin::BI__sync_lock_test_and_set_16:
2105 case Builtin::BI__sync_lock_release:
2106 case Builtin::BI__sync_lock_release_1:
2107 case Builtin::BI__sync_lock_release_2:
2108 case Builtin::BI__sync_lock_release_4:
2109 case Builtin::BI__sync_lock_release_8:
2110 case Builtin::BI__sync_lock_release_16:
2113 ResultType = Context.VoidTy;
2116 case Builtin::BI__sync_swap:
2117 case Builtin::BI__sync_swap_1:
2118 case Builtin::BI__sync_swap_2:
2119 case Builtin::BI__sync_swap_4:
2120 case Builtin::BI__sync_swap_8:
2121 case Builtin::BI__sync_swap_16:
2126 // Now that we know how many fixed arguments we expect, first check that we
2127 // have at least that many.
2128 if (TheCall->getNumArgs() < 1+NumFixed) {
2129 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2130 << 0 << 1+NumFixed << TheCall->getNumArgs()
2131 << TheCall->getCallee()->getSourceRange();
2135 if (WarnAboutSemanticsChange) {
2136 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2137 << TheCall->getCallee()->getSourceRange();
2140 // Get the decl for the concrete builtin from this, we can tell what the
2141 // concrete integer type we should convert to is.
2142 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2143 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
2144 FunctionDecl *NewBuiltinDecl;
2145 if (NewBuiltinID == BuiltinID)
2146 NewBuiltinDecl = FDecl;
2148 // Perform builtin lookup to avoid redeclaring it.
2149 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2150 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2151 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2152 assert(Res.getFoundDecl());
2153 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
2154 if (!NewBuiltinDecl)
2158 // The first argument --- the pointer --- has a fixed type; we
2159 // deduce the types of the rest of the arguments accordingly. Walk
2160 // the remaining arguments, converting them to the deduced value type.
2161 for (unsigned i = 0; i != NumFixed; ++i) {
2162 ExprResult Arg = TheCall->getArg(i+1);
2164 // GCC does an implicit conversion to the pointer or integer ValType. This
2165 // can fail in some cases (1i -> int**), check for this error case now.
2166 // Initialize the argument.
2167 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2168 ValType, /*consume*/ false);
2169 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2170 if (Arg.isInvalid())
2173 // Okay, we have something that *can* be converted to the right type. Check
2174 // to see if there is a potentially weird extension going on here. This can
2175 // happen when you do an atomic operation on something like an char* and
2176 // pass in 42. The 42 gets converted to char. This is even more strange
2177 // for things like 45.123 -> char, etc.
2178 // FIXME: Do this check.
2179 TheCall->setArg(i+1, Arg.get());
2182 ASTContext& Context = this->getASTContext();
2184 // Create a new DeclRefExpr to refer to the new decl.
2185 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2187 DRE->getQualifierLoc(),
2190 /*enclosing*/ false,
2192 Context.BuiltinFnTy,
2193 DRE->getValueKind());
2195 // Set the callee in the CallExpr.
2196 // FIXME: This loses syntactic information.
2197 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2198 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2199 CK_BuiltinFnToFnPtr);
2200 TheCall->setCallee(PromotedCall.get());
2202 // Change the result type of the call to match the original value type. This
2203 // is arbitrary, but the codegen for these builtins ins design to handle it
2205 TheCall->setType(ResultType);
2207 return TheCallResult;
2210 /// CheckObjCString - Checks that the argument to the builtin
2211 /// CFString constructor is correct
2212 /// Note: It might also make sense to do the UTF-16 conversion here (would
2213 /// simplify the backend).
2214 bool Sema::CheckObjCString(Expr *Arg) {
2215 Arg = Arg->IgnoreParenCasts();
2216 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2218 if (!Literal || !Literal->isAscii()) {
2219 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2220 << Arg->getSourceRange();
2224 if (Literal->containsNonAsciiOrNull()) {
2225 StringRef String = Literal->getString();
2226 unsigned NumBytes = String.size();
2227 SmallVector<UTF16, 128> ToBuf(NumBytes);
2228 const UTF8 *FromPtr = (const UTF8 *)String.data();
2229 UTF16 *ToPtr = &ToBuf[0];
2231 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2232 &ToPtr, ToPtr + NumBytes,
2234 // Check for conversion failure.
2235 if (Result != conversionOK)
2236 Diag(Arg->getLocStart(),
2237 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2242 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2243 /// Emit an error and return true on failure, return false on success.
2244 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2245 Expr *Fn = TheCall->getCallee();
2246 if (TheCall->getNumArgs() > 2) {
2247 Diag(TheCall->getArg(2)->getLocStart(),
2248 diag::err_typecheck_call_too_many_args)
2249 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2250 << Fn->getSourceRange()
2251 << SourceRange(TheCall->getArg(2)->getLocStart(),
2252 (*(TheCall->arg_end()-1))->getLocEnd());
2256 if (TheCall->getNumArgs() < 2) {
2257 return Diag(TheCall->getLocEnd(),
2258 diag::err_typecheck_call_too_few_args_at_least)
2259 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
2262 // Type-check the first argument normally.
2263 if (checkBuiltinArgument(*this, TheCall, 0))
2266 // Determine whether the current function is variadic or not.
2267 BlockScopeInfo *CurBlock = getCurBlock();
2270 isVariadic = CurBlock->TheDecl->isVariadic();
2271 else if (FunctionDecl *FD = getCurFunctionDecl())
2272 isVariadic = FD->isVariadic();
2274 isVariadic = getCurMethodDecl()->isVariadic();
2277 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2281 // Verify that the second argument to the builtin is the last argument of the
2282 // current function or method.
2283 bool SecondArgIsLastNamedArgument = false;
2284 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
2286 // These are valid if SecondArgIsLastNamedArgument is false after the next
2289 SourceLocation ParamLoc;
2291 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2292 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
2293 // FIXME: This isn't correct for methods (results in bogus warning).
2294 // Get the last formal in the current function.
2295 const ParmVarDecl *LastArg;
2297 LastArg = *(CurBlock->TheDecl->param_end()-1);
2298 else if (FunctionDecl *FD = getCurFunctionDecl())
2299 LastArg = *(FD->param_end()-1);
2301 LastArg = *(getCurMethodDecl()->param_end()-1);
2302 SecondArgIsLastNamedArgument = PV == LastArg;
2304 Type = PV->getType();
2305 ParamLoc = PV->getLocation();
2309 if (!SecondArgIsLastNamedArgument)
2310 Diag(TheCall->getArg(1)->getLocStart(),
2311 diag::warn_second_parameter_of_va_start_not_last_named_argument);
2312 else if (Type->isReferenceType()) {
2313 Diag(Arg->getLocStart(),
2314 diag::warn_va_start_of_reference_type_is_undefined);
2315 Diag(ParamLoc, diag::note_parameter_type) << Type;
2318 TheCall->setType(Context.VoidTy);
2322 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2323 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2324 // const char *named_addr);
2326 Expr *Func = Call->getCallee();
2328 if (Call->getNumArgs() < 3)
2329 return Diag(Call->getLocEnd(),
2330 diag::err_typecheck_call_too_few_args_at_least)
2331 << 0 /*function call*/ << 3 << Call->getNumArgs();
2333 // Determine whether the current function is variadic or not.
2335 if (BlockScopeInfo *CurBlock = getCurBlock())
2336 IsVariadic = CurBlock->TheDecl->isVariadic();
2337 else if (FunctionDecl *FD = getCurFunctionDecl())
2338 IsVariadic = FD->isVariadic();
2339 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2340 IsVariadic = MD->isVariadic();
2342 llvm_unreachable("unexpected statement type");
2345 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2349 // Type-check the first argument normally.
2350 if (checkBuiltinArgument(*this, Call, 0))
2356 } ArgumentTypes[] = {
2357 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2358 { 2, Context.getSizeType() },
2361 for (const auto &AT : ArgumentTypes) {
2362 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2363 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2365 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2366 << Arg->getType() << AT.Type << 1 /* different class */
2367 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2368 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2374 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2375 /// friends. This is declared to take (...), so we have to check everything.
2376 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2377 if (TheCall->getNumArgs() < 2)
2378 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2379 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
2380 if (TheCall->getNumArgs() > 2)
2381 return Diag(TheCall->getArg(2)->getLocStart(),
2382 diag::err_typecheck_call_too_many_args)
2383 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2384 << SourceRange(TheCall->getArg(2)->getLocStart(),
2385 (*(TheCall->arg_end()-1))->getLocEnd());
2387 ExprResult OrigArg0 = TheCall->getArg(0);
2388 ExprResult OrigArg1 = TheCall->getArg(1);
2390 // Do standard promotions between the two arguments, returning their common
2392 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
2393 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2396 // Make sure any conversions are pushed back into the call; this is
2397 // type safe since unordered compare builtins are declared as "_Bool
2399 TheCall->setArg(0, OrigArg0.get());
2400 TheCall->setArg(1, OrigArg1.get());
2402 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
2405 // If the common type isn't a real floating type, then the arguments were
2406 // invalid for this operation.
2407 if (Res.isNull() || !Res->isRealFloatingType())
2408 return Diag(OrigArg0.get()->getLocStart(),
2409 diag::err_typecheck_call_invalid_ordered_compare)
2410 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2411 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
2416 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2417 /// __builtin_isnan and friends. This is declared to take (...), so we have
2418 /// to check everything. We expect the last argument to be a floating point
2420 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2421 if (TheCall->getNumArgs() < NumArgs)
2422 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2423 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
2424 if (TheCall->getNumArgs() > NumArgs)
2425 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
2426 diag::err_typecheck_call_too_many_args)
2427 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
2428 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
2429 (*(TheCall->arg_end()-1))->getLocEnd());
2431 Expr *OrigArg = TheCall->getArg(NumArgs-1);
2433 if (OrigArg->isTypeDependent())
2436 // This operation requires a non-_Complex floating-point number.
2437 if (!OrigArg->getType()->isRealFloatingType())
2438 return Diag(OrigArg->getLocStart(),
2439 diag::err_typecheck_call_invalid_unary_fp)
2440 << OrigArg->getType() << OrigArg->getSourceRange();
2442 // If this is an implicit conversion from float -> double, remove it.
2443 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2444 Expr *CastArg = Cast->getSubExpr();
2445 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2446 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2447 "promotion from float to double is the only expected cast here");
2448 Cast->setSubExpr(nullptr);
2449 TheCall->setArg(NumArgs-1, CastArg);
2456 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2457 // This is declared to take (...), so we have to check everything.
2458 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
2459 if (TheCall->getNumArgs() < 2)
2460 return ExprError(Diag(TheCall->getLocEnd(),
2461 diag::err_typecheck_call_too_few_args_at_least)
2462 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2463 << TheCall->getSourceRange());
2465 // Determine which of the following types of shufflevector we're checking:
2466 // 1) unary, vector mask: (lhs, mask)
2467 // 2) binary, vector mask: (lhs, rhs, mask)
2468 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2469 QualType resType = TheCall->getArg(0)->getType();
2470 unsigned numElements = 0;
2472 if (!TheCall->getArg(0)->isTypeDependent() &&
2473 !TheCall->getArg(1)->isTypeDependent()) {
2474 QualType LHSType = TheCall->getArg(0)->getType();
2475 QualType RHSType = TheCall->getArg(1)->getType();
2477 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2478 return ExprError(Diag(TheCall->getLocStart(),
2479 diag::err_shufflevector_non_vector)
2480 << SourceRange(TheCall->getArg(0)->getLocStart(),
2481 TheCall->getArg(1)->getLocEnd()));
2483 numElements = LHSType->getAs<VectorType>()->getNumElements();
2484 unsigned numResElements = TheCall->getNumArgs() - 2;
2486 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2487 // with mask. If so, verify that RHS is an integer vector type with the
2488 // same number of elts as lhs.
2489 if (TheCall->getNumArgs() == 2) {
2490 if (!RHSType->hasIntegerRepresentation() ||
2491 RHSType->getAs<VectorType>()->getNumElements() != numElements)
2492 return ExprError(Diag(TheCall->getLocStart(),
2493 diag::err_shufflevector_incompatible_vector)
2494 << SourceRange(TheCall->getArg(1)->getLocStart(),
2495 TheCall->getArg(1)->getLocEnd()));
2496 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
2497 return ExprError(Diag(TheCall->getLocStart(),
2498 diag::err_shufflevector_incompatible_vector)
2499 << SourceRange(TheCall->getArg(0)->getLocStart(),
2500 TheCall->getArg(1)->getLocEnd()));
2501 } else if (numElements != numResElements) {
2502 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
2503 resType = Context.getVectorType(eltType, numResElements,
2504 VectorType::GenericVector);
2508 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
2509 if (TheCall->getArg(i)->isTypeDependent() ||
2510 TheCall->getArg(i)->isValueDependent())
2513 llvm::APSInt Result(32);
2514 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2515 return ExprError(Diag(TheCall->getLocStart(),
2516 diag::err_shufflevector_nonconstant_argument)
2517 << TheCall->getArg(i)->getSourceRange());
2519 // Allow -1 which will be translated to undef in the IR.
2520 if (Result.isSigned() && Result.isAllOnesValue())
2523 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
2524 return ExprError(Diag(TheCall->getLocStart(),
2525 diag::err_shufflevector_argument_too_large)
2526 << TheCall->getArg(i)->getSourceRange());
2529 SmallVector<Expr*, 32> exprs;
2531 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
2532 exprs.push_back(TheCall->getArg(i));
2533 TheCall->setArg(i, nullptr);
2536 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2537 TheCall->getCallee()->getLocStart(),
2538 TheCall->getRParenLoc());
2541 /// SemaConvertVectorExpr - Handle __builtin_convertvector
2542 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2543 SourceLocation BuiltinLoc,
2544 SourceLocation RParenLoc) {
2545 ExprValueKind VK = VK_RValue;
2546 ExprObjectKind OK = OK_Ordinary;
2547 QualType DstTy = TInfo->getType();
2548 QualType SrcTy = E->getType();
2550 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2551 return ExprError(Diag(BuiltinLoc,
2552 diag::err_convertvector_non_vector)
2553 << E->getSourceRange());
2554 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2555 return ExprError(Diag(BuiltinLoc,
2556 diag::err_convertvector_non_vector_type));
2558 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2559 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2560 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2561 if (SrcElts != DstElts)
2562 return ExprError(Diag(BuiltinLoc,
2563 diag::err_convertvector_incompatible_vector)
2564 << E->getSourceRange());
2567 return new (Context)
2568 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
2571 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2572 // This is declared to take (const void*, ...) and can take two
2573 // optional constant int args.
2574 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
2575 unsigned NumArgs = TheCall->getNumArgs();
2578 return Diag(TheCall->getLocEnd(),
2579 diag::err_typecheck_call_too_many_args_at_most)
2580 << 0 /*function call*/ << 3 << NumArgs
2581 << TheCall->getSourceRange();
2583 // Argument 0 is checked for us and the remaining arguments must be
2584 // constant integers.
2585 for (unsigned i = 1; i != NumArgs; ++i)
2586 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
2592 /// SemaBuiltinAssume - Handle __assume (MS Extension).
2593 // __assume does not evaluate its arguments, and should warn if its argument
2594 // has side effects.
2595 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2596 Expr *Arg = TheCall->getArg(0);
2597 if (Arg->isInstantiationDependent()) return false;
2599 if (Arg->HasSideEffects(Context))
2600 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2601 << Arg->getSourceRange()
2602 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2607 /// Handle __builtin_assume_aligned. This is declared
2608 /// as (const void*, size_t, ...) and can take one optional constant int arg.
2609 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2610 unsigned NumArgs = TheCall->getNumArgs();
2613 return Diag(TheCall->getLocEnd(),
2614 diag::err_typecheck_call_too_many_args_at_most)
2615 << 0 /*function call*/ << 3 << NumArgs
2616 << TheCall->getSourceRange();
2618 // The alignment must be a constant integer.
2619 Expr *Arg = TheCall->getArg(1);
2621 // We can't check the value of a dependent argument.
2622 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2623 llvm::APSInt Result;
2624 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2627 if (!Result.isPowerOf2())
2628 return Diag(TheCall->getLocStart(),
2629 diag::err_alignment_not_power_of_two)
2630 << Arg->getSourceRange();
2634 ExprResult Arg(TheCall->getArg(2));
2635 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2636 Context.getSizeType(), false);
2637 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2638 if (Arg.isInvalid()) return true;
2639 TheCall->setArg(2, Arg.get());
2645 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2646 /// TheCall is a constant expression.
2647 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2648 llvm::APSInt &Result) {
2649 Expr *Arg = TheCall->getArg(ArgNum);
2650 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2651 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2653 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2655 if (!Arg->isIntegerConstantExpr(Result, Context))
2656 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
2657 << FDecl->getDeclName() << Arg->getSourceRange();
2662 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2663 /// TheCall is a constant expression in the range [Low, High].
2664 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2665 int Low, int High) {
2666 llvm::APSInt Result;
2668 // We can't check the value of a dependent argument.
2669 Expr *Arg = TheCall->getArg(ArgNum);
2670 if (Arg->isTypeDependent() || Arg->isValueDependent())
2673 // Check constant-ness first.
2674 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2677 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
2678 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2679 << Low << High << Arg->getSourceRange();
2684 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2685 /// TheCall is an ARM/AArch64 special register string literal.
2686 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2687 int ArgNum, unsigned ExpectedFieldNum,
2689 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2690 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2691 BuiltinID == ARM::BI__builtin_arm_rsr ||
2692 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2693 BuiltinID == ARM::BI__builtin_arm_wsr ||
2694 BuiltinID == ARM::BI__builtin_arm_wsrp;
2695 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2696 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2697 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2698 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2699 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2700 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2701 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2703 // We can't check the value of a dependent argument.
2704 Expr *Arg = TheCall->getArg(ArgNum);
2705 if (Arg->isTypeDependent() || Arg->isValueDependent())
2708 // Check if the argument is a string literal.
2709 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2710 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2711 << Arg->getSourceRange();
2713 // Check the type of special register given.
2714 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2715 SmallVector<StringRef, 6> Fields;
2716 Reg.split(Fields, ":");
2718 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2719 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2720 << Arg->getSourceRange();
2722 // If the string is the name of a register then we cannot check that it is
2723 // valid here but if the string is of one the forms described in ACLE then we
2724 // can check that the supplied fields are integers and within the valid
2726 if (Fields.size() > 1) {
2727 bool FiveFields = Fields.size() == 5;
2729 bool ValidString = true;
2731 ValidString &= Fields[0].startswith_lower("cp") ||
2732 Fields[0].startswith_lower("p");
2735 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2737 ValidString &= Fields[2].startswith_lower("c");
2739 Fields[2] = Fields[2].drop_front(1);
2742 ValidString &= Fields[3].startswith_lower("c");
2744 Fields[3] = Fields[3].drop_front(1);
2748 SmallVector<int, 5> Ranges;
2750 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2752 Ranges.append({15, 7, 15});
2754 for (unsigned i=0; i<Fields.size(); ++i) {
2756 ValidString &= !Fields[i].getAsInteger(10, IntField);
2757 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2761 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2762 << Arg->getSourceRange();
2764 } else if (IsAArch64Builtin && Fields.size() == 1) {
2765 // If the register name is one of those that appear in the condition below
2766 // and the special register builtin being used is one of the write builtins,
2767 // then we require that the argument provided for writing to the register
2768 // is an integer constant expression. This is because it will be lowered to
2769 // an MSR (immediate) instruction, so we need to know the immediate at
2771 if (TheCall->getNumArgs() != 2)
2774 std::string RegLower = Reg.lower();
2775 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2776 RegLower != "pan" && RegLower != "uao")
2779 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2785 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2786 /// This checks that the target supports __builtin_longjmp and
2787 /// that val is a constant 1.
2788 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2789 if (!Context.getTargetInfo().hasSjLjLowering())
2790 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2791 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2793 Expr *Arg = TheCall->getArg(1);
2794 llvm::APSInt Result;
2796 // TODO: This is less than ideal. Overload this to take a value.
2797 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2801 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2802 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2808 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2809 /// This checks that the target supports __builtin_setjmp.
2810 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2811 if (!Context.getTargetInfo().hasSjLjLowering())
2812 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2813 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2818 enum StringLiteralCheckType {
2820 SLCT_UncheckedLiteral,
2825 // Determine if an expression is a string literal or constant string.
2826 // If this function returns false on the arguments to a function expecting a
2827 // format string, we will usually need to emit a warning.
2828 // True string literals are then checked by CheckFormatString.
2829 static StringLiteralCheckType
2830 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2831 bool HasVAListArg, unsigned format_idx,
2832 unsigned firstDataArg, Sema::FormatStringType Type,
2833 Sema::VariadicCallType CallType, bool InFunctionCall,
2834 llvm::SmallBitVector &CheckedVarArgs) {
2836 if (E->isTypeDependent() || E->isValueDependent())
2837 return SLCT_NotALiteral;
2839 E = E->IgnoreParenCasts();
2841 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
2842 // Technically -Wformat-nonliteral does not warn about this case.
2843 // The behavior of printf and friends in this case is implementation
2844 // dependent. Ideally if the format string cannot be null then
2845 // it should have a 'nonnull' attribute in the function prototype.
2846 return SLCT_UncheckedLiteral;
2848 switch (E->getStmtClass()) {
2849 case Stmt::BinaryConditionalOperatorClass:
2850 case Stmt::ConditionalOperatorClass: {
2851 // The expression is a literal if both sub-expressions were, and it was
2852 // completely checked only if both sub-expressions were checked.
2853 const AbstractConditionalOperator *C =
2854 cast<AbstractConditionalOperator>(E);
2855 StringLiteralCheckType Left =
2856 checkFormatStringExpr(S, C->getTrueExpr(), Args,
2857 HasVAListArg, format_idx, firstDataArg,
2858 Type, CallType, InFunctionCall, CheckedVarArgs);
2859 if (Left == SLCT_NotALiteral)
2860 return SLCT_NotALiteral;
2861 StringLiteralCheckType Right =
2862 checkFormatStringExpr(S, C->getFalseExpr(), Args,
2863 HasVAListArg, format_idx, firstDataArg,
2864 Type, CallType, InFunctionCall, CheckedVarArgs);
2865 return Left < Right ? Left : Right;
2868 case Stmt::ImplicitCastExprClass: {
2869 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2873 case Stmt::OpaqueValueExprClass:
2874 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2878 return SLCT_NotALiteral;
2880 case Stmt::PredefinedExprClass:
2881 // While __func__, etc., are technically not string literals, they
2882 // cannot contain format specifiers and thus are not a security
2884 return SLCT_UncheckedLiteral;
2886 case Stmt::DeclRefExprClass: {
2887 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2889 // As an exception, do not flag errors for variables binding to
2890 // const string literals.
2891 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2892 bool isConstant = false;
2893 QualType T = DR->getType();
2895 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2896 isConstant = AT->getElementType().isConstant(S.Context);
2897 } else if (const PointerType *PT = T->getAs<PointerType>()) {
2898 isConstant = T.isConstant(S.Context) &&
2899 PT->getPointeeType().isConstant(S.Context);
2900 } else if (T->isObjCObjectPointerType()) {
2901 // In ObjC, there is usually no "const ObjectPointer" type,
2902 // so don't check if the pointee type is constant.
2903 isConstant = T.isConstant(S.Context);
2907 if (const Expr *Init = VD->getAnyInitializer()) {
2908 // Look through initializers like const char c[] = { "foo" }
2909 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2910 if (InitList->isStringLiteralInit())
2911 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2913 return checkFormatStringExpr(S, Init, Args,
2914 HasVAListArg, format_idx,
2915 firstDataArg, Type, CallType,
2916 /*InFunctionCall*/false, CheckedVarArgs);
2920 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2921 // special check to see if the format string is a function parameter
2922 // of the function calling the printf function. If the function
2923 // has an attribute indicating it is a printf-like function, then we
2924 // should suppress warnings concerning non-literals being used in a call
2925 // to a vprintf function. For example:
2928 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2930 // va_start(ap, fmt);
2931 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2935 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2936 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2937 int PVIndex = PV->getFunctionScopeIndex() + 1;
2938 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
2939 // adjust for implicit parameter
2940 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2941 if (MD->isInstance())
2943 // We also check if the formats are compatible.
2944 // We can't pass a 'scanf' string to a 'printf' function.
2945 if (PVIndex == PVFormat->getFormatIdx() &&
2946 Type == S.GetFormatStringType(PVFormat))
2947 return SLCT_UncheckedLiteral;
2954 return SLCT_NotALiteral;
2957 case Stmt::CallExprClass:
2958 case Stmt::CXXMemberCallExprClass: {
2959 const CallExpr *CE = cast<CallExpr>(E);
2960 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2961 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2962 unsigned ArgIndex = FA->getFormatIdx();
2963 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2964 if (MD->isInstance())
2966 const Expr *Arg = CE->getArg(ArgIndex - 1);
2968 return checkFormatStringExpr(S, Arg, Args,
2969 HasVAListArg, format_idx, firstDataArg,
2970 Type, CallType, InFunctionCall,
2972 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2973 unsigned BuiltinID = FD->getBuiltinID();
2974 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2975 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2976 const Expr *Arg = CE->getArg(0);
2977 return checkFormatStringExpr(S, Arg, Args,
2978 HasVAListArg, format_idx,
2979 firstDataArg, Type, CallType,
2980 InFunctionCall, CheckedVarArgs);
2985 return SLCT_NotALiteral;
2987 case Stmt::ObjCStringLiteralClass:
2988 case Stmt::StringLiteralClass: {
2989 const StringLiteral *StrE = nullptr;
2991 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2992 StrE = ObjCFExpr->getString();
2994 StrE = cast<StringLiteral>(E);
2997 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2998 Type, InFunctionCall, CallType, CheckedVarArgs);
2999 return SLCT_CheckedLiteral;
3002 return SLCT_NotALiteral;
3006 return SLCT_NotALiteral;
3010 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
3011 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
3012 .Case("scanf", FST_Scanf)
3013 .Cases("printf", "printf0", FST_Printf)
3014 .Cases("NSString", "CFString", FST_NSString)
3015 .Case("strftime", FST_Strftime)
3016 .Case("strfmon", FST_Strfmon)
3017 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
3018 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
3019 .Case("os_trace", FST_OSTrace)
3020 .Default(FST_Unknown);
3023 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3024 /// functions) for correct use of format strings.
3025 /// Returns true if a format string has been fully checked.
3026 bool Sema::CheckFormatArguments(const FormatAttr *Format,
3027 ArrayRef<const Expr *> Args,
3029 VariadicCallType CallType,
3030 SourceLocation Loc, SourceRange Range,
3031 llvm::SmallBitVector &CheckedVarArgs) {
3032 FormatStringInfo FSI;
3033 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
3034 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
3035 FSI.FirstDataArg, GetFormatStringType(Format),
3036 CallType, Loc, Range, CheckedVarArgs);
3040 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
3041 bool HasVAListArg, unsigned format_idx,
3042 unsigned firstDataArg, FormatStringType Type,
3043 VariadicCallType CallType,
3044 SourceLocation Loc, SourceRange Range,
3045 llvm::SmallBitVector &CheckedVarArgs) {
3046 // CHECK: printf/scanf-like function is called with no format string.
3047 if (format_idx >= Args.size()) {
3048 Diag(Loc, diag::warn_missing_format_string) << Range;
3052 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
3054 // CHECK: format string is not a string literal.
3056 // Dynamically generated format strings are difficult to
3057 // automatically vet at compile time. Requiring that format strings
3058 // are string literals: (1) permits the checking of format strings by
3059 // the compiler and thereby (2) can practically remove the source of
3060 // many format string exploits.
3062 // Format string can be either ObjC string (e.g. @"%d") or
3063 // C string (e.g. "%d")
3064 // ObjC string uses the same format specifiers as C string, so we can use
3065 // the same format string checking logic for both ObjC and C strings.
3066 StringLiteralCheckType CT =
3067 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3068 format_idx, firstDataArg, Type, CallType,
3069 /*IsFunctionCall*/true, CheckedVarArgs);
3070 if (CT != SLCT_NotALiteral)
3071 // Literal format string found, check done!
3072 return CT == SLCT_CheckedLiteral;
3074 // Strftime is particular as it always uses a single 'time' argument,
3075 // so it is safe to pass a non-literal string.
3076 if (Type == FST_Strftime)
3079 // Do not emit diag when the string param is a macro expansion and the
3080 // format is either NSString or CFString. This is a hack to prevent
3081 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3082 // which are usually used in place of NS and CF string literals.
3083 if (Type == FST_NSString &&
3084 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
3087 // If there are no arguments specified, warn with -Wformat-security, otherwise
3088 // warn only with -Wformat-nonliteral.
3089 if (Args.size() == firstDataArg)
3090 Diag(Args[format_idx]->getLocStart(),
3091 diag::warn_format_nonliteral_noargs)
3092 << OrigFormatExpr->getSourceRange();
3094 Diag(Args[format_idx]->getLocStart(),
3095 diag::warn_format_nonliteral)
3096 << OrigFormatExpr->getSourceRange();
3101 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3104 const StringLiteral *FExpr;
3105 const Expr *OrigFormatExpr;
3106 const unsigned FirstDataArg;
3107 const unsigned NumDataArgs;
3108 const char *Beg; // Start of format string.
3109 const bool HasVAListArg;
3110 ArrayRef<const Expr *> Args;
3112 llvm::SmallBitVector CoveredArgs;
3113 bool usesPositionalArgs;
3115 bool inFunctionCall;
3116 Sema::VariadicCallType CallType;
3117 llvm::SmallBitVector &CheckedVarArgs;
3119 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
3120 const Expr *origFormatExpr, unsigned firstDataArg,
3121 unsigned numDataArgs, const char *beg, bool hasVAListArg,
3122 ArrayRef<const Expr *> Args,
3123 unsigned formatIdx, bool inFunctionCall,
3124 Sema::VariadicCallType callType,
3125 llvm::SmallBitVector &CheckedVarArgs)
3126 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
3127 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3128 Beg(beg), HasVAListArg(hasVAListArg),
3129 Args(Args), FormatIdx(formatIdx),
3130 usesPositionalArgs(false), atFirstArg(true),
3131 inFunctionCall(inFunctionCall), CallType(callType),
3132 CheckedVarArgs(CheckedVarArgs) {
3133 CoveredArgs.resize(numDataArgs);
3134 CoveredArgs.reset();
3137 void DoneProcessing();
3139 void HandleIncompleteSpecifier(const char *startSpecifier,
3140 unsigned specifierLen) override;
3142 void HandleInvalidLengthModifier(
3143 const analyze_format_string::FormatSpecifier &FS,
3144 const analyze_format_string::ConversionSpecifier &CS,
3145 const char *startSpecifier, unsigned specifierLen,
3148 void HandleNonStandardLengthModifier(
3149 const analyze_format_string::FormatSpecifier &FS,
3150 const char *startSpecifier, unsigned specifierLen);
3152 void HandleNonStandardConversionSpecifier(
3153 const analyze_format_string::ConversionSpecifier &CS,
3154 const char *startSpecifier, unsigned specifierLen);
3156 void HandlePosition(const char *startPos, unsigned posLen) override;
3158 void HandleInvalidPosition(const char *startSpecifier,
3159 unsigned specifierLen,
3160 analyze_format_string::PositionContext p) override;
3162 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
3164 void HandleNullChar(const char *nullCharacter) override;
3166 template <typename Range>
3167 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3168 const Expr *ArgumentExpr,
3169 PartialDiagnostic PDiag,
3170 SourceLocation StringLoc,
3171 bool IsStringLocation, Range StringRange,
3172 ArrayRef<FixItHint> Fixit = None);
3175 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3176 const char *startSpec,
3177 unsigned specifierLen,
3178 const char *csStart, unsigned csLen);
3180 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3181 const char *startSpec,
3182 unsigned specifierLen);
3184 SourceRange getFormatStringRange();
3185 CharSourceRange getSpecifierRange(const char *startSpecifier,
3186 unsigned specifierLen);
3187 SourceLocation getLocationOfByte(const char *x);
3189 const Expr *getDataArg(unsigned i) const;
3191 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3192 const analyze_format_string::ConversionSpecifier &CS,
3193 const char *startSpecifier, unsigned specifierLen,
3196 template <typename Range>
3197 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3198 bool IsStringLocation, Range StringRange,
3199 ArrayRef<FixItHint> Fixit = None);
3203 SourceRange CheckFormatHandler::getFormatStringRange() {
3204 return OrigFormatExpr->getSourceRange();
3207 CharSourceRange CheckFormatHandler::
3208 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
3209 SourceLocation Start = getLocationOfByte(startSpecifier);
3210 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3212 // Advance the end SourceLocation by one due to half-open ranges.
3213 End = End.getLocWithOffset(1);
3215 return CharSourceRange::getCharRange(Start, End);
3218 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
3219 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
3222 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3223 unsigned specifierLen){
3224 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3225 getLocationOfByte(startSpecifier),
3226 /*IsStringLocation*/true,
3227 getSpecifierRange(startSpecifier, specifierLen));
3230 void CheckFormatHandler::HandleInvalidLengthModifier(
3231 const analyze_format_string::FormatSpecifier &FS,
3232 const analyze_format_string::ConversionSpecifier &CS,
3233 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
3234 using namespace analyze_format_string;
3236 const LengthModifier &LM = FS.getLengthModifier();
3237 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3239 // See if we know how to fix this length modifier.
3240 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
3242 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
3243 getLocationOfByte(LM.getStart()),
3244 /*IsStringLocation*/true,
3245 getSpecifierRange(startSpecifier, specifierLen));
3247 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3248 << FixedLM->toString()
3249 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3253 if (DiagID == diag::warn_format_nonsensical_length)
3254 Hint = FixItHint::CreateRemoval(LMRange);
3256 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
3257 getLocationOfByte(LM.getStart()),
3258 /*IsStringLocation*/true,
3259 getSpecifierRange(startSpecifier, specifierLen),
3264 void CheckFormatHandler::HandleNonStandardLengthModifier(
3265 const analyze_format_string::FormatSpecifier &FS,
3266 const char *startSpecifier, unsigned specifierLen) {
3267 using namespace analyze_format_string;
3269 const LengthModifier &LM = FS.getLengthModifier();
3270 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3272 // See if we know how to fix this length modifier.
3273 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
3275 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3276 << LM.toString() << 0,
3277 getLocationOfByte(LM.getStart()),
3278 /*IsStringLocation*/true,
3279 getSpecifierRange(startSpecifier, specifierLen));
3281 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3282 << FixedLM->toString()
3283 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3286 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3287 << LM.toString() << 0,
3288 getLocationOfByte(LM.getStart()),
3289 /*IsStringLocation*/true,
3290 getSpecifierRange(startSpecifier, specifierLen));
3294 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3295 const analyze_format_string::ConversionSpecifier &CS,
3296 const char *startSpecifier, unsigned specifierLen) {
3297 using namespace analyze_format_string;
3299 // See if we know how to fix this conversion specifier.
3300 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
3302 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3303 << CS.toString() << /*conversion specifier*/1,
3304 getLocationOfByte(CS.getStart()),
3305 /*IsStringLocation*/true,
3306 getSpecifierRange(startSpecifier, specifierLen));
3308 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3309 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3310 << FixedCS->toString()
3311 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3313 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3314 << CS.toString() << /*conversion specifier*/1,
3315 getLocationOfByte(CS.getStart()),
3316 /*IsStringLocation*/true,
3317 getSpecifierRange(startSpecifier, specifierLen));
3321 void CheckFormatHandler::HandlePosition(const char *startPos,
3323 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3324 getLocationOfByte(startPos),
3325 /*IsStringLocation*/true,
3326 getSpecifierRange(startPos, posLen));
3330 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3331 analyze_format_string::PositionContext p) {
3332 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3334 getLocationOfByte(startPos), /*IsStringLocation*/true,
3335 getSpecifierRange(startPos, posLen));
3338 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
3340 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3341 getLocationOfByte(startPos),
3342 /*IsStringLocation*/true,
3343 getSpecifierRange(startPos, posLen));
3346 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
3347 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
3348 // The presence of a null character is likely an error.
3349 EmitFormatDiagnostic(
3350 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3351 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3352 getFormatStringRange());
3356 // Note that this may return NULL if there was an error parsing or building
3357 // one of the argument expressions.
3358 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
3359 return Args[FirstDataArg + i];
3362 void CheckFormatHandler::DoneProcessing() {
3363 // Does the number of data arguments exceed the number of
3364 // format conversions in the format string?
3365 if (!HasVAListArg) {
3366 // Find any arguments that weren't covered.
3368 signed notCoveredArg = CoveredArgs.find_first();
3369 if (notCoveredArg >= 0) {
3370 assert((unsigned)notCoveredArg < NumDataArgs);
3371 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3372 SourceLocation Loc = E->getLocStart();
3373 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3374 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3375 Loc, /*IsStringLocation*/false,
3376 getFormatStringRange());
3384 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3386 const char *startSpec,
3387 unsigned specifierLen,
3388 const char *csStart,
3391 bool keepGoing = true;
3392 if (argIndex < NumDataArgs) {
3393 // Consider the argument coverered, even though the specifier doesn't
3395 CoveredArgs.set(argIndex);
3398 // If argIndex exceeds the number of data arguments we
3399 // don't issue a warning because that is just a cascade of warnings (and
3400 // they may have intended '%%' anyway). We don't want to continue processing
3401 // the format string after this point, however, as we will like just get
3402 // gibberish when trying to match arguments.
3406 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3407 << StringRef(csStart, csLen),
3408 Loc, /*IsStringLocation*/true,
3409 getSpecifierRange(startSpec, specifierLen));
3415 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3416 const char *startSpec,
3417 unsigned specifierLen) {
3418 EmitFormatDiagnostic(
3419 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3420 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3424 CheckFormatHandler::CheckNumArgs(
3425 const analyze_format_string::FormatSpecifier &FS,
3426 const analyze_format_string::ConversionSpecifier &CS,
3427 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3429 if (argIndex >= NumDataArgs) {
3430 PartialDiagnostic PDiag = FS.usesPositionalArg()
3431 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3432 << (argIndex+1) << NumDataArgs)
3433 : S.PDiag(diag::warn_printf_insufficient_data_args);
3434 EmitFormatDiagnostic(
3435 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3436 getSpecifierRange(startSpecifier, specifierLen));
3442 template<typename Range>
3443 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3445 bool IsStringLocation,
3447 ArrayRef<FixItHint> FixIt) {
3448 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
3449 Loc, IsStringLocation, StringRange, FixIt);
3452 /// \brief If the format string is not within the funcion call, emit a note
3453 /// so that the function call and string are in diagnostic messages.
3455 /// \param InFunctionCall if true, the format string is within the function
3456 /// call and only one diagnostic message will be produced. Otherwise, an
3457 /// extra note will be emitted pointing to location of the format string.
3459 /// \param ArgumentExpr the expression that is passed as the format string
3460 /// argument in the function call. Used for getting locations when two
3461 /// diagnostics are emitted.
3463 /// \param PDiag the callee should already have provided any strings for the
3464 /// diagnostic message. This function only adds locations and fixits
3467 /// \param Loc primary location for diagnostic. If two diagnostics are
3468 /// required, one will be at Loc and a new SourceLocation will be created for
3471 /// \param IsStringLocation if true, Loc points to the format string should be
3472 /// used for the note. Otherwise, Loc points to the argument list and will
3473 /// be used with PDiag.
3475 /// \param StringRange some or all of the string to highlight. This is
3476 /// templated so it can accept either a CharSourceRange or a SourceRange.
3478 /// \param FixIt optional fix it hint for the format string.
3479 template<typename Range>
3480 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3481 const Expr *ArgumentExpr,
3482 PartialDiagnostic PDiag,
3484 bool IsStringLocation,
3486 ArrayRef<FixItHint> FixIt) {
3487 if (InFunctionCall) {
3488 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3492 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3493 << ArgumentExpr->getSourceRange();
3495 const Sema::SemaDiagnosticBuilder &Note =
3496 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3497 diag::note_format_string_defined);
3499 Note << StringRange;
3504 //===--- CHECK: Printf format string checking ------------------------------===//
3507 class CheckPrintfHandler : public CheckFormatHandler {
3510 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3511 const Expr *origFormatExpr, unsigned firstDataArg,
3512 unsigned numDataArgs, bool isObjC,
3513 const char *beg, bool hasVAListArg,
3514 ArrayRef<const Expr *> Args,
3515 unsigned formatIdx, bool inFunctionCall,
3516 Sema::VariadicCallType CallType,
3517 llvm::SmallBitVector &CheckedVarArgs)
3518 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3519 numDataArgs, beg, hasVAListArg, Args,
3520 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3525 bool HandleInvalidPrintfConversionSpecifier(
3526 const analyze_printf::PrintfSpecifier &FS,
3527 const char *startSpecifier,
3528 unsigned specifierLen) override;
3530 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3531 const char *startSpecifier,
3532 unsigned specifierLen) override;
3533 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3534 const char *StartSpecifier,
3535 unsigned SpecifierLen,
3538 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3539 const char *startSpecifier, unsigned specifierLen);
3540 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3541 const analyze_printf::OptionalAmount &Amt,
3543 const char *startSpecifier, unsigned specifierLen);
3544 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3545 const analyze_printf::OptionalFlag &flag,
3546 const char *startSpecifier, unsigned specifierLen);
3547 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3548 const analyze_printf::OptionalFlag &ignoredFlag,
3549 const analyze_printf::OptionalFlag &flag,
3550 const char *startSpecifier, unsigned specifierLen);
3551 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
3557 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3558 const analyze_printf::PrintfSpecifier &FS,
3559 const char *startSpecifier,
3560 unsigned specifierLen) {
3561 const analyze_printf::PrintfConversionSpecifier &CS =
3562 FS.getConversionSpecifier();
3564 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3565 getLocationOfByte(CS.getStart()),
3566 startSpecifier, specifierLen,
3567 CS.getStart(), CS.getLength());
3570 bool CheckPrintfHandler::HandleAmount(
3571 const analyze_format_string::OptionalAmount &Amt,
3572 unsigned k, const char *startSpecifier,
3573 unsigned specifierLen) {
3575 if (Amt.hasDataArgument()) {
3576 if (!HasVAListArg) {
3577 unsigned argIndex = Amt.getArgIndex();
3578 if (argIndex >= NumDataArgs) {
3579 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3581 getLocationOfByte(Amt.getStart()),
3582 /*IsStringLocation*/true,
3583 getSpecifierRange(startSpecifier, specifierLen));
3584 // Don't do any more checking. We will just emit
3589 // Type check the data argument. It should be an 'int'.
3590 // Although not in conformance with C99, we also allow the argument to be
3591 // an 'unsigned int' as that is a reasonably safe case. GCC also
3592 // doesn't emit a warning for that case.
3593 CoveredArgs.set(argIndex);
3594 const Expr *Arg = getDataArg(argIndex);
3598 QualType T = Arg->getType();
3600 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3601 assert(AT.isValid());
3603 if (!AT.matchesType(S.Context, T)) {
3604 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
3605 << k << AT.getRepresentativeTypeName(S.Context)
3606 << T << Arg->getSourceRange(),
3607 getLocationOfByte(Amt.getStart()),
3608 /*IsStringLocation*/true,
3609 getSpecifierRange(startSpecifier, specifierLen));
3610 // Don't do any more checking. We will just emit
3619 void CheckPrintfHandler::HandleInvalidAmount(
3620 const analyze_printf::PrintfSpecifier &FS,
3621 const analyze_printf::OptionalAmount &Amt,
3623 const char *startSpecifier,
3624 unsigned specifierLen) {
3625 const analyze_printf::PrintfConversionSpecifier &CS =
3626 FS.getConversionSpecifier();
3629 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3630 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3631 Amt.getConstantLength()))
3634 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3635 << type << CS.toString(),
3636 getLocationOfByte(Amt.getStart()),
3637 /*IsStringLocation*/true,
3638 getSpecifierRange(startSpecifier, specifierLen),
3642 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3643 const analyze_printf::OptionalFlag &flag,
3644 const char *startSpecifier,
3645 unsigned specifierLen) {
3646 // Warn about pointless flag with a fixit removal.
3647 const analyze_printf::PrintfConversionSpecifier &CS =
3648 FS.getConversionSpecifier();
3649 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3650 << flag.toString() << CS.toString(),
3651 getLocationOfByte(flag.getPosition()),
3652 /*IsStringLocation*/true,
3653 getSpecifierRange(startSpecifier, specifierLen),
3654 FixItHint::CreateRemoval(
3655 getSpecifierRange(flag.getPosition(), 1)));
3658 void CheckPrintfHandler::HandleIgnoredFlag(
3659 const analyze_printf::PrintfSpecifier &FS,
3660 const analyze_printf::OptionalFlag &ignoredFlag,
3661 const analyze_printf::OptionalFlag &flag,
3662 const char *startSpecifier,
3663 unsigned specifierLen) {
3664 // Warn about ignored flag with a fixit removal.
3665 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3666 << ignoredFlag.toString() << flag.toString(),
3667 getLocationOfByte(ignoredFlag.getPosition()),
3668 /*IsStringLocation*/true,
3669 getSpecifierRange(startSpecifier, specifierLen),
3670 FixItHint::CreateRemoval(
3671 getSpecifierRange(ignoredFlag.getPosition(), 1)));
3674 // Determines if the specified is a C++ class or struct containing
3675 // a member with the specified name and kind (e.g. a CXXMethodDecl named
3677 template<typename MemberKind>
3678 static llvm::SmallPtrSet<MemberKind*, 1>
3679 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3680 const RecordType *RT = Ty->getAs<RecordType>();
3681 llvm::SmallPtrSet<MemberKind*, 1> Results;
3685 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
3686 if (!RD || !RD->getDefinition())
3689 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
3690 Sema::LookupMemberName);
3691 R.suppressDiagnostics();
3693 // We just need to include all members of the right kind turned up by the
3694 // filter, at this point.
3695 if (S.LookupQualifiedName(R, RT->getDecl()))
3696 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3697 NamedDecl *decl = (*I)->getUnderlyingDecl();
3698 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3704 /// Check if we could call '.c_str()' on an object.
3706 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3707 /// allow the call, or if it would be ambiguous).
3708 bool Sema::hasCStrMethod(const Expr *E) {
3709 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3711 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3712 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3714 if ((*MI)->getMinRequiredArguments() == 0)
3719 // Check if a (w)string was passed when a (w)char* was needed, and offer a
3720 // better diagnostic if so. AT is assumed to be valid.
3721 // Returns true when a c_str() conversion method is found.
3722 bool CheckPrintfHandler::checkForCStrMembers(
3723 const analyze_printf::ArgType &AT, const Expr *E) {
3724 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3727 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3729 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3731 const CXXMethodDecl *Method = *MI;
3732 if (Method->getMinRequiredArguments() == 0 &&
3733 AT.matchesType(S.Context, Method->getReturnType())) {
3734 // FIXME: Suggest parens if the expression needs them.
3735 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
3736 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3738 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3747 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
3749 const char *startSpecifier,
3750 unsigned specifierLen) {
3752 using namespace analyze_format_string;
3753 using namespace analyze_printf;
3754 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
3756 if (FS.consumesDataArgument()) {
3759 usesPositionalArgs = FS.usesPositionalArg();
3761 else if (usesPositionalArgs != FS.usesPositionalArg()) {
3762 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3763 startSpecifier, specifierLen);
3768 // First check if the field width, precision, and conversion specifier
3769 // have matching data arguments.
3770 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3771 startSpecifier, specifierLen)) {
3775 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3776 startSpecifier, specifierLen)) {
3780 if (!CS.consumesDataArgument()) {
3781 // FIXME: Technically specifying a precision or field width here
3782 // makes no sense. Worth issuing a warning at some point.
3786 // Consume the argument.
3787 unsigned argIndex = FS.getArgIndex();
3788 if (argIndex < NumDataArgs) {
3789 // The check to see if the argIndex is valid will come later.
3790 // We set the bit here because we may exit early from this
3791 // function if we encounter some other error.
3792 CoveredArgs.set(argIndex);
3795 // FreeBSD kernel extensions.
3796 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3797 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3798 // We need at least two arguments.
3799 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3802 // Claim the second argument.
3803 CoveredArgs.set(argIndex + 1);
3805 // Type check the first argument (int for %b, pointer for %D)
3806 const Expr *Ex = getDataArg(argIndex);
3807 const analyze_printf::ArgType &AT =
3808 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3809 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3810 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3811 EmitFormatDiagnostic(
3812 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3813 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3814 << false << Ex->getSourceRange(),
3815 Ex->getLocStart(), /*IsStringLocation*/false,
3816 getSpecifierRange(startSpecifier, specifierLen));
3818 // Type check the second argument (char * for both %b and %D)
3819 Ex = getDataArg(argIndex + 1);
3820 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3821 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3822 EmitFormatDiagnostic(
3823 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3824 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3825 << false << Ex->getSourceRange(),
3826 Ex->getLocStart(), /*IsStringLocation*/false,
3827 getSpecifierRange(startSpecifier, specifierLen));
3832 // Check for using an Objective-C specific conversion specifier
3833 // in a non-ObjC literal.
3834 if (!ObjCContext && CS.isObjCArg()) {
3835 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3839 // Check for invalid use of field width
3840 if (!FS.hasValidFieldWidth()) {
3841 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
3842 startSpecifier, specifierLen);
3845 // Check for invalid use of precision
3846 if (!FS.hasValidPrecision()) {
3847 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3848 startSpecifier, specifierLen);
3851 // Check each flag does not conflict with any other component.
3852 if (!FS.hasValidThousandsGroupingPrefix())
3853 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3854 if (!FS.hasValidLeadingZeros())
3855 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3856 if (!FS.hasValidPlusPrefix())
3857 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3858 if (!FS.hasValidSpacePrefix())
3859 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3860 if (!FS.hasValidAlternativeForm())
3861 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3862 if (!FS.hasValidLeftJustified())
3863 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3865 // Check that flags are not ignored by another flag
3866 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3867 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3868 startSpecifier, specifierLen);
3869 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3870 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3871 startSpecifier, specifierLen);
3873 // Check the length modifier is valid with the given conversion specifier.
3874 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3875 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3876 diag::warn_format_nonsensical_length);
3877 else if (!FS.hasStandardLengthModifier())
3878 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3879 else if (!FS.hasStandardLengthConversionCombination())
3880 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3881 diag::warn_format_non_standard_conversion_spec);
3883 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3884 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3886 // The remaining checks depend on the data arguments.
3890 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3893 const Expr *Arg = getDataArg(argIndex);
3897 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3900 static bool requiresParensToAddCast(const Expr *E) {
3901 // FIXME: We should have a general way to reason about operator
3902 // precedence and whether parens are actually needed here.
3903 // Take care of a few common cases where they aren't.
3904 const Expr *Inside = E->IgnoreImpCasts();
3905 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3906 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3908 switch (Inside->getStmtClass()) {
3909 case Stmt::ArraySubscriptExprClass:
3910 case Stmt::CallExprClass:
3911 case Stmt::CharacterLiteralClass:
3912 case Stmt::CXXBoolLiteralExprClass:
3913 case Stmt::DeclRefExprClass:
3914 case Stmt::FloatingLiteralClass:
3915 case Stmt::IntegerLiteralClass:
3916 case Stmt::MemberExprClass:
3917 case Stmt::ObjCArrayLiteralClass:
3918 case Stmt::ObjCBoolLiteralExprClass:
3919 case Stmt::ObjCBoxedExprClass:
3920 case Stmt::ObjCDictionaryLiteralClass:
3921 case Stmt::ObjCEncodeExprClass:
3922 case Stmt::ObjCIvarRefExprClass:
3923 case Stmt::ObjCMessageExprClass:
3924 case Stmt::ObjCPropertyRefExprClass:
3925 case Stmt::ObjCStringLiteralClass:
3926 case Stmt::ObjCSubscriptRefExprClass:
3927 case Stmt::ParenExprClass:
3928 case Stmt::StringLiteralClass:
3929 case Stmt::UnaryOperatorClass:
3936 static std::pair<QualType, StringRef>
3937 shouldNotPrintDirectly(const ASTContext &Context,
3938 QualType IntendedTy,
3940 // Use a 'while' to peel off layers of typedefs.
3941 QualType TyTy = IntendedTy;
3942 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3943 StringRef Name = UserTy->getDecl()->getName();
3944 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3945 .Case("NSInteger", Context.LongTy)
3946 .Case("NSUInteger", Context.UnsignedLongTy)
3947 .Case("SInt32", Context.IntTy)
3948 .Case("UInt32", Context.UnsignedIntTy)
3949 .Default(QualType());
3951 if (!CastTy.isNull())
3952 return std::make_pair(CastTy, Name);
3954 TyTy = UserTy->desugar();
3957 // Strip parens if necessary.
3958 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3959 return shouldNotPrintDirectly(Context,
3960 PE->getSubExpr()->getType(),
3963 // If this is a conditional expression, then its result type is constructed
3964 // via usual arithmetic conversions and thus there might be no necessary
3965 // typedef sugar there. Recurse to operands to check for NSInteger &
3966 // Co. usage condition.
3967 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3968 QualType TrueTy, FalseTy;
3969 StringRef TrueName, FalseName;
3971 std::tie(TrueTy, TrueName) =
3972 shouldNotPrintDirectly(Context,
3973 CO->getTrueExpr()->getType(),
3975 std::tie(FalseTy, FalseName) =
3976 shouldNotPrintDirectly(Context,
3977 CO->getFalseExpr()->getType(),
3978 CO->getFalseExpr());
3980 if (TrueTy == FalseTy)
3981 return std::make_pair(TrueTy, TrueName);
3982 else if (TrueTy.isNull())
3983 return std::make_pair(FalseTy, FalseName);
3984 else if (FalseTy.isNull())
3985 return std::make_pair(TrueTy, TrueName);
3988 return std::make_pair(QualType(), StringRef());
3992 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3993 const char *StartSpecifier,
3994 unsigned SpecifierLen,
3996 using namespace analyze_format_string;
3997 using namespace analyze_printf;
3998 // Now type check the data expression that matches the
3999 // format specifier.
4000 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4005 QualType ExprTy = E->getType();
4006 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4007 ExprTy = TET->getUnderlyingExpr()->getType();
4010 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4012 if (match == analyze_printf::ArgType::Match) {
4016 // Look through argument promotions for our error message's reported type.
4017 // This includes the integral and floating promotions, but excludes array
4018 // and function pointer decay; seeing that an argument intended to be a
4019 // string has type 'char [6]' is probably more confusing than 'char *'.
4020 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4021 if (ICE->getCastKind() == CK_IntegralCast ||
4022 ICE->getCastKind() == CK_FloatingCast) {
4023 E = ICE->getSubExpr();
4024 ExprTy = E->getType();
4026 // Check if we didn't match because of an implicit cast from a 'char'
4027 // or 'short' to an 'int'. This is done because printf is a varargs
4029 if (ICE->getType() == S.Context.IntTy ||
4030 ICE->getType() == S.Context.UnsignedIntTy) {
4031 // All further checking is done on the subexpression.
4032 if (AT.matchesType(S.Context, ExprTy))
4036 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4037 // Special case for 'a', which has type 'int' in C.
4038 // Note, however, that we do /not/ want to treat multibyte constants like
4039 // 'MooV' as characters! This form is deprecated but still exists.
4040 if (ExprTy == S.Context.IntTy)
4041 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4042 ExprTy = S.Context.CharTy;
4045 // Look through enums to their underlying type.
4046 bool IsEnum = false;
4047 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4048 ExprTy = EnumTy->getDecl()->getIntegerType();
4052 // %C in an Objective-C context prints a unichar, not a wchar_t.
4053 // If the argument is an integer of some kind, believe the %C and suggest
4054 // a cast instead of changing the conversion specifier.
4055 QualType IntendedTy = ExprTy;
4057 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4058 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4059 !ExprTy->isCharType()) {
4060 // 'unichar' is defined as a typedef of unsigned short, but we should
4061 // prefer using the typedef if it is visible.
4062 IntendedTy = S.Context.UnsignedShortTy;
4064 // While we are here, check if the value is an IntegerLiteral that happens
4065 // to be within the valid range.
4066 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4067 const llvm::APInt &V = IL->getValue();
4068 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4072 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4073 Sema::LookupOrdinaryName);
4074 if (S.LookupName(Result, S.getCurScope())) {
4075 NamedDecl *ND = Result.getFoundDecl();
4076 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4077 if (TD->getUnderlyingType() == IntendedTy)
4078 IntendedTy = S.Context.getTypedefType(TD);
4083 // Special-case some of Darwin's platform-independence types by suggesting
4084 // casts to primitive types that are known to be large enough.
4085 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
4086 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
4088 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4089 if (!CastTy.isNull()) {
4090 IntendedTy = CastTy;
4091 ShouldNotPrintDirectly = true;
4095 // We may be able to offer a FixItHint if it is a supported type.
4096 PrintfSpecifier fixedFS = FS;
4097 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
4098 S.Context, ObjCContext);
4101 // Get the fix string from the fixed format specifier
4102 SmallString<16> buf;
4103 llvm::raw_svector_ostream os(buf);
4104 fixedFS.toString(os);
4106 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4108 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
4109 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4110 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4111 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4113 // In this case, the specifier is wrong and should be changed to match
4115 EmitFormatDiagnostic(S.PDiag(diag)
4116 << AT.getRepresentativeTypeName(S.Context)
4117 << IntendedTy << IsEnum << E->getSourceRange(),
4119 /*IsStringLocation*/ false, SpecRange,
4120 FixItHint::CreateReplacement(SpecRange, os.str()));
4123 // The canonical type for formatting this value is different from the
4124 // actual type of the expression. (This occurs, for example, with Darwin's
4125 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4126 // should be printed as 'long' for 64-bit compatibility.)
4127 // Rather than emitting a normal format/argument mismatch, we want to
4128 // add a cast to the recommended type (and correct the format string
4130 SmallString<16> CastBuf;
4131 llvm::raw_svector_ostream CastFix(CastBuf);
4133 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4136 SmallVector<FixItHint,4> Hints;
4137 if (!AT.matchesType(S.Context, IntendedTy))
4138 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4140 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4141 // If there's already a cast present, just replace it.
4142 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4143 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4145 } else if (!requiresParensToAddCast(E)) {
4146 // If the expression has high enough precedence,
4147 // just write the C-style cast.
4148 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4151 // Otherwise, add parens around the expression as well as the cast.
4153 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4156 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
4157 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4160 if (ShouldNotPrintDirectly) {
4161 // The expression has a type that should not be printed directly.
4162 // We extract the name from the typedef because we don't want to show
4163 // the underlying type in the diagnostic.
4165 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4166 Name = TypedefTy->getDecl()->getName();
4169 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
4170 << Name << IntendedTy << IsEnum
4171 << E->getSourceRange(),
4172 E->getLocStart(), /*IsStringLocation=*/false,
4175 // In this case, the expression could be printed using a different
4176 // specifier, but we've decided that the specifier is probably correct
4177 // and we should cast instead. Just use the normal warning message.
4178 EmitFormatDiagnostic(
4179 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4180 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
4181 << E->getSourceRange(),
4182 E->getLocStart(), /*IsStringLocation*/false,
4187 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4189 // Since the warning for passing non-POD types to variadic functions
4190 // was deferred until now, we emit a warning for non-POD
4192 switch (S.isValidVarArgType(ExprTy)) {
4193 case Sema::VAK_Valid:
4194 case Sema::VAK_ValidInCXX11: {
4195 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4196 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4197 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4200 EmitFormatDiagnostic(
4201 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4202 << IsEnum << CSR << E->getSourceRange(),
4203 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4206 case Sema::VAK_Undefined:
4207 case Sema::VAK_MSVCUndefined:
4208 EmitFormatDiagnostic(
4209 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
4210 << S.getLangOpts().CPlusPlus11
4213 << AT.getRepresentativeTypeName(S.Context)
4215 << E->getSourceRange(),
4216 E->getLocStart(), /*IsStringLocation*/false, CSR);
4217 checkForCStrMembers(AT, E);
4220 case Sema::VAK_Invalid:
4221 if (ExprTy->isObjCObjectType())
4222 EmitFormatDiagnostic(
4223 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4224 << S.getLangOpts().CPlusPlus11
4227 << AT.getRepresentativeTypeName(S.Context)
4229 << E->getSourceRange(),
4230 E->getLocStart(), /*IsStringLocation*/false, CSR);
4232 // FIXME: If this is an initializer list, suggest removing the braces
4233 // or inserting a cast to the target type.
4234 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4235 << isa<InitListExpr>(E) << ExprTy << CallType
4236 << AT.getRepresentativeTypeName(S.Context)
4237 << E->getSourceRange();
4241 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4242 "format string specifier index out of range");
4243 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
4249 //===--- CHECK: Scanf format string checking ------------------------------===//
4252 class CheckScanfHandler : public CheckFormatHandler {
4254 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4255 const Expr *origFormatExpr, unsigned firstDataArg,
4256 unsigned numDataArgs, const char *beg, bool hasVAListArg,
4257 ArrayRef<const Expr *> Args,
4258 unsigned formatIdx, bool inFunctionCall,
4259 Sema::VariadicCallType CallType,
4260 llvm::SmallBitVector &CheckedVarArgs)
4261 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4262 numDataArgs, beg, hasVAListArg,
4263 Args, formatIdx, inFunctionCall, CallType,
4267 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4268 const char *startSpecifier,
4269 unsigned specifierLen) override;
4271 bool HandleInvalidScanfConversionSpecifier(
4272 const analyze_scanf::ScanfSpecifier &FS,
4273 const char *startSpecifier,
4274 unsigned specifierLen) override;
4276 void HandleIncompleteScanList(const char *start, const char *end) override;
4280 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4282 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4283 getLocationOfByte(end), /*IsStringLocation*/true,
4284 getSpecifierRange(start, end - start));
4287 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4288 const analyze_scanf::ScanfSpecifier &FS,
4289 const char *startSpecifier,
4290 unsigned specifierLen) {
4292 const analyze_scanf::ScanfConversionSpecifier &CS =
4293 FS.getConversionSpecifier();
4295 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4296 getLocationOfByte(CS.getStart()),
4297 startSpecifier, specifierLen,
4298 CS.getStart(), CS.getLength());
4301 bool CheckScanfHandler::HandleScanfSpecifier(
4302 const analyze_scanf::ScanfSpecifier &FS,
4303 const char *startSpecifier,
4304 unsigned specifierLen) {
4306 using namespace analyze_scanf;
4307 using namespace analyze_format_string;
4309 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
4311 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4312 // be used to decide if we are using positional arguments consistently.
4313 if (FS.consumesDataArgument()) {
4316 usesPositionalArgs = FS.usesPositionalArg();
4318 else if (usesPositionalArgs != FS.usesPositionalArg()) {
4319 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4320 startSpecifier, specifierLen);
4325 // Check if the field with is non-zero.
4326 const OptionalAmount &Amt = FS.getFieldWidth();
4327 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4328 if (Amt.getConstantAmount() == 0) {
4329 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4330 Amt.getConstantLength());
4331 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4332 getLocationOfByte(Amt.getStart()),
4333 /*IsStringLocation*/true, R,
4334 FixItHint::CreateRemoval(R));
4338 if (!FS.consumesDataArgument()) {
4339 // FIXME: Technically specifying a precision or field width here
4340 // makes no sense. Worth issuing a warning at some point.
4344 // Consume the argument.
4345 unsigned argIndex = FS.getArgIndex();
4346 if (argIndex < NumDataArgs) {
4347 // The check to see if the argIndex is valid will come later.
4348 // We set the bit here because we may exit early from this
4349 // function if we encounter some other error.
4350 CoveredArgs.set(argIndex);
4353 // Check the length modifier is valid with the given conversion specifier.
4354 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
4355 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4356 diag::warn_format_nonsensical_length);
4357 else if (!FS.hasStandardLengthModifier())
4358 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
4359 else if (!FS.hasStandardLengthConversionCombination())
4360 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4361 diag::warn_format_non_standard_conversion_spec);
4363 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4364 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4366 // The remaining checks depend on the data arguments.
4370 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
4373 // Check that the argument type matches the format specifier.
4374 const Expr *Ex = getDataArg(argIndex);
4378 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
4380 if (!AT.isValid()) {
4384 analyze_format_string::ArgType::MatchKind match =
4385 AT.matchesType(S.Context, Ex->getType());
4386 if (match == analyze_format_string::ArgType::Match) {
4390 ScanfSpecifier fixedFS = FS;
4391 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4392 S.getLangOpts(), S.Context);
4394 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4395 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4396 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4400 // Get the fix string from the fixed format specifier.
4401 SmallString<128> buf;
4402 llvm::raw_svector_ostream os(buf);
4403 fixedFS.toString(os);
4405 EmitFormatDiagnostic(
4406 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4407 << Ex->getType() << false << Ex->getSourceRange(),
4409 /*IsStringLocation*/ false,
4410 getSpecifierRange(startSpecifier, specifierLen),
4411 FixItHint::CreateReplacement(
4412 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4414 EmitFormatDiagnostic(S.PDiag(diag)
4415 << AT.getRepresentativeTypeName(S.Context)
4416 << Ex->getType() << false << Ex->getSourceRange(),
4418 /*IsStringLocation*/ false,
4419 getSpecifierRange(startSpecifier, specifierLen));
4425 void Sema::CheckFormatString(const StringLiteral *FExpr,
4426 const Expr *OrigFormatExpr,
4427 ArrayRef<const Expr *> Args,
4428 bool HasVAListArg, unsigned format_idx,
4429 unsigned firstDataArg, FormatStringType Type,
4430 bool inFunctionCall, VariadicCallType CallType,
4431 llvm::SmallBitVector &CheckedVarArgs) {
4433 // CHECK: is the format string a wide literal?
4434 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
4435 CheckFormatHandler::EmitFormatDiagnostic(
4436 *this, inFunctionCall, Args[format_idx],
4437 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4438 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
4442 // Str - The format string. NOTE: this is NOT null-terminated!
4443 StringRef StrRef = FExpr->getString();
4444 const char *Str = StrRef.data();
4445 // Account for cases where the string literal is truncated in a declaration.
4446 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4447 assert(T && "String literal not of constant array type!");
4448 size_t TypeSize = T->getSize().getZExtValue();
4449 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4450 const unsigned numDataArgs = Args.size() - firstDataArg;
4452 // Emit a warning if the string literal is truncated and does not contain an
4453 // embedded null character.
4454 if (TypeSize <= StrRef.size() &&
4455 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4456 CheckFormatHandler::EmitFormatDiagnostic(
4457 *this, inFunctionCall, Args[format_idx],
4458 PDiag(diag::warn_printf_format_string_not_null_terminated),
4459 FExpr->getLocStart(),
4460 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4464 // CHECK: empty format string?
4465 if (StrLen == 0 && numDataArgs > 0) {
4466 CheckFormatHandler::EmitFormatDiagnostic(
4467 *this, inFunctionCall, Args[format_idx],
4468 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4469 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
4473 if (Type == FST_Printf || Type == FST_NSString ||
4474 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
4475 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
4476 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
4477 Str, HasVAListArg, Args, format_idx,
4478 inFunctionCall, CallType, CheckedVarArgs);
4480 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
4482 Context.getTargetInfo(),
4483 Type == FST_FreeBSDKPrintf))
4485 } else if (Type == FST_Scanf) {
4486 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
4487 Str, HasVAListArg, Args, format_idx,
4488 inFunctionCall, CallType, CheckedVarArgs);
4490 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
4492 Context.getTargetInfo()))
4494 } // TODO: handle other formats
4497 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4498 // Str - The format string. NOTE: this is NOT null-terminated!
4499 StringRef StrRef = FExpr->getString();
4500 const char *Str = StrRef.data();
4501 // Account for cases where the string literal is truncated in a declaration.
4502 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4503 assert(T && "String literal not of constant array type!");
4504 size_t TypeSize = T->getSize().getZExtValue();
4505 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4506 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4508 Context.getTargetInfo());
4511 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4513 // Returns the related absolute value function that is larger, of 0 if one
4515 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4516 switch (AbsFunction) {
4520 case Builtin::BI__builtin_abs:
4521 return Builtin::BI__builtin_labs;
4522 case Builtin::BI__builtin_labs:
4523 return Builtin::BI__builtin_llabs;
4524 case Builtin::BI__builtin_llabs:
4527 case Builtin::BI__builtin_fabsf:
4528 return Builtin::BI__builtin_fabs;
4529 case Builtin::BI__builtin_fabs:
4530 return Builtin::BI__builtin_fabsl;
4531 case Builtin::BI__builtin_fabsl:
4534 case Builtin::BI__builtin_cabsf:
4535 return Builtin::BI__builtin_cabs;
4536 case Builtin::BI__builtin_cabs:
4537 return Builtin::BI__builtin_cabsl;
4538 case Builtin::BI__builtin_cabsl:
4541 case Builtin::BIabs:
4542 return Builtin::BIlabs;
4543 case Builtin::BIlabs:
4544 return Builtin::BIllabs;
4545 case Builtin::BIllabs:
4548 case Builtin::BIfabsf:
4549 return Builtin::BIfabs;
4550 case Builtin::BIfabs:
4551 return Builtin::BIfabsl;
4552 case Builtin::BIfabsl:
4555 case Builtin::BIcabsf:
4556 return Builtin::BIcabs;
4557 case Builtin::BIcabs:
4558 return Builtin::BIcabsl;
4559 case Builtin::BIcabsl:
4564 // Returns the argument type of the absolute value function.
4565 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4570 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4571 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4572 if (Error != ASTContext::GE_None)
4575 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4579 if (FT->getNumParams() != 1)
4582 return FT->getParamType(0);
4585 // Returns the best absolute value function, or zero, based on type and
4586 // current absolute value function.
4587 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4588 unsigned AbsFunctionKind) {
4589 unsigned BestKind = 0;
4590 uint64_t ArgSize = Context.getTypeSize(ArgType);
4591 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4592 Kind = getLargerAbsoluteValueFunction(Kind)) {
4593 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4594 if (Context.getTypeSize(ParamType) >= ArgSize) {
4597 else if (Context.hasSameType(ParamType, ArgType)) {
4606 enum AbsoluteValueKind {
4612 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4613 if (T->isIntegralOrEnumerationType())
4615 if (T->isRealFloatingType())
4616 return AVK_Floating;
4617 if (T->isAnyComplexType())
4620 llvm_unreachable("Type not integer, floating, or complex");
4623 // Changes the absolute value function to a different type. Preserves whether
4624 // the function is a builtin.
4625 static unsigned changeAbsFunction(unsigned AbsKind,
4626 AbsoluteValueKind ValueKind) {
4627 switch (ValueKind) {
4632 case Builtin::BI__builtin_fabsf:
4633 case Builtin::BI__builtin_fabs:
4634 case Builtin::BI__builtin_fabsl:
4635 case Builtin::BI__builtin_cabsf:
4636 case Builtin::BI__builtin_cabs:
4637 case Builtin::BI__builtin_cabsl:
4638 return Builtin::BI__builtin_abs;
4639 case Builtin::BIfabsf:
4640 case Builtin::BIfabs:
4641 case Builtin::BIfabsl:
4642 case Builtin::BIcabsf:
4643 case Builtin::BIcabs:
4644 case Builtin::BIcabsl:
4645 return Builtin::BIabs;
4651 case Builtin::BI__builtin_abs:
4652 case Builtin::BI__builtin_labs:
4653 case Builtin::BI__builtin_llabs:
4654 case Builtin::BI__builtin_cabsf:
4655 case Builtin::BI__builtin_cabs:
4656 case Builtin::BI__builtin_cabsl:
4657 return Builtin::BI__builtin_fabsf;
4658 case Builtin::BIabs:
4659 case Builtin::BIlabs:
4660 case Builtin::BIllabs:
4661 case Builtin::BIcabsf:
4662 case Builtin::BIcabs:
4663 case Builtin::BIcabsl:
4664 return Builtin::BIfabsf;
4670 case Builtin::BI__builtin_abs:
4671 case Builtin::BI__builtin_labs:
4672 case Builtin::BI__builtin_llabs:
4673 case Builtin::BI__builtin_fabsf:
4674 case Builtin::BI__builtin_fabs:
4675 case Builtin::BI__builtin_fabsl:
4676 return Builtin::BI__builtin_cabsf;
4677 case Builtin::BIabs:
4678 case Builtin::BIlabs:
4679 case Builtin::BIllabs:
4680 case Builtin::BIfabsf:
4681 case Builtin::BIfabs:
4682 case Builtin::BIfabsl:
4683 return Builtin::BIcabsf;
4686 llvm_unreachable("Unable to convert function");
4689 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
4690 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4694 switch (FDecl->getBuiltinID()) {
4697 case Builtin::BI__builtin_abs:
4698 case Builtin::BI__builtin_fabs:
4699 case Builtin::BI__builtin_fabsf:
4700 case Builtin::BI__builtin_fabsl:
4701 case Builtin::BI__builtin_labs:
4702 case Builtin::BI__builtin_llabs:
4703 case Builtin::BI__builtin_cabs:
4704 case Builtin::BI__builtin_cabsf:
4705 case Builtin::BI__builtin_cabsl:
4706 case Builtin::BIabs:
4707 case Builtin::BIlabs:
4708 case Builtin::BIllabs:
4709 case Builtin::BIfabs:
4710 case Builtin::BIfabsf:
4711 case Builtin::BIfabsl:
4712 case Builtin::BIcabs:
4713 case Builtin::BIcabsf:
4714 case Builtin::BIcabsl:
4715 return FDecl->getBuiltinID();
4717 llvm_unreachable("Unknown Builtin type");
4720 // If the replacement is valid, emit a note with replacement function.
4721 // Additionally, suggest including the proper header if not already included.
4722 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
4723 unsigned AbsKind, QualType ArgType) {
4724 bool EmitHeaderHint = true;
4725 const char *HeaderName = nullptr;
4726 const char *FunctionName = nullptr;
4727 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4728 FunctionName = "std::abs";
4729 if (ArgType->isIntegralOrEnumerationType()) {
4730 HeaderName = "cstdlib";
4731 } else if (ArgType->isRealFloatingType()) {
4732 HeaderName = "cmath";
4734 llvm_unreachable("Invalid Type");
4737 // Lookup all std::abs
4738 if (NamespaceDecl *Std = S.getStdNamespace()) {
4739 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
4740 R.suppressDiagnostics();
4741 S.LookupQualifiedName(R, Std);
4743 for (const auto *I : R) {
4744 const FunctionDecl *FDecl = nullptr;
4745 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4746 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4748 FDecl = dyn_cast<FunctionDecl>(I);
4753 // Found std::abs(), check that they are the right ones.
4754 if (FDecl->getNumParams() != 1)
4757 // Check that the parameter type can handle the argument.
4758 QualType ParamType = FDecl->getParamDecl(0)->getType();
4759 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4760 S.Context.getTypeSize(ArgType) <=
4761 S.Context.getTypeSize(ParamType)) {
4762 // Found a function, don't need the header hint.
4763 EmitHeaderHint = false;
4769 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4770 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4773 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4774 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4775 R.suppressDiagnostics();
4776 S.LookupName(R, S.getCurScope());
4778 if (R.isSingleResult()) {
4779 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4780 if (FD && FD->getBuiltinID() == AbsKind) {
4781 EmitHeaderHint = false;
4785 } else if (!R.empty()) {
4791 S.Diag(Loc, diag::note_replace_abs_function)
4792 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
4797 if (!EmitHeaderHint)
4800 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4804 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4808 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4811 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4813 while (ND && ND->isInlineNamespace()) {
4814 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
4817 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4820 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4826 // Warn when using the wrong abs() function.
4827 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4828 const FunctionDecl *FDecl,
4829 IdentifierInfo *FnInfo) {
4830 if (Call->getNumArgs() != 1)
4833 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
4834 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4835 if (AbsKind == 0 && !IsStdAbs)
4838 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4839 QualType ParamType = Call->getArg(0)->getType();
4841 // Unsigned types cannot be negative. Suggest removing the absolute value
4843 if (ArgType->isUnsignedIntegerType()) {
4844 const char *FunctionName =
4845 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
4846 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4847 Diag(Call->getExprLoc(), diag::note_remove_abs)
4849 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4853 // std::abs has overloads which prevent most of the absolute value problems
4858 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4859 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4861 // The argument and parameter are the same kind. Check if they are the right
4863 if (ArgValueKind == ParamValueKind) {
4864 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4867 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4868 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4869 << FDecl << ArgType << ParamType;
4871 if (NewAbsKind == 0)
4874 emitReplacement(*this, Call->getExprLoc(),
4875 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
4879 // ArgValueKind != ParamValueKind
4880 // The wrong type of absolute value function was used. Attempt to find the
4882 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4883 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4884 if (NewAbsKind == 0)
4887 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4888 << FDecl << ParamValueKind << ArgValueKind;
4890 emitReplacement(*this, Call->getExprLoc(),
4891 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
4895 //===--- CHECK: Standard memory functions ---------------------------------===//
4897 /// \brief Takes the expression passed to the size_t parameter of functions
4898 /// such as memcmp, strncat, etc and warns if it's a comparison.
4900 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4901 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4902 IdentifierInfo *FnName,
4903 SourceLocation FnLoc,
4904 SourceLocation RParenLoc) {
4905 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4909 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4910 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4913 SourceRange SizeRange = Size->getSourceRange();
4914 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4915 << SizeRange << FnName;
4916 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
4917 << FnName << FixItHint::CreateInsertion(
4918 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
4919 << FixItHint::CreateRemoval(RParenLoc);
4920 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
4921 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
4922 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4928 /// \brief Determine whether the given type is or contains a dynamic class type
4929 /// (e.g., whether it has a vtable).
4930 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4931 bool &IsContained) {
4932 // Look through array types while ignoring qualifiers.
4933 const Type *Ty = T->getBaseElementTypeUnsafe();
4934 IsContained = false;
4936 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4937 RD = RD ? RD->getDefinition() : nullptr;
4941 if (RD->isDynamicClass())
4944 // Check all the fields. If any bases were dynamic, the class is dynamic.
4945 // It's impossible for a class to transitively contain itself by value, so
4946 // infinite recursion is impossible.
4947 for (auto *FD : RD->fields()) {
4949 if (const CXXRecordDecl *ContainedRD =
4950 getContainedDynamicClass(FD->getType(), SubContained)) {
4959 /// \brief If E is a sizeof expression, returns its argument expression,
4960 /// otherwise returns NULL.
4961 static const Expr *getSizeOfExprArg(const Expr *E) {
4962 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4963 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4964 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4965 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
4970 /// \brief If E is a sizeof expression, returns its argument type.
4971 static QualType getSizeOfArgType(const Expr *E) {
4972 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4973 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4974 if (SizeOf->getKind() == clang::UETT_SizeOf)
4975 return SizeOf->getTypeOfArgument();
4980 /// \brief Check for dangerous or invalid arguments to memset().
4982 /// This issues warnings on known problematic, dangerous or unspecified
4983 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4986 /// \param Call The call expression to diagnose.
4987 void Sema::CheckMemaccessArguments(const CallExpr *Call,
4989 IdentifierInfo *FnName) {
4992 // It is possible to have a non-standard definition of memset. Validate
4993 // we have enough arguments, and if not, abort further checking.
4994 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
4995 if (Call->getNumArgs() < ExpectedNumArgs)
4998 unsigned LastArg = (BId == Builtin::BImemset ||
4999 BId == Builtin::BIstrndup ? 1 : 2);
5000 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
5001 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
5003 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5004 Call->getLocStart(), Call->getRParenLoc()))
5007 // We have special checking when the length is a sizeof expression.
5008 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5009 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5010 llvm::FoldingSetNodeID SizeOfArgID;
5012 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5013 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
5014 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
5016 QualType DestTy = Dest->getType();
5018 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
5019 PointeeTy = DestPtrTy->getPointeeType();
5021 // Never warn about void type pointers. This can be used to suppress
5023 if (PointeeTy->isVoidType())
5026 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5027 // actually comparing the expressions for equality. Because computing the
5028 // expression IDs can be expensive, we only do this if the diagnostic is
5031 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5032 SizeOfArg->getExprLoc())) {
5033 // We only compute IDs for expressions if the warning is enabled, and
5034 // cache the sizeof arg's ID.
5035 if (SizeOfArgID == llvm::FoldingSetNodeID())
5036 SizeOfArg->Profile(SizeOfArgID, Context, true);
5037 llvm::FoldingSetNodeID DestID;
5038 Dest->Profile(DestID, Context, true);
5039 if (DestID == SizeOfArgID) {
5040 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5041 // over sizeof(src) as well.
5042 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
5043 StringRef ReadableName = FnName->getName();
5045 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
5046 if (UnaryOp->getOpcode() == UO_AddrOf)
5047 ActionIdx = 1; // If its an address-of operator, just remove it.
5048 if (!PointeeTy->isIncompleteType() &&
5049 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
5050 ActionIdx = 2; // If the pointee's size is sizeof(char),
5051 // suggest an explicit length.
5053 // If the function is defined as a builtin macro, do not show macro
5055 SourceLocation SL = SizeOfArg->getExprLoc();
5056 SourceRange DSR = Dest->getSourceRange();
5057 SourceRange SSR = SizeOfArg->getSourceRange();
5058 SourceManager &SM = getSourceManager();
5060 if (SM.isMacroArgExpansion(SL)) {
5061 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5062 SL = SM.getSpellingLoc(SL);
5063 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5064 SM.getSpellingLoc(DSR.getEnd()));
5065 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5066 SM.getSpellingLoc(SSR.getEnd()));
5069 DiagRuntimeBehavior(SL, SizeOfArg,
5070 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
5076 DiagRuntimeBehavior(SL, SizeOfArg,
5077 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5085 // Also check for cases where the sizeof argument is the exact same
5086 // type as the memory argument, and where it points to a user-defined
5088 if (SizeOfArgTy != QualType()) {
5089 if (PointeeTy->isRecordType() &&
5090 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5091 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5092 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5093 << FnName << SizeOfArgTy << ArgIdx
5094 << PointeeTy << Dest->getSourceRange()
5095 << LenExpr->getSourceRange());
5099 } else if (DestTy->isArrayType()) {
5103 if (PointeeTy == QualType())
5106 // Always complain about dynamic classes.
5108 if (const CXXRecordDecl *ContainedRD =
5109 getContainedDynamicClass(PointeeTy, IsContained)) {
5111 unsigned OperationType = 0;
5112 // "overwritten" if we're warning about the destination for any call
5113 // but memcmp; otherwise a verb appropriate to the call.
5114 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5115 if (BId == Builtin::BImemcpy)
5117 else if(BId == Builtin::BImemmove)
5119 else if (BId == Builtin::BImemcmp)
5123 DiagRuntimeBehavior(
5124 Dest->getExprLoc(), Dest,
5125 PDiag(diag::warn_dyn_class_memaccess)
5126 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5127 << FnName << IsContained << ContainedRD << OperationType
5128 << Call->getCallee()->getSourceRange());
5129 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5130 BId != Builtin::BImemset)
5131 DiagRuntimeBehavior(
5132 Dest->getExprLoc(), Dest,
5133 PDiag(diag::warn_arc_object_memaccess)
5134 << ArgIdx << FnName << PointeeTy
5135 << Call->getCallee()->getSourceRange());
5139 DiagRuntimeBehavior(
5140 Dest->getExprLoc(), Dest,
5141 PDiag(diag::note_bad_memaccess_silence)
5142 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5148 // A little helper routine: ignore addition and subtraction of integer literals.
5149 // This intentionally does not ignore all integer constant expressions because
5150 // we don't want to remove sizeof().
5151 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5152 Ex = Ex->IgnoreParenCasts();
5155 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5156 if (!BO || !BO->isAdditiveOp())
5159 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5160 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5162 if (isa<IntegerLiteral>(RHS))
5164 else if (isa<IntegerLiteral>(LHS))
5173 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5174 ASTContext &Context) {
5175 // Only handle constant-sized or VLAs, but not flexible members.
5176 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5177 // Only issue the FIXIT for arrays of size > 1.
5178 if (CAT->getSize().getSExtValue() <= 1)
5180 } else if (!Ty->isVariableArrayType()) {
5186 // Warn if the user has made the 'size' argument to strlcpy or strlcat
5187 // be the size of the source, instead of the destination.
5188 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5189 IdentifierInfo *FnName) {
5191 // Don't crash if the user has the wrong number of arguments
5192 unsigned NumArgs = Call->getNumArgs();
5193 if ((NumArgs != 3) && (NumArgs != 4))
5196 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5197 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
5198 const Expr *CompareWithSrc = nullptr;
5200 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5201 Call->getLocStart(), Call->getRParenLoc()))
5204 // Look for 'strlcpy(dst, x, sizeof(x))'
5205 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5206 CompareWithSrc = Ex;
5208 // Look for 'strlcpy(dst, x, strlen(x))'
5209 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
5210 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5211 SizeCall->getNumArgs() == 1)
5212 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5216 if (!CompareWithSrc)
5219 // Determine if the argument to sizeof/strlen is equal to the source
5220 // argument. In principle there's all kinds of things you could do
5221 // here, for instance creating an == expression and evaluating it with
5222 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5223 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5227 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5228 if (!CompareWithSrcDRE ||
5229 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5232 const Expr *OriginalSizeArg = Call->getArg(2);
5233 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5234 << OriginalSizeArg->getSourceRange() << FnName;
5236 // Output a FIXIT hint if the destination is an array (rather than a
5237 // pointer to an array). This could be enhanced to handle some
5238 // pointers if we know the actual size, like if DstArg is 'array+2'
5239 // we could say 'sizeof(array)-2'.
5240 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
5241 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
5244 SmallString<128> sizeString;
5245 llvm::raw_svector_ostream OS(sizeString);
5247 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5250 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5251 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5255 /// Check if two expressions refer to the same declaration.
5256 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5257 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5258 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5259 return D1->getDecl() == D2->getDecl();
5263 static const Expr *getStrlenExprArg(const Expr *E) {
5264 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5265 const FunctionDecl *FD = CE->getDirectCallee();
5266 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
5268 return CE->getArg(0)->IgnoreParenCasts();
5273 // Warn on anti-patterns as the 'size' argument to strncat.
5274 // The correct size argument should look like following:
5275 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5276 void Sema::CheckStrncatArguments(const CallExpr *CE,
5277 IdentifierInfo *FnName) {
5278 // Don't crash if the user has the wrong number of arguments.
5279 if (CE->getNumArgs() < 3)
5281 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5282 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5283 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5285 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5286 CE->getRParenLoc()))
5289 // Identify common expressions, which are wrongly used as the size argument
5290 // to strncat and may lead to buffer overflows.
5291 unsigned PatternType = 0;
5292 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5294 if (referToTheSameDecl(SizeOfArg, DstArg))
5297 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5299 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5300 if (BE->getOpcode() == BO_Sub) {
5301 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5302 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5303 // - sizeof(dst) - strlen(dst)
5304 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5305 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5307 // - sizeof(src) - (anything)
5308 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5313 if (PatternType == 0)
5316 // Generate the diagnostic.
5317 SourceLocation SL = LenArg->getLocStart();
5318 SourceRange SR = LenArg->getSourceRange();
5319 SourceManager &SM = getSourceManager();
5321 // If the function is defined as a builtin macro, do not show macro expansion.
5322 if (SM.isMacroArgExpansion(SL)) {
5323 SL = SM.getSpellingLoc(SL);
5324 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5325 SM.getSpellingLoc(SR.getEnd()));
5328 // Check if the destination is an array (rather than a pointer to an array).
5329 QualType DstTy = DstArg->getType();
5330 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5332 if (!isKnownSizeArray) {
5333 if (PatternType == 1)
5334 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5336 Diag(SL, diag::warn_strncat_src_size) << SR;
5340 if (PatternType == 1)
5341 Diag(SL, diag::warn_strncat_large_size) << SR;
5343 Diag(SL, diag::warn_strncat_src_size) << SR;
5345 SmallString<128> sizeString;
5346 llvm::raw_svector_ostream OS(sizeString);
5348 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5351 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5354 Diag(SL, diag::note_strncat_wrong_size)
5355 << FixItHint::CreateReplacement(SR, OS.str());
5358 //===--- CHECK: Return Address of Stack Variable --------------------------===//
5360 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5362 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5365 /// CheckReturnStackAddr - Check if a return statement returns the address
5366 /// of a stack variable.
5368 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5369 SourceLocation ReturnLoc) {
5371 Expr *stackE = nullptr;
5372 SmallVector<DeclRefExpr *, 8> refVars;
5374 // Perform checking for returned stack addresses, local blocks,
5375 // label addresses or references to temporaries.
5376 if (lhsType->isPointerType() ||
5377 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
5378 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
5379 } else if (lhsType->isReferenceType()) {
5380 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
5384 return; // Nothing suspicious was found.
5386 SourceLocation diagLoc;
5387 SourceRange diagRange;
5388 if (refVars.empty()) {
5389 diagLoc = stackE->getLocStart();
5390 diagRange = stackE->getSourceRange();
5392 // We followed through a reference variable. 'stackE' contains the
5393 // problematic expression but we will warn at the return statement pointing
5394 // at the reference variable. We will later display the "trail" of
5395 // reference variables using notes.
5396 diagLoc = refVars[0]->getLocStart();
5397 diagRange = refVars[0]->getSourceRange();
5400 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
5401 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
5402 : diag::warn_ret_stack_addr)
5403 << DR->getDecl()->getDeclName() << diagRange;
5404 } else if (isa<BlockExpr>(stackE)) { // local block.
5405 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
5406 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
5407 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
5408 } else { // local temporary.
5409 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5410 : diag::warn_ret_local_temp_addr)
5414 // Display the "trail" of reference variables that we followed until we
5415 // found the problematic expression using notes.
5416 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5417 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5418 // If this var binds to another reference var, show the range of the next
5419 // var, otherwise the var binds to the problematic expression, in which case
5420 // show the range of the expression.
5421 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5422 : stackE->getSourceRange();
5423 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5424 << VD->getDeclName() << range;
5428 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5429 /// check if the expression in a return statement evaluates to an address
5430 /// to a location on the stack, a local block, an address of a label, or a
5431 /// reference to local temporary. The recursion is used to traverse the
5432 /// AST of the return expression, with recursion backtracking when we
5433 /// encounter a subexpression that (1) clearly does not lead to one of the
5434 /// above problematic expressions (2) is something we cannot determine leads to
5435 /// a problematic expression based on such local checking.
5437 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
5438 /// the expression that they point to. Such variables are added to the
5439 /// 'refVars' vector so that we know what the reference variable "trail" was.
5441 /// EvalAddr processes expressions that are pointers that are used as
5442 /// references (and not L-values). EvalVal handles all other values.
5443 /// At the base case of the recursion is a check for the above problematic
5446 /// This implementation handles:
5448 /// * pointer-to-pointer casts
5449 /// * implicit conversions from array references to pointers
5450 /// * taking the address of fields
5451 /// * arbitrary interplay between "&" and "*" operators
5452 /// * pointer arithmetic from an address of a stack variable
5453 /// * taking the address of an array element where the array is on the stack
5454 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5456 if (E->isTypeDependent())
5459 // We should only be called for evaluating pointer expressions.
5460 assert((E->getType()->isAnyPointerType() ||
5461 E->getType()->isBlockPointerType() ||
5462 E->getType()->isObjCQualifiedIdType()) &&
5463 "EvalAddr only works on pointers");
5465 E = E->IgnoreParens();
5467 // Our "symbolic interpreter" is just a dispatch off the currently
5468 // viewed AST node. We then recursively traverse the AST by calling
5469 // EvalAddr and EvalVal appropriately.
5470 switch (E->getStmtClass()) {
5471 case Stmt::DeclRefExprClass: {
5472 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5474 // If we leave the immediate function, the lifetime isn't about to end.
5475 if (DR->refersToEnclosingVariableOrCapture())
5478 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5479 // If this is a reference variable, follow through to the expression that
5481 if (V->hasLocalStorage() &&
5482 V->getType()->isReferenceType() && V->hasInit()) {
5483 // Add the reference variable to the "trail".
5484 refVars.push_back(DR);
5485 return EvalAddr(V->getInit(), refVars, ParentDecl);
5491 case Stmt::UnaryOperatorClass: {
5492 // The only unary operator that make sense to handle here
5493 // is AddrOf. All others don't make sense as pointers.
5494 UnaryOperator *U = cast<UnaryOperator>(E);
5496 if (U->getOpcode() == UO_AddrOf)
5497 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
5502 case Stmt::BinaryOperatorClass: {
5503 // Handle pointer arithmetic. All other binary operators are not valid
5505 BinaryOperator *B = cast<BinaryOperator>(E);
5506 BinaryOperatorKind op = B->getOpcode();
5508 if (op != BO_Add && op != BO_Sub)
5511 Expr *Base = B->getLHS();
5513 // Determine which argument is the real pointer base. It could be
5514 // the RHS argument instead of the LHS.
5515 if (!Base->getType()->isPointerType()) Base = B->getRHS();
5517 assert (Base->getType()->isPointerType());
5518 return EvalAddr(Base, refVars, ParentDecl);
5521 // For conditional operators we need to see if either the LHS or RHS are
5522 // valid DeclRefExpr*s. If one of them is valid, we return it.
5523 case Stmt::ConditionalOperatorClass: {
5524 ConditionalOperator *C = cast<ConditionalOperator>(E);
5526 // Handle the GNU extension for missing LHS.
5527 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5528 if (Expr *LHSExpr = C->getLHS()) {
5529 // In C++, we can have a throw-expression, which has 'void' type.
5530 if (!LHSExpr->getType()->isVoidType())
5531 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
5535 // In C++, we can have a throw-expression, which has 'void' type.
5536 if (C->getRHS()->getType()->isVoidType())
5539 return EvalAddr(C->getRHS(), refVars, ParentDecl);
5542 case Stmt::BlockExprClass:
5543 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
5544 return E; // local block.
5547 case Stmt::AddrLabelExprClass:
5548 return E; // address of label.
5550 case Stmt::ExprWithCleanupsClass:
5551 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5554 // For casts, we need to handle conversions from arrays to
5555 // pointer values, and pointer-to-pointer conversions.
5556 case Stmt::ImplicitCastExprClass:
5557 case Stmt::CStyleCastExprClass:
5558 case Stmt::CXXFunctionalCastExprClass:
5559 case Stmt::ObjCBridgedCastExprClass:
5560 case Stmt::CXXStaticCastExprClass:
5561 case Stmt::CXXDynamicCastExprClass:
5562 case Stmt::CXXConstCastExprClass:
5563 case Stmt::CXXReinterpretCastExprClass: {
5564 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5565 switch (cast<CastExpr>(E)->getCastKind()) {
5566 case CK_LValueToRValue:
5568 case CK_BaseToDerived:
5569 case CK_DerivedToBase:
5570 case CK_UncheckedDerivedToBase:
5572 case CK_CPointerToObjCPointerCast:
5573 case CK_BlockPointerToObjCPointerCast:
5574 case CK_AnyPointerToBlockPointerCast:
5575 return EvalAddr(SubExpr, refVars, ParentDecl);
5577 case CK_ArrayToPointerDecay:
5578 return EvalVal(SubExpr, refVars, ParentDecl);
5581 if (SubExpr->getType()->isAnyPointerType() ||
5582 SubExpr->getType()->isBlockPointerType() ||
5583 SubExpr->getType()->isObjCQualifiedIdType())
5584 return EvalAddr(SubExpr, refVars, ParentDecl);
5593 case Stmt::MaterializeTemporaryExprClass:
5594 if (Expr *Result = EvalAddr(
5595 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5596 refVars, ParentDecl))
5601 // Everything else: we simply don't reason about them.
5608 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
5609 /// See the comments for EvalAddr for more details.
5610 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5613 // We should only be called for evaluating non-pointer expressions, or
5614 // expressions with a pointer type that are not used as references but instead
5615 // are l-values (e.g., DeclRefExpr with a pointer type).
5617 // Our "symbolic interpreter" is just a dispatch off the currently
5618 // viewed AST node. We then recursively traverse the AST by calling
5619 // EvalAddr and EvalVal appropriately.
5621 E = E->IgnoreParens();
5622 switch (E->getStmtClass()) {
5623 case Stmt::ImplicitCastExprClass: {
5624 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
5625 if (IE->getValueKind() == VK_LValue) {
5626 E = IE->getSubExpr();
5632 case Stmt::ExprWithCleanupsClass:
5633 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
5635 case Stmt::DeclRefExprClass: {
5636 // When we hit a DeclRefExpr we are looking at code that refers to a
5637 // variable's name. If it's not a reference variable we check if it has
5638 // local storage within the function, and if so, return the expression.
5639 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5641 // If we leave the immediate function, the lifetime isn't about to end.
5642 if (DR->refersToEnclosingVariableOrCapture())
5645 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5646 // Check if it refers to itself, e.g. "int& i = i;".
5647 if (V == ParentDecl)
5650 if (V->hasLocalStorage()) {
5651 if (!V->getType()->isReferenceType())
5654 // Reference variable, follow through to the expression that
5657 // Add the reference variable to the "trail".
5658 refVars.push_back(DR);
5659 return EvalVal(V->getInit(), refVars, V);
5667 case Stmt::UnaryOperatorClass: {
5668 // The only unary operator that make sense to handle here
5669 // is Deref. All others don't resolve to a "name." This includes
5670 // handling all sorts of rvalues passed to a unary operator.
5671 UnaryOperator *U = cast<UnaryOperator>(E);
5673 if (U->getOpcode() == UO_Deref)
5674 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
5679 case Stmt::ArraySubscriptExprClass: {
5680 // Array subscripts are potential references to data on the stack. We
5681 // retrieve the DeclRefExpr* for the array variable if it indeed
5682 // has local storage.
5683 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
5686 case Stmt::ConditionalOperatorClass: {
5687 // For conditional operators we need to see if either the LHS or RHS are
5688 // non-NULL Expr's. If one is non-NULL, we return it.
5689 ConditionalOperator *C = cast<ConditionalOperator>(E);
5691 // Handle the GNU extension for missing LHS.
5692 if (Expr *LHSExpr = C->getLHS()) {
5693 // In C++, we can have a throw-expression, which has 'void' type.
5694 if (!LHSExpr->getType()->isVoidType())
5695 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5699 // In C++, we can have a throw-expression, which has 'void' type.
5700 if (C->getRHS()->getType()->isVoidType())
5703 return EvalVal(C->getRHS(), refVars, ParentDecl);
5706 // Accesses to members are potential references to data on the stack.
5707 case Stmt::MemberExprClass: {
5708 MemberExpr *M = cast<MemberExpr>(E);
5710 // Check for indirect access. We only want direct field accesses.
5714 // Check whether the member type is itself a reference, in which case
5715 // we're not going to refer to the member, but to what the member refers to.
5716 if (M->getMemberDecl()->getType()->isReferenceType())
5719 return EvalVal(M->getBase(), refVars, ParentDecl);
5722 case Stmt::MaterializeTemporaryExprClass:
5723 if (Expr *Result = EvalVal(
5724 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5725 refVars, ParentDecl))
5731 // Check that we don't return or take the address of a reference to a
5732 // temporary. This is only useful in C++.
5733 if (!E->isTypeDependent() && E->isRValue())
5736 // Everything else: we simply don't reason about them.
5743 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5744 SourceLocation ReturnLoc,
5746 const AttrVec *Attrs,
5747 const FunctionDecl *FD) {
5748 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5750 // Check if the return value is null but should not be.
5751 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
5752 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
5753 CheckNonNullExpr(*this, RetValExp))
5754 Diag(ReturnLoc, diag::warn_null_ret)
5755 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
5757 // C++11 [basic.stc.dynamic.allocation]p4:
5758 // If an allocation function declared with a non-throwing
5759 // exception-specification fails to allocate storage, it shall return
5760 // a null pointer. Any other allocation function that fails to allocate
5761 // storage shall indicate failure only by throwing an exception [...]
5763 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5764 if (Op == OO_New || Op == OO_Array_New) {
5765 const FunctionProtoType *Proto
5766 = FD->getType()->castAs<FunctionProtoType>();
5767 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5768 CheckNonNullExpr(*this, RetValExp))
5769 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5770 << FD << getLangOpts().CPlusPlus11;
5775 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5777 /// Check for comparisons of floating point operands using != and ==.
5778 /// Issue a warning if these are no self-comparisons, as they are not likely
5779 /// to do what the programmer intended.
5780 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
5781 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5782 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
5784 // Special case: check for x == x (which is OK).
5785 // Do not emit warnings for such cases.
5786 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5787 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5788 if (DRL->getDecl() == DRR->getDecl())
5792 // Special case: check for comparisons against literals that can be exactly
5793 // represented by APFloat. In such cases, do not emit a warning. This
5794 // is a heuristic: often comparison against such literals are used to
5795 // detect if a value in a variable has not changed. This clearly can
5796 // lead to false negatives.
5797 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5801 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5805 // Check for comparisons with builtin types.
5806 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
5807 if (CL->getBuiltinCallee())
5810 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
5811 if (CR->getBuiltinCallee())
5814 // Emit the diagnostic.
5815 Diag(Loc, diag::warn_floatingpoint_eq)
5816 << LHS->getSourceRange() << RHS->getSourceRange();
5819 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5820 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
5824 /// Structure recording the 'active' range of an integer-valued
5827 /// The number of bits active in the int.
5830 /// True if the int is known not to have negative values.
5833 IntRange(unsigned Width, bool NonNegative)
5834 : Width(Width), NonNegative(NonNegative)
5837 /// Returns the range of the bool type.
5838 static IntRange forBoolType() {
5839 return IntRange(1, true);
5842 /// Returns the range of an opaque value of the given integral type.
5843 static IntRange forValueOfType(ASTContext &C, QualType T) {
5844 return forValueOfCanonicalType(C,
5845 T->getCanonicalTypeInternal().getTypePtr());
5848 /// Returns the range of an opaque value of a canonical integral type.
5849 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
5850 assert(T->isCanonicalUnqualified());
5852 if (const VectorType *VT = dyn_cast<VectorType>(T))
5853 T = VT->getElementType().getTypePtr();
5854 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5855 T = CT->getElementType().getTypePtr();
5856 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5857 T = AT->getValueType().getTypePtr();
5859 // For enum types, use the known bit width of the enumerators.
5860 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
5861 EnumDecl *Enum = ET->getDecl();
5862 if (!Enum->isCompleteDefinition())
5863 return IntRange(C.getIntWidth(QualType(T, 0)), false);
5865 unsigned NumPositive = Enum->getNumPositiveBits();
5866 unsigned NumNegative = Enum->getNumNegativeBits();
5868 if (NumNegative == 0)
5869 return IntRange(NumPositive, true/*NonNegative*/);
5871 return IntRange(std::max(NumPositive + 1, NumNegative),
5872 false/*NonNegative*/);
5875 const BuiltinType *BT = cast<BuiltinType>(T);
5876 assert(BT->isInteger());
5878 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5881 /// Returns the "target" range of a canonical integral type, i.e.
5882 /// the range of values expressible in the type.
5884 /// This matches forValueOfCanonicalType except that enums have the
5885 /// full range of their type, not the range of their enumerators.
5886 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5887 assert(T->isCanonicalUnqualified());
5889 if (const VectorType *VT = dyn_cast<VectorType>(T))
5890 T = VT->getElementType().getTypePtr();
5891 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5892 T = CT->getElementType().getTypePtr();
5893 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5894 T = AT->getValueType().getTypePtr();
5895 if (const EnumType *ET = dyn_cast<EnumType>(T))
5896 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
5898 const BuiltinType *BT = cast<BuiltinType>(T);
5899 assert(BT->isInteger());
5901 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5904 /// Returns the supremum of two ranges: i.e. their conservative merge.
5905 static IntRange join(IntRange L, IntRange R) {
5906 return IntRange(std::max(L.Width, R.Width),
5907 L.NonNegative && R.NonNegative);
5910 /// Returns the infinum of two ranges: i.e. their aggressive merge.
5911 static IntRange meet(IntRange L, IntRange R) {
5912 return IntRange(std::min(L.Width, R.Width),
5913 L.NonNegative || R.NonNegative);
5917 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5918 unsigned MaxWidth) {
5919 if (value.isSigned() && value.isNegative())
5920 return IntRange(value.getMinSignedBits(), false);
5922 if (value.getBitWidth() > MaxWidth)
5923 value = value.trunc(MaxWidth);
5925 // isNonNegative() just checks the sign bit without considering
5927 return IntRange(value.getActiveBits(), true);
5930 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5931 unsigned MaxWidth) {
5933 return GetValueRange(C, result.getInt(), MaxWidth);
5935 if (result.isVector()) {
5936 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5937 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5938 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5939 R = IntRange::join(R, El);
5944 if (result.isComplexInt()) {
5945 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5946 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5947 return IntRange::join(R, I);
5950 // This can happen with lossless casts to intptr_t of "based" lvalues.
5951 // Assume it might use arbitrary bits.
5952 // FIXME: The only reason we need to pass the type in here is to get
5953 // the sign right on this one case. It would be nice if APValue
5955 assert(result.isLValue() || result.isAddrLabelDiff());
5956 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
5959 static QualType GetExprType(Expr *E) {
5960 QualType Ty = E->getType();
5961 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5962 Ty = AtomicRHS->getValueType();
5966 /// Pseudo-evaluate the given integer expression, estimating the
5967 /// range of values it might take.
5969 /// \param MaxWidth - the width to which the value will be truncated
5970 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
5971 E = E->IgnoreParens();
5973 // Try a full evaluation first.
5974 Expr::EvalResult result;
5975 if (E->EvaluateAsRValue(result, C))
5976 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
5978 // I think we only want to look through implicit casts here; if the
5979 // user has an explicit widening cast, we should treat the value as
5980 // being of the new, wider type.
5981 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
5982 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
5983 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5985 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
5987 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
5989 // Assume that non-integer casts can span the full range of the type.
5991 return OutputTypeRange;
5994 = GetExprRange(C, CE->getSubExpr(),
5995 std::min(MaxWidth, OutputTypeRange.Width));
5997 // Bail out if the subexpr's range is as wide as the cast type.
5998 if (SubRange.Width >= OutputTypeRange.Width)
5999 return OutputTypeRange;
6001 // Otherwise, we take the smaller width, and we're non-negative if
6002 // either the output type or the subexpr is.
6003 return IntRange(SubRange.Width,
6004 SubRange.NonNegative || OutputTypeRange.NonNegative);
6007 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6008 // If we can fold the condition, just take that operand.
6010 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6011 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6012 : CO->getFalseExpr(),
6015 // Otherwise, conservatively merge.
6016 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6017 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6018 return IntRange::join(L, R);
6021 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6022 switch (BO->getOpcode()) {
6024 // Boolean-valued operations are single-bit and positive.
6033 return IntRange::forBoolType();
6035 // The type of the assignments is the type of the LHS, so the RHS
6036 // is not necessarily the same type.
6045 return IntRange::forValueOfType(C, GetExprType(E));
6047 // Simple assignments just pass through the RHS, which will have
6048 // been coerced to the LHS type.
6051 return GetExprRange(C, BO->getRHS(), MaxWidth);
6053 // Operations with opaque sources are black-listed.
6056 return IntRange::forValueOfType(C, GetExprType(E));
6058 // Bitwise-and uses the *infinum* of the two source ranges.
6061 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6062 GetExprRange(C, BO->getRHS(), MaxWidth));
6064 // Left shift gets black-listed based on a judgement call.
6066 // ...except that we want to treat '1 << (blah)' as logically
6067 // positive. It's an important idiom.
6068 if (IntegerLiteral *I
6069 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6070 if (I->getValue() == 1) {
6071 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
6072 return IntRange(R.Width, /*NonNegative*/ true);
6078 return IntRange::forValueOfType(C, GetExprType(E));
6080 // Right shift by a constant can narrow its left argument.
6082 case BO_ShrAssign: {
6083 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6085 // If the shift amount is a positive constant, drop the width by
6088 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6089 shift.isNonNegative()) {
6090 unsigned zext = shift.getZExtValue();
6091 if (zext >= L.Width)
6092 L.Width = (L.NonNegative ? 0 : 1);
6100 // Comma acts as its right operand.
6102 return GetExprRange(C, BO->getRHS(), MaxWidth);
6104 // Black-list pointer subtractions.
6106 if (BO->getLHS()->getType()->isPointerType())
6107 return IntRange::forValueOfType(C, GetExprType(E));
6110 // The width of a division result is mostly determined by the size
6113 // Don't 'pre-truncate' the operands.
6114 unsigned opWidth = C.getIntWidth(GetExprType(E));
6115 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6117 // If the divisor is constant, use that.
6118 llvm::APSInt divisor;
6119 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6120 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6121 if (log2 >= L.Width)
6122 L.Width = (L.NonNegative ? 0 : 1);
6124 L.Width = std::min(L.Width - log2, MaxWidth);
6128 // Otherwise, just use the LHS's width.
6129 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6130 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6133 // The result of a remainder can't be larger than the result of
6136 // Don't 'pre-truncate' the operands.
6137 unsigned opWidth = C.getIntWidth(GetExprType(E));
6138 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6139 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6141 IntRange meet = IntRange::meet(L, R);
6142 meet.Width = std::min(meet.Width, MaxWidth);
6146 // The default behavior is okay for these.
6154 // The default case is to treat the operation as if it were closed
6155 // on the narrowest type that encompasses both operands.
6156 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6157 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6158 return IntRange::join(L, R);
6161 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6162 switch (UO->getOpcode()) {
6163 // Boolean-valued operations are white-listed.
6165 return IntRange::forBoolType();
6167 // Operations with opaque sources are black-listed.
6169 case UO_AddrOf: // should be impossible
6170 return IntRange::forValueOfType(C, GetExprType(E));
6173 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6177 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6178 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6180 if (FieldDecl *BitField = E->getSourceBitField())
6181 return IntRange(BitField->getBitWidthValue(C),
6182 BitField->getType()->isUnsignedIntegerOrEnumerationType());
6184 return IntRange::forValueOfType(C, GetExprType(E));
6187 static IntRange GetExprRange(ASTContext &C, Expr *E) {
6188 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
6191 /// Checks whether the given value, which currently has the given
6192 /// source semantics, has the same value when coerced through the
6193 /// target semantics.
6194 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6195 const llvm::fltSemantics &Src,
6196 const llvm::fltSemantics &Tgt) {
6197 llvm::APFloat truncated = value;
6200 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6201 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6203 return truncated.bitwiseIsEqual(value);
6206 /// Checks whether the given value, which currently has the given
6207 /// source semantics, has the same value when coerced through the
6208 /// target semantics.
6210 /// The value might be a vector of floats (or a complex number).
6211 static bool IsSameFloatAfterCast(const APValue &value,
6212 const llvm::fltSemantics &Src,
6213 const llvm::fltSemantics &Tgt) {
6214 if (value.isFloat())
6215 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6217 if (value.isVector()) {
6218 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6219 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6224 assert(value.isComplexFloat());
6225 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6226 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6229 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
6231 static bool IsZero(Sema &S, Expr *E) {
6232 // Suppress cases where we are comparing against an enum constant.
6233 if (const DeclRefExpr *DR =
6234 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6235 if (isa<EnumConstantDecl>(DR->getDecl()))
6238 // Suppress cases where the '0' value is expanded from a macro.
6239 if (E->getLocStart().isMacroID())
6243 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6246 static bool HasEnumType(Expr *E) {
6247 // Strip off implicit integral promotions.
6248 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6249 if (ICE->getCastKind() != CK_IntegralCast &&
6250 ICE->getCastKind() != CK_NoOp)
6252 E = ICE->getSubExpr();
6255 return E->getType()->isEnumeralType();
6258 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
6259 // Disable warning in template instantiations.
6260 if (!S.ActiveTemplateInstantiations.empty())
6263 BinaryOperatorKind op = E->getOpcode();
6264 if (E->isValueDependent())
6267 if (op == BO_LT && IsZero(S, E->getRHS())) {
6268 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
6269 << "< 0" << "false" << HasEnumType(E->getLHS())
6270 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6271 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
6272 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
6273 << ">= 0" << "true" << HasEnumType(E->getLHS())
6274 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6275 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
6276 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
6277 << "0 >" << "false" << HasEnumType(E->getRHS())
6278 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6279 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
6280 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
6281 << "0 <=" << "true" << HasEnumType(E->getRHS())
6282 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6286 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6287 Expr *Constant, Expr *Other,
6290 // Disable warning in template instantiations.
6291 if (!S.ActiveTemplateInstantiations.empty())
6294 // TODO: Investigate using GetExprRange() to get tighter bounds
6295 // on the bit ranges.
6296 QualType OtherT = Other->getType();
6297 if (const auto *AT = OtherT->getAs<AtomicType>())
6298 OtherT = AT->getValueType();
6299 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6300 unsigned OtherWidth = OtherRange.Width;
6302 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6304 // 0 values are handled later by CheckTrivialUnsignedComparison().
6305 if ((Value == 0) && (!OtherIsBooleanType))
6308 BinaryOperatorKind op = E->getOpcode();
6311 // Used for diagnostic printout.
6313 LiteralConstant = 0,
6316 } LiteralOrBoolConstant = LiteralConstant;
6318 if (!OtherIsBooleanType) {
6319 QualType ConstantT = Constant->getType();
6320 QualType CommonT = E->getLHS()->getType();
6322 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6324 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6325 "comparison with non-integer type");
6327 bool ConstantSigned = ConstantT->isSignedIntegerType();
6328 bool CommonSigned = CommonT->isSignedIntegerType();
6330 bool EqualityOnly = false;
6333 // The common type is signed, therefore no signed to unsigned conversion.
6334 if (!OtherRange.NonNegative) {
6335 // Check that the constant is representable in type OtherT.
6336 if (ConstantSigned) {
6337 if (OtherWidth >= Value.getMinSignedBits())
6339 } else { // !ConstantSigned
6340 if (OtherWidth >= Value.getActiveBits() + 1)
6343 } else { // !OtherSigned
6344 // Check that the constant is representable in type OtherT.
6345 // Negative values are out of range.
6346 if (ConstantSigned) {
6347 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6349 } else { // !ConstantSigned
6350 if (OtherWidth >= Value.getActiveBits())
6354 } else { // !CommonSigned
6355 if (OtherRange.NonNegative) {
6356 if (OtherWidth >= Value.getActiveBits())
6358 } else { // OtherSigned
6359 assert(!ConstantSigned &&
6360 "Two signed types converted to unsigned types.");
6361 // Check to see if the constant is representable in OtherT.
6362 if (OtherWidth > Value.getActiveBits())
6364 // Check to see if the constant is equivalent to a negative value
6366 if (S.Context.getIntWidth(ConstantT) ==
6367 S.Context.getIntWidth(CommonT) &&
6368 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6370 // The constant value rests between values that OtherT can represent
6371 // after conversion. Relational comparison still works, but equality
6372 // comparisons will be tautological.
6373 EqualityOnly = true;
6377 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6379 if (op == BO_EQ || op == BO_NE) {
6380 IsTrue = op == BO_NE;
6381 } else if (EqualityOnly) {
6383 } else if (RhsConstant) {
6384 if (op == BO_GT || op == BO_GE)
6385 IsTrue = !PositiveConstant;
6386 else // op == BO_LT || op == BO_LE
6387 IsTrue = PositiveConstant;
6389 if (op == BO_LT || op == BO_LE)
6390 IsTrue = !PositiveConstant;
6391 else // op == BO_GT || op == BO_GE
6392 IsTrue = PositiveConstant;
6395 // Other isKnownToHaveBooleanValue
6396 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6397 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6398 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6400 static const struct LinkedConditions {
6401 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6402 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6403 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6404 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6405 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6406 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6409 // Constant on LHS. | Constant on RHS. |
6410 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6411 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6412 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6413 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6414 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6415 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6416 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6419 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6421 enum ConstantValue ConstVal = Zero;
6422 if (Value.isUnsigned() || Value.isNonNegative()) {
6424 LiteralOrBoolConstant =
6425 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6427 } else if (Value == 1) {
6428 LiteralOrBoolConstant =
6429 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6432 LiteralOrBoolConstant = LiteralConstant;
6439 CompareBoolWithConstantResult CmpRes;
6443 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6446 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6449 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6452 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6455 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6458 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6465 if (CmpRes == AFals) {
6467 } else if (CmpRes == ATrue) {
6474 // If this is a comparison to an enum constant, include that
6475 // constant in the diagnostic.
6476 const EnumConstantDecl *ED = nullptr;
6477 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6478 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6480 SmallString<64> PrettySourceValue;
6481 llvm::raw_svector_ostream OS(PrettySourceValue);
6483 OS << '\'' << *ED << "' (" << Value << ")";
6487 S.DiagRuntimeBehavior(
6488 E->getOperatorLoc(), E,
6489 S.PDiag(diag::warn_out_of_range_compare)
6490 << OS.str() << LiteralOrBoolConstant
6491 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6492 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
6495 /// Analyze the operands of the given comparison. Implements the
6496 /// fallback case from AnalyzeComparison.
6497 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
6498 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6499 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6502 /// \brief Implements -Wsign-compare.
6504 /// \param E the binary operator to check for warnings
6505 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
6506 // The type the comparison is being performed in.
6507 QualType T = E->getLHS()->getType();
6509 // Only analyze comparison operators where both sides have been converted to
6511 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6512 return AnalyzeImpConvsInComparison(S, E);
6514 // Don't analyze value-dependent comparisons directly.
6515 if (E->isValueDependent())
6516 return AnalyzeImpConvsInComparison(S, E);
6518 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6519 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
6521 bool IsComparisonConstant = false;
6523 // Check whether an integer constant comparison results in a value
6524 // of 'true' or 'false'.
6525 if (T->isIntegralType(S.Context)) {
6526 llvm::APSInt RHSValue;
6527 bool IsRHSIntegralLiteral =
6528 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6529 llvm::APSInt LHSValue;
6530 bool IsLHSIntegralLiteral =
6531 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6532 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6533 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6534 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6535 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6537 IsComparisonConstant =
6538 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
6539 } else if (!T->hasUnsignedIntegerRepresentation())
6540 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
6542 // We don't do anything special if this isn't an unsigned integral
6543 // comparison: we're only interested in integral comparisons, and
6544 // signed comparisons only happen in cases we don't care to warn about.
6546 // We also don't care about value-dependent expressions or expressions
6547 // whose result is a constant.
6548 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
6549 return AnalyzeImpConvsInComparison(S, E);
6551 // Check to see if one of the (unmodified) operands is of different
6553 Expr *signedOperand, *unsignedOperand;
6554 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6555 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
6556 "unsigned comparison between two signed integer expressions?");
6557 signedOperand = LHS;
6558 unsignedOperand = RHS;
6559 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6560 signedOperand = RHS;
6561 unsignedOperand = LHS;
6563 CheckTrivialUnsignedComparison(S, E);
6564 return AnalyzeImpConvsInComparison(S, E);
6567 // Otherwise, calculate the effective range of the signed operand.
6568 IntRange signedRange = GetExprRange(S.Context, signedOperand);
6570 // Go ahead and analyze implicit conversions in the operands. Note
6571 // that we skip the implicit conversions on both sides.
6572 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6573 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
6575 // If the signed range is non-negative, -Wsign-compare won't fire,
6576 // but we should still check for comparisons which are always true
6578 if (signedRange.NonNegative)
6579 return CheckTrivialUnsignedComparison(S, E);
6581 // For (in)equality comparisons, if the unsigned operand is a
6582 // constant which cannot collide with a overflowed signed operand,
6583 // then reinterpreting the signed operand as unsigned will not
6584 // change the result of the comparison.
6585 if (E->isEqualityOp()) {
6586 unsigned comparisonWidth = S.Context.getIntWidth(T);
6587 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
6589 // We should never be unable to prove that the unsigned operand is
6591 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6593 if (unsignedRange.Width < comparisonWidth)
6597 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6598 S.PDiag(diag::warn_mixed_sign_comparison)
6599 << LHS->getType() << RHS->getType()
6600 << LHS->getSourceRange() << RHS->getSourceRange());
6603 /// Analyzes an attempt to assign the given value to a bitfield.
6605 /// Returns true if there was something fishy about the attempt.
6606 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6607 SourceLocation InitLoc) {
6608 assert(Bitfield->isBitField());
6609 if (Bitfield->isInvalidDecl())
6612 // White-list bool bitfields.
6613 if (Bitfield->getType()->isBooleanType())
6616 // Ignore value- or type-dependent expressions.
6617 if (Bitfield->getBitWidth()->isValueDependent() ||
6618 Bitfield->getBitWidth()->isTypeDependent() ||
6619 Init->isValueDependent() ||
6620 Init->isTypeDependent())
6623 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6626 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
6629 unsigned OriginalWidth = Value.getBitWidth();
6630 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
6632 if (OriginalWidth <= FieldWidth)
6635 // Compute the value which the bitfield will contain.
6636 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
6637 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
6639 // Check whether the stored value is equal to the original value.
6640 TruncatedValue = TruncatedValue.extend(OriginalWidth);
6641 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
6644 // Special-case bitfields of width 1: booleans are naturally 0/1, and
6645 // therefore don't strictly fit into a signed bitfield of width 1.
6646 if (FieldWidth == 1 && Value == 1)
6649 std::string PrettyValue = Value.toString(10);
6650 std::string PrettyTrunc = TruncatedValue.toString(10);
6652 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6653 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6654 << Init->getSourceRange();
6659 /// Analyze the given simple or compound assignment for warning-worthy
6661 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
6662 // Just recurse on the LHS.
6663 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6665 // We want to recurse on the RHS as normal unless we're assigning to
6667 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
6668 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
6669 E->getOperatorLoc())) {
6670 // Recurse, ignoring any implicit conversions on the RHS.
6671 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6672 E->getOperatorLoc());
6676 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6679 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
6680 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
6681 SourceLocation CContext, unsigned diag,
6682 bool pruneControlFlow = false) {
6683 if (pruneControlFlow) {
6684 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6686 << SourceType << T << E->getSourceRange()
6687 << SourceRange(CContext));
6690 S.Diag(E->getExprLoc(), diag)
6691 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6694 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
6695 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
6696 SourceLocation CContext, unsigned diag,
6697 bool pruneControlFlow = false) {
6698 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
6701 /// Diagnose an implicit cast from a literal expression. Does not warn when the
6702 /// cast wouldn't lose information.
6703 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6704 SourceLocation CContext) {
6705 // Try to convert the literal exactly to an integer. If we can, don't warn.
6706 bool isExact = false;
6707 const llvm::APFloat &Value = FL->getValue();
6708 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6709 T->hasUnsignedIntegerRepresentation());
6710 if (Value.convertToInteger(IntegerValue,
6711 llvm::APFloat::rmTowardZero, &isExact)
6712 == llvm::APFloat::opOK && isExact)
6715 // FIXME: Force the precision of the source value down so we don't print
6716 // digits which are usually useless (we don't really care here if we
6717 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6718 // would automatically print the shortest representation, but it's a bit
6719 // tricky to implement.
6720 SmallString<16> PrettySourceValue;
6721 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6722 precision = (precision * 59 + 195) / 196;
6723 Value.toString(PrettySourceValue, precision);
6725 SmallString<16> PrettyTargetValue;
6726 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6727 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6729 IntegerValue.toString(PrettyTargetValue);
6731 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
6732 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6733 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
6736 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6737 if (!Range.Width) return "0";
6739 llvm::APSInt ValueInRange = Value;
6740 ValueInRange.setIsSigned(!Range.NonNegative);
6741 ValueInRange = ValueInRange.trunc(Range.Width);
6742 return ValueInRange.toString(10);
6745 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6746 if (!isa<ImplicitCastExpr>(Ex))
6749 Expr *InnerE = Ex->IgnoreParenImpCasts();
6750 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6751 const Type *Source =
6752 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6753 if (Target->isDependentType())
6756 const BuiltinType *FloatCandidateBT =
6757 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6758 const Type *BoolCandidateType = ToBool ? Target : Source;
6760 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6761 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6764 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6765 SourceLocation CC) {
6766 unsigned NumArgs = TheCall->getNumArgs();
6767 for (unsigned i = 0; i < NumArgs; ++i) {
6768 Expr *CurrA = TheCall->getArg(i);
6769 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6772 bool IsSwapped = ((i > 0) &&
6773 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6774 IsSwapped |= ((i < (NumArgs - 1)) &&
6775 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6777 // Warn on this floating-point to bool conversion.
6778 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6779 CurrA->getType(), CC,
6780 diag::warn_impcast_floating_point_to_bool);
6785 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6786 SourceLocation CC) {
6787 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6791 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6792 const Expr::NullPointerConstantKind NullKind =
6793 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6794 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6797 // Return if target type is a safe conversion.
6798 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6799 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6802 SourceLocation Loc = E->getSourceRange().getBegin();
6804 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6805 if (NullKind == Expr::NPCK_GNUNull) {
6806 if (Loc.isMacroID())
6807 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6810 // Only warn if the null and context location are in the same macro expansion.
6811 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6814 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6815 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6816 << FixItHint::CreateReplacement(Loc,
6817 S.getFixItZeroLiteralForType(T, Loc));
6820 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
6821 SourceLocation CC, bool *ICContext = nullptr) {
6822 if (E->isTypeDependent() || E->isValueDependent()) return;
6824 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6825 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6826 if (Source == Target) return;
6827 if (Target->isDependentType()) return;
6829 // If the conversion context location is invalid don't complain. We also
6830 // don't want to emit a warning if the issue occurs from the expansion of
6831 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6832 // delay this check as long as possible. Once we detect we are in that
6833 // scenario, we just return.
6837 // Diagnose implicit casts to bool.
6838 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6839 if (isa<StringLiteral>(E))
6840 // Warn on string literal to bool. Checks for string literals in logical
6841 // and expressions, for instance, assert(0 && "error here"), are
6842 // prevented by a check in AnalyzeImplicitConversions().
6843 return DiagnoseImpCast(S, E, T, CC,
6844 diag::warn_impcast_string_literal_to_bool);
6845 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6846 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6847 // This covers the literal expressions that evaluate to Objective-C
6849 return DiagnoseImpCast(S, E, T, CC,
6850 diag::warn_impcast_objective_c_literal_to_bool);
6852 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6853 // Warn on pointer to bool conversion that is always true.
6854 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6859 // Strip vector types.
6860 if (isa<VectorType>(Source)) {
6861 if (!isa<VectorType>(Target)) {
6862 if (S.SourceMgr.isInSystemMacro(CC))
6864 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
6867 // If the vector cast is cast between two vectors of the same size, it is
6868 // a bitcast, not a conversion.
6869 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6872 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6873 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6875 if (auto VecTy = dyn_cast<VectorType>(Target))
6876 Target = VecTy->getElementType().getTypePtr();
6878 // Strip complex types.
6879 if (isa<ComplexType>(Source)) {
6880 if (!isa<ComplexType>(Target)) {
6881 if (S.SourceMgr.isInSystemMacro(CC))
6884 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
6887 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6888 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6891 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6892 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6894 // If the source is floating point...
6895 if (SourceBT && SourceBT->isFloatingPoint()) {
6896 // ...and the target is floating point...
6897 if (TargetBT && TargetBT->isFloatingPoint()) {
6898 // ...then warn if we're dropping FP rank.
6900 // Builtin FP kinds are ordered by increasing FP rank.
6901 if (SourceBT->getKind() > TargetBT->getKind()) {
6902 // Don't warn about float constants that are precisely
6903 // representable in the target type.
6904 Expr::EvalResult result;
6905 if (E->EvaluateAsRValue(result, S.Context)) {
6906 // Value might be a float, a float vector, or a float complex.
6907 if (IsSameFloatAfterCast(result.Val,
6908 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6909 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
6913 if (S.SourceMgr.isInSystemMacro(CC))
6916 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
6921 // If the target is integral, always warn.
6922 if (TargetBT && TargetBT->isInteger()) {
6923 if (S.SourceMgr.isInSystemMacro(CC))
6926 Expr *InnerE = E->IgnoreParenImpCasts();
6927 // We also want to warn on, e.g., "int i = -1.234"
6928 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6929 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6930 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6932 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6933 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
6935 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6939 // If the target is bool, warn if expr is a function or method call.
6940 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6942 // Check last argument of function call to see if it is an
6943 // implicit cast from a type matching the type the result
6944 // is being cast to.
6945 CallExpr *CEx = cast<CallExpr>(E);
6946 unsigned NumArgs = CEx->getNumArgs();
6948 Expr *LastA = CEx->getArg(NumArgs - 1);
6949 Expr *InnerE = LastA->IgnoreParenImpCasts();
6950 const Type *InnerType =
6951 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6952 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6953 // Warn on this floating-point to bool conversion
6954 DiagnoseImpCast(S, E, T, CC,
6955 diag::warn_impcast_floating_point_to_bool);
6962 DiagnoseNullConversion(S, E, T, CC);
6964 if (!Source->isIntegerType() || !Target->isIntegerType())
6967 // TODO: remove this early return once the false positives for constant->bool
6968 // in templates, macros, etc, are reduced or removed.
6969 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6972 IntRange SourceRange = GetExprRange(S.Context, E);
6973 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
6975 if (SourceRange.Width > TargetRange.Width) {
6976 // If the source is a constant, use a default-on diagnostic.
6977 // TODO: this should happen for bitfield stores, too.
6978 llvm::APSInt Value(32);
6979 if (E->isIntegerConstantExpr(Value, S.Context)) {
6980 if (S.SourceMgr.isInSystemMacro(CC))
6983 std::string PrettySourceValue = Value.toString(10);
6984 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
6986 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6987 S.PDiag(diag::warn_impcast_integer_precision_constant)
6988 << PrettySourceValue << PrettyTargetValue
6989 << E->getType() << T << E->getSourceRange()
6990 << clang::SourceRange(CC));
6994 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6995 if (S.SourceMgr.isInSystemMacro(CC))
6998 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
6999 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7000 /* pruneControlFlow */ true);
7001 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
7004 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7005 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7006 SourceRange.Width == TargetRange.Width)) {
7008 if (S.SourceMgr.isInSystemMacro(CC))
7011 unsigned DiagID = diag::warn_impcast_integer_sign;
7013 // Traditionally, gcc has warned about this under -Wsign-compare.
7014 // We also want to warn about it in -Wconversion.
7015 // So if -Wconversion is off, use a completely identical diagnostic
7016 // in the sign-compare group.
7017 // The conditional-checking code will
7019 DiagID = diag::warn_impcast_integer_sign_conditional;
7023 return DiagnoseImpCast(S, E, T, CC, DiagID);
7026 // Diagnose conversions between different enumeration types.
7027 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7028 // type, to give us better diagnostics.
7029 QualType SourceType = E->getType();
7030 if (!S.getLangOpts().CPlusPlus) {
7031 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7032 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7033 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7034 SourceType = S.Context.getTypeDeclType(Enum);
7035 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7039 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7040 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
7041 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7042 TargetEnum->getDecl()->hasNameForLinkage() &&
7043 SourceEnum != TargetEnum) {
7044 if (S.SourceMgr.isInSystemMacro(CC))
7047 return DiagnoseImpCast(S, E, SourceType, T, CC,
7048 diag::warn_impcast_different_enum_types);
7054 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7055 SourceLocation CC, QualType T);
7057 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
7058 SourceLocation CC, bool &ICContext) {
7059 E = E->IgnoreParenImpCasts();
7061 if (isa<ConditionalOperator>(E))
7062 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
7064 AnalyzeImplicitConversions(S, E, CC);
7065 if (E->getType() != T)
7066 return CheckImplicitConversion(S, E, T, CC, &ICContext);
7070 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7071 SourceLocation CC, QualType T) {
7072 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
7074 bool Suspicious = false;
7075 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7076 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
7078 // If -Wconversion would have warned about either of the candidates
7079 // for a signedness conversion to the context type...
7080 if (!Suspicious) return;
7082 // ...but it's currently ignored...
7083 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
7086 // ...then check whether it would have warned about either of the
7087 // candidates for a signedness conversion to the condition type.
7088 if (E->getType() == T) return;
7091 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7092 E->getType(), CC, &Suspicious);
7094 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
7095 E->getType(), CC, &Suspicious);
7098 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7099 /// Input argument E is a logical expression.
7100 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7101 if (S.getLangOpts().Bool)
7103 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7106 /// AnalyzeImplicitConversions - Find and report any interesting
7107 /// implicit conversions in the given expression. There are a couple
7108 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
7109 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
7110 QualType T = OrigE->getType();
7111 Expr *E = OrigE->IgnoreParenImpCasts();
7113 if (E->isTypeDependent() || E->isValueDependent())
7116 // For conditional operators, we analyze the arguments as if they
7117 // were being fed directly into the output.
7118 if (isa<ConditionalOperator>(E)) {
7119 ConditionalOperator *CO = cast<ConditionalOperator>(E);
7120 CheckConditionalOperator(S, CO, CC, T);
7124 // Check implicit argument conversions for function calls.
7125 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7126 CheckImplicitArgumentConversions(S, Call, CC);
7128 // Go ahead and check any implicit conversions we might have skipped.
7129 // The non-canonical typecheck is just an optimization;
7130 // CheckImplicitConversion will filter out dead implicit conversions.
7131 if (E->getType() != T)
7132 CheckImplicitConversion(S, E, T, CC);
7134 // Now continue drilling into this expression.
7136 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
7137 if (POE->getResultExpr())
7138 E = POE->getResultExpr();
7141 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
7142 if (OVE->getSourceExpr())
7143 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
7147 // Skip past explicit casts.
7148 if (isa<ExplicitCastExpr>(E)) {
7149 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
7150 return AnalyzeImplicitConversions(S, E, CC);
7153 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7154 // Do a somewhat different check with comparison operators.
7155 if (BO->isComparisonOp())
7156 return AnalyzeComparison(S, BO);
7158 // And with simple assignments.
7159 if (BO->getOpcode() == BO_Assign)
7160 return AnalyzeAssignment(S, BO);
7163 // These break the otherwise-useful invariant below. Fortunately,
7164 // we don't really need to recurse into them, because any internal
7165 // expressions should have been analyzed already when they were
7166 // built into statements.
7167 if (isa<StmtExpr>(E)) return;
7169 // Don't descend into unevaluated contexts.
7170 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
7172 // Now just recurse over the expression's children.
7173 CC = E->getExprLoc();
7174 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
7175 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
7176 for (Stmt::child_range I = E->children(); I; ++I) {
7177 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
7181 if (IsLogicalAndOperator &&
7182 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
7183 // Ignore checking string literals that are in logical and operators.
7184 // This is a common pattern for asserts.
7186 AnalyzeImplicitConversions(S, ChildExpr, CC);
7189 if (BO && BO->isLogicalOp()) {
7190 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7191 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
7192 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
7194 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7195 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
7196 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
7199 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7200 if (U->getOpcode() == UO_LNot)
7201 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
7204 } // end anonymous namespace
7212 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7213 // Returns true when emitting a warning about taking the address of a reference.
7214 static bool CheckForReference(Sema &SemaRef, const Expr *E,
7215 PartialDiagnostic PD) {
7216 E = E->IgnoreParenImpCasts();
7218 const FunctionDecl *FD = nullptr;
7220 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7221 if (!DRE->getDecl()->getType()->isReferenceType())
7223 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7224 if (!M->getMemberDecl()->getType()->isReferenceType())
7226 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
7227 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
7229 FD = Call->getDirectCallee();
7234 SemaRef.Diag(E->getExprLoc(), PD);
7236 // If possible, point to location of function.
7238 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7244 // Returns true if the SourceLocation is expanded from any macro body.
7245 // Returns false if the SourceLocation is invalid, is from not in a macro
7246 // expansion, or is from expanded from a top-level macro argument.
7247 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7248 if (Loc.isInvalid())
7251 while (Loc.isMacroID()) {
7252 if (SM.isMacroBodyExpansion(Loc))
7254 Loc = SM.getImmediateMacroCallerLoc(Loc);
7260 /// \brief Diagnose pointers that are always non-null.
7261 /// \param E the expression containing the pointer
7262 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7263 /// compared to a null pointer
7264 /// \param IsEqual True when the comparison is equal to a null pointer
7265 /// \param Range Extra SourceRange to highlight in the diagnostic
7266 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7267 Expr::NullPointerConstantKind NullKind,
7268 bool IsEqual, SourceRange Range) {
7272 // Don't warn inside macros.
7273 if (E->getExprLoc().isMacroID()) {
7274 const SourceManager &SM = getSourceManager();
7275 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7276 IsInAnyMacroBody(SM, Range.getBegin()))
7279 E = E->IgnoreImpCasts();
7281 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7283 if (isa<CXXThisExpr>(E)) {
7284 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7285 : diag::warn_this_bool_conversion;
7286 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7290 bool IsAddressOf = false;
7292 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7293 if (UO->getOpcode() != UO_AddrOf)
7296 E = UO->getSubExpr();
7300 unsigned DiagID = IsCompare
7301 ? diag::warn_address_of_reference_null_compare
7302 : diag::warn_address_of_reference_bool_conversion;
7303 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7305 if (CheckForReference(*this, E, PD)) {
7310 // Expect to find a single Decl. Skip anything more complicated.
7311 ValueDecl *D = nullptr;
7312 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7314 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7315 D = M->getMemberDecl();
7318 // Weak Decls can be null.
7319 if (!D || D->isWeak())
7322 // Check for parameter decl with nonnull attribute
7323 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7324 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7325 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7326 unsigned NumArgs = FD->getNumParams();
7327 llvm::SmallBitVector AttrNonNull(NumArgs);
7328 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7329 if (!NonNull->args_size()) {
7330 AttrNonNull.set(0, NumArgs);
7333 for (unsigned Val : NonNull->args()) {
7336 AttrNonNull.set(Val);
7339 if (!AttrNonNull.empty())
7340 for (unsigned i = 0; i < NumArgs; ++i)
7341 if (FD->getParamDecl(i) == PV &&
7342 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
7344 llvm::raw_string_ostream S(Str);
7345 E->printPretty(S, nullptr, getPrintingPolicy());
7346 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7347 : diag::warn_cast_nonnull_to_bool;
7348 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7349 << Range << IsEqual;
7355 QualType T = D->getType();
7356 const bool IsArray = T->isArrayType();
7357 const bool IsFunction = T->isFunctionType();
7359 // Address of function is used to silence the function warning.
7360 if (IsAddressOf && IsFunction) {
7365 if (!IsAddressOf && !IsFunction && !IsArray)
7368 // Pretty print the expression for the diagnostic.
7370 llvm::raw_string_ostream S(Str);
7371 E->printPretty(S, nullptr, getPrintingPolicy());
7373 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7374 : diag::warn_impcast_pointer_to_bool;
7377 DiagType = AddressOf;
7378 else if (IsFunction)
7379 DiagType = FunctionPointer;
7381 DiagType = ArrayPointer;
7383 llvm_unreachable("Could not determine diagnostic.");
7384 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7385 << Range << IsEqual;
7390 // Suggest '&' to silence the function warning.
7391 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7392 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7394 // Check to see if '()' fixit should be emitted.
7395 QualType ReturnType;
7396 UnresolvedSet<4> NonTemplateOverloads;
7397 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7398 if (ReturnType.isNull())
7402 // There are two cases here. If there is null constant, the only suggest
7403 // for a pointer return type. If the null is 0, then suggest if the return
7404 // type is a pointer or an integer type.
7405 if (!ReturnType->isPointerType()) {
7406 if (NullKind == Expr::NPCK_ZeroExpression ||
7407 NullKind == Expr::NPCK_ZeroLiteral) {
7408 if (!ReturnType->isIntegerType())
7414 } else { // !IsCompare
7415 // For function to bool, only suggest if the function pointer has bool
7417 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7420 Diag(E->getExprLoc(), diag::note_function_to_function_call)
7421 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
7425 /// Diagnoses "dangerous" implicit conversions within the given
7426 /// expression (which is a full expression). Implements -Wconversion
7427 /// and -Wsign-compare.
7429 /// \param CC the "context" location of the implicit conversion, i.e.
7430 /// the most location of the syntactic entity requiring the implicit
7432 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
7433 // Don't diagnose in unevaluated contexts.
7434 if (isUnevaluatedContext())
7437 // Don't diagnose for value- or type-dependent expressions.
7438 if (E->isTypeDependent() || E->isValueDependent())
7441 // Check for array bounds violations in cases where the check isn't triggered
7442 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7443 // ArraySubscriptExpr is on the RHS of a variable initialization.
7444 CheckArrayAccess(E);
7446 // This is not the right CC for (e.g.) a variable initialization.
7447 AnalyzeImplicitConversions(*this, E, CC);
7450 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7451 /// Input argument E is a logical expression.
7452 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7453 ::CheckBoolLikeConversion(*this, E, CC);
7456 /// Diagnose when expression is an integer constant expression and its evaluation
7457 /// results in integer overflow
7458 void Sema::CheckForIntOverflow (Expr *E) {
7459 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7460 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
7464 /// \brief Visitor for expressions which looks for unsequenced operations on the
7466 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
7467 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7469 /// \brief A tree of sequenced regions within an expression. Two regions are
7470 /// unsequenced if one is an ancestor or a descendent of the other. When we
7471 /// finish processing an expression with sequencing, such as a comma
7472 /// expression, we fold its tree nodes into its parent, since they are
7473 /// unsequenced with respect to nodes we will visit later.
7474 class SequenceTree {
7476 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7477 unsigned Parent : 31;
7480 SmallVector<Value, 8> Values;
7483 /// \brief A region within an expression which may be sequenced with respect
7484 /// to some other region.
7486 explicit Seq(unsigned N) : Index(N) {}
7488 friend class SequenceTree;
7493 SequenceTree() { Values.push_back(Value(0)); }
7494 Seq root() const { return Seq(0); }
7496 /// \brief Create a new sequence of operations, which is an unsequenced
7497 /// subset of \p Parent. This sequence of operations is sequenced with
7498 /// respect to other children of \p Parent.
7499 Seq allocate(Seq Parent) {
7500 Values.push_back(Value(Parent.Index));
7501 return Seq(Values.size() - 1);
7504 /// \brief Merge a sequence of operations into its parent.
7506 Values[S.Index].Merged = true;
7509 /// \brief Determine whether two operations are unsequenced. This operation
7510 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7511 /// should have been merged into its parent as appropriate.
7512 bool isUnsequenced(Seq Cur, Seq Old) {
7513 unsigned C = representative(Cur.Index);
7514 unsigned Target = representative(Old.Index);
7515 while (C >= Target) {
7518 C = Values[C].Parent;
7524 /// \brief Pick a representative for a sequence.
7525 unsigned representative(unsigned K) {
7526 if (Values[K].Merged)
7527 // Perform path compression as we go.
7528 return Values[K].Parent = representative(Values[K].Parent);
7533 /// An object for which we can track unsequenced uses.
7534 typedef NamedDecl *Object;
7536 /// Different flavors of object usage which we track. We only track the
7537 /// least-sequenced usage of each kind.
7539 /// A read of an object. Multiple unsequenced reads are OK.
7541 /// A modification of an object which is sequenced before the value
7542 /// computation of the expression, such as ++n in C++.
7544 /// A modification of an object which is not sequenced before the value
7545 /// computation of the expression, such as n++.
7548 UK_Count = UK_ModAsSideEffect + 1
7552 Usage() : Use(nullptr), Seq() {}
7554 SequenceTree::Seq Seq;
7558 UsageInfo() : Diagnosed(false) {}
7559 Usage Uses[UK_Count];
7560 /// Have we issued a diagnostic for this variable already?
7563 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7566 /// Sequenced regions within the expression.
7568 /// Declaration modifications and references which we have seen.
7569 UsageInfoMap UsageMap;
7570 /// The region we are currently within.
7571 SequenceTree::Seq Region;
7572 /// Filled in with declarations which were modified as a side-effect
7573 /// (that is, post-increment operations).
7574 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
7575 /// Expressions to check later. We defer checking these to reduce
7577 SmallVectorImpl<Expr *> &WorkList;
7579 /// RAII object wrapping the visitation of a sequenced subexpression of an
7580 /// expression. At the end of this process, the side-effects of the evaluation
7581 /// become sequenced with respect to the value computation of the result, so
7582 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7584 struct SequencedSubexpression {
7585 SequencedSubexpression(SequenceChecker &Self)
7586 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7587 Self.ModAsSideEffect = &ModAsSideEffect;
7589 ~SequencedSubexpression() {
7590 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7592 UsageInfo &U = Self.UsageMap[MI->first];
7593 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7594 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7595 SideEffectUsage = MI->second;
7597 Self.ModAsSideEffect = OldModAsSideEffect;
7600 SequenceChecker &Self;
7601 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7602 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
7605 /// RAII object wrapping the visitation of a subexpression which we might
7606 /// choose to evaluate as a constant. If any subexpression is evaluated and
7607 /// found to be non-constant, this allows us to suppress the evaluation of
7608 /// the outer expression.
7609 class EvaluationTracker {
7611 EvaluationTracker(SequenceChecker &Self)
7612 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7613 Self.EvalTracker = this;
7615 ~EvaluationTracker() {
7616 Self.EvalTracker = Prev;
7618 Prev->EvalOK &= EvalOK;
7621 bool evaluate(const Expr *E, bool &Result) {
7622 if (!EvalOK || E->isValueDependent())
7624 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7629 SequenceChecker &Self;
7630 EvaluationTracker *Prev;
7634 /// \brief Find the object which is produced by the specified expression,
7636 Object getObject(Expr *E, bool Mod) const {
7637 E = E->IgnoreParenCasts();
7638 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7639 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7640 return getObject(UO->getSubExpr(), Mod);
7641 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7642 if (BO->getOpcode() == BO_Comma)
7643 return getObject(BO->getRHS(), Mod);
7644 if (Mod && BO->isAssignmentOp())
7645 return getObject(BO->getLHS(), Mod);
7646 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7647 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7648 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7649 return ME->getMemberDecl();
7650 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7651 // FIXME: If this is a reference, map through to its value.
7652 return DRE->getDecl();
7656 /// \brief Note that an object was modified or used by an expression.
7657 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7658 Usage &U = UI.Uses[UK];
7659 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7660 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7661 ModAsSideEffect->push_back(std::make_pair(O, U));
7666 /// \brief Check whether a modification or use conflicts with a prior usage.
7667 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7672 const Usage &U = UI.Uses[OtherKind];
7673 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7677 Expr *ModOrUse = Ref;
7678 if (OtherKind == UK_Use)
7679 std::swap(Mod, ModOrUse);
7681 SemaRef.Diag(Mod->getExprLoc(),
7682 IsModMod ? diag::warn_unsequenced_mod_mod
7683 : diag::warn_unsequenced_mod_use)
7684 << O << SourceRange(ModOrUse->getExprLoc());
7685 UI.Diagnosed = true;
7688 void notePreUse(Object O, Expr *Use) {
7689 UsageInfo &U = UsageMap[O];
7690 // Uses conflict with other modifications.
7691 checkUsage(O, U, Use, UK_ModAsValue, false);
7693 void notePostUse(Object O, Expr *Use) {
7694 UsageInfo &U = UsageMap[O];
7695 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7696 addUsage(U, O, Use, UK_Use);
7699 void notePreMod(Object O, Expr *Mod) {
7700 UsageInfo &U = UsageMap[O];
7701 // Modifications conflict with other modifications and with uses.
7702 checkUsage(O, U, Mod, UK_ModAsValue, true);
7703 checkUsage(O, U, Mod, UK_Use, false);
7705 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7706 UsageInfo &U = UsageMap[O];
7707 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7708 addUsage(U, O, Use, UK);
7712 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
7713 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7714 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
7718 void VisitStmt(Stmt *S) {
7719 // Skip all statements which aren't expressions for now.
7722 void VisitExpr(Expr *E) {
7723 // By default, just recurse to evaluated subexpressions.
7727 void VisitCastExpr(CastExpr *E) {
7728 Object O = Object();
7729 if (E->getCastKind() == CK_LValueToRValue)
7730 O = getObject(E->getSubExpr(), false);
7739 void VisitBinComma(BinaryOperator *BO) {
7740 // C++11 [expr.comma]p1:
7741 // Every value computation and side effect associated with the left
7742 // expression is sequenced before every value computation and side
7743 // effect associated with the right expression.
7744 SequenceTree::Seq LHS = Tree.allocate(Region);
7745 SequenceTree::Seq RHS = Tree.allocate(Region);
7746 SequenceTree::Seq OldRegion = Region;
7749 SequencedSubexpression SeqLHS(*this);
7751 Visit(BO->getLHS());
7755 Visit(BO->getRHS());
7759 // Forget that LHS and RHS are sequenced. They are both unsequenced
7760 // with respect to other stuff.
7765 void VisitBinAssign(BinaryOperator *BO) {
7766 // The modification is sequenced after the value computation of the LHS
7767 // and RHS, so check it before inspecting the operands and update the
7769 Object O = getObject(BO->getLHS(), true);
7771 return VisitExpr(BO);
7775 // C++11 [expr.ass]p7:
7776 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7779 // Therefore, for a compound assignment operator, O is considered used
7780 // everywhere except within the evaluation of E1 itself.
7781 if (isa<CompoundAssignOperator>(BO))
7784 Visit(BO->getLHS());
7786 if (isa<CompoundAssignOperator>(BO))
7789 Visit(BO->getRHS());
7791 // C++11 [expr.ass]p1:
7792 // the assignment is sequenced [...] before the value computation of the
7793 // assignment expression.
7794 // C11 6.5.16/3 has no such rule.
7795 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7796 : UK_ModAsSideEffect);
7798 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7799 VisitBinAssign(CAO);
7802 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7803 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7804 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7805 Object O = getObject(UO->getSubExpr(), true);
7807 return VisitExpr(UO);
7810 Visit(UO->getSubExpr());
7811 // C++11 [expr.pre.incr]p1:
7812 // the expression ++x is equivalent to x+=1
7813 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7814 : UK_ModAsSideEffect);
7817 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7818 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7819 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7820 Object O = getObject(UO->getSubExpr(), true);
7822 return VisitExpr(UO);
7825 Visit(UO->getSubExpr());
7826 notePostMod(O, UO, UK_ModAsSideEffect);
7829 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7830 void VisitBinLOr(BinaryOperator *BO) {
7831 // The side-effects of the LHS of an '&&' are sequenced before the
7832 // value computation of the RHS, and hence before the value computation
7833 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7834 // as if they were unconditionally sequenced.
7835 EvaluationTracker Eval(*this);
7837 SequencedSubexpression Sequenced(*this);
7838 Visit(BO->getLHS());
7842 if (Eval.evaluate(BO->getLHS(), Result)) {
7844 Visit(BO->getRHS());
7846 // Check for unsequenced operations in the RHS, treating it as an
7847 // entirely separate evaluation.
7849 // FIXME: If there are operations in the RHS which are unsequenced
7850 // with respect to operations outside the RHS, and those operations
7851 // are unconditionally evaluated, diagnose them.
7852 WorkList.push_back(BO->getRHS());
7855 void VisitBinLAnd(BinaryOperator *BO) {
7856 EvaluationTracker Eval(*this);
7858 SequencedSubexpression Sequenced(*this);
7859 Visit(BO->getLHS());
7863 if (Eval.evaluate(BO->getLHS(), Result)) {
7865 Visit(BO->getRHS());
7867 WorkList.push_back(BO->getRHS());
7871 // Only visit the condition, unless we can be sure which subexpression will
7873 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
7874 EvaluationTracker Eval(*this);
7876 SequencedSubexpression Sequenced(*this);
7877 Visit(CO->getCond());
7881 if (Eval.evaluate(CO->getCond(), Result))
7882 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
7884 WorkList.push_back(CO->getTrueExpr());
7885 WorkList.push_back(CO->getFalseExpr());
7889 void VisitCallExpr(CallExpr *CE) {
7890 // C++11 [intro.execution]p15:
7891 // When calling a function [...], every value computation and side effect
7892 // associated with any argument expression, or with the postfix expression
7893 // designating the called function, is sequenced before execution of every
7894 // expression or statement in the body of the function [and thus before
7895 // the value computation of its result].
7896 SequencedSubexpression Sequenced(*this);
7897 Base::VisitCallExpr(CE);
7899 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7902 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
7903 // This is a call, so all subexpressions are sequenced before the result.
7904 SequencedSubexpression Sequenced(*this);
7906 if (!CCE->isListInitialization())
7907 return VisitExpr(CCE);
7909 // In C++11, list initializations are sequenced.
7910 SmallVector<SequenceTree::Seq, 32> Elts;
7911 SequenceTree::Seq Parent = Region;
7912 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7915 Region = Tree.allocate(Parent);
7916 Elts.push_back(Region);
7920 // Forget that the initializers are sequenced.
7922 for (unsigned I = 0; I < Elts.size(); ++I)
7923 Tree.merge(Elts[I]);
7926 void VisitInitListExpr(InitListExpr *ILE) {
7927 if (!SemaRef.getLangOpts().CPlusPlus11)
7928 return VisitExpr(ILE);
7930 // In C++11, list initializations are sequenced.
7931 SmallVector<SequenceTree::Seq, 32> Elts;
7932 SequenceTree::Seq Parent = Region;
7933 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7934 Expr *E = ILE->getInit(I);
7936 Region = Tree.allocate(Parent);
7937 Elts.push_back(Region);
7941 // Forget that the initializers are sequenced.
7943 for (unsigned I = 0; I < Elts.size(); ++I)
7944 Tree.merge(Elts[I]);
7949 void Sema::CheckUnsequencedOperations(Expr *E) {
7950 SmallVector<Expr *, 8> WorkList;
7951 WorkList.push_back(E);
7952 while (!WorkList.empty()) {
7953 Expr *Item = WorkList.pop_back_val();
7954 SequenceChecker(*this, Item, WorkList);
7958 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7960 CheckImplicitConversions(E, CheckLoc);
7961 CheckUnsequencedOperations(E);
7962 if (!IsConstexpr && !E->isValueDependent())
7963 CheckForIntOverflow(E);
7966 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7967 FieldDecl *BitField,
7969 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7972 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
7973 SourceLocation Loc) {
7974 if (!PType->isVariablyModifiedType())
7976 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
7977 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
7980 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
7981 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
7984 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
7985 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
7989 const ArrayType *AT = S.Context.getAsArrayType(PType);
7993 if (AT->getSizeModifier() != ArrayType::Star) {
7994 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
7998 S.Diag(Loc, diag::err_array_star_in_function_definition);
8001 /// CheckParmsForFunctionDef - Check that the parameters of the given
8002 /// function are appropriate for the definition of a function. This
8003 /// takes care of any checks that cannot be performed on the
8004 /// declaration itself, e.g., that the types of each of the function
8005 /// parameters are complete.
8006 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8007 ParmVarDecl *const *PEnd,
8008 bool CheckParameterNames) {
8009 bool HasInvalidParm = false;
8010 for (; P != PEnd; ++P) {
8011 ParmVarDecl *Param = *P;
8013 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8014 // function declarator that is part of a function definition of
8015 // that function shall not have incomplete type.
8017 // This is also C++ [dcl.fct]p6.
8018 if (!Param->isInvalidDecl() &&
8019 RequireCompleteType(Param->getLocation(), Param->getType(),
8020 diag::err_typecheck_decl_incomplete_type)) {
8021 Param->setInvalidDecl();
8022 HasInvalidParm = true;
8025 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8026 // declaration of each parameter shall include an identifier.
8027 if (CheckParameterNames &&
8028 Param->getIdentifier() == nullptr &&
8029 !Param->isImplicit() &&
8030 !getLangOpts().CPlusPlus)
8031 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
8034 // If the function declarator is not part of a definition of that
8035 // function, parameters may have incomplete type and may use the [*]
8036 // notation in their sequences of declarator specifiers to specify
8037 // variable length array types.
8038 QualType PType = Param->getOriginalType();
8039 // FIXME: This diagnostic should point the '[*]' if source-location
8040 // information is added for it.
8041 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
8043 // MSVC destroys objects passed by value in the callee. Therefore a
8044 // function definition which takes such a parameter must be able to call the
8045 // object's destructor. However, we don't perform any direct access check
8047 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8049 .areArgsDestroyedLeftToRightInCallee()) {
8050 if (!Param->isInvalidDecl()) {
8051 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8052 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8053 if (!ClassDecl->isInvalidDecl() &&
8054 !ClassDecl->hasIrrelevantDestructor() &&
8055 !ClassDecl->isDependentContext()) {
8056 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8057 MarkFunctionReferenced(Param->getLocation(), Destructor);
8058 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8065 return HasInvalidParm;
8068 /// CheckCastAlign - Implements -Wcast-align, which warns when a
8069 /// pointer cast increases the alignment requirements.
8070 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8071 // This is actually a lot of work to potentially be doing on every
8072 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
8073 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
8076 // Ignore dependent types.
8077 if (T->isDependentType() || Op->getType()->isDependentType())
8080 // Require that the destination be a pointer type.
8081 const PointerType *DestPtr = T->getAs<PointerType>();
8082 if (!DestPtr) return;
8084 // If the destination has alignment 1, we're done.
8085 QualType DestPointee = DestPtr->getPointeeType();
8086 if (DestPointee->isIncompleteType()) return;
8087 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8088 if (DestAlign.isOne()) return;
8090 // Require that the source be a pointer type.
8091 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8092 if (!SrcPtr) return;
8093 QualType SrcPointee = SrcPtr->getPointeeType();
8095 // Whitelist casts from cv void*. We already implicitly
8096 // whitelisted casts to cv void*, since they have alignment 1.
8097 // Also whitelist casts involving incomplete types, which implicitly
8099 if (SrcPointee->isIncompleteType()) return;
8101 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8102 if (SrcAlign >= DestAlign) return;
8104 Diag(TRange.getBegin(), diag::warn_cast_align)
8105 << Op->getType() << T
8106 << static_cast<unsigned>(SrcAlign.getQuantity())
8107 << static_cast<unsigned>(DestAlign.getQuantity())
8108 << TRange << Op->getSourceRange();
8111 static const Type* getElementType(const Expr *BaseExpr) {
8112 const Type* EltType = BaseExpr->getType().getTypePtr();
8113 if (EltType->isAnyPointerType())
8114 return EltType->getPointeeType().getTypePtr();
8115 else if (EltType->isArrayType())
8116 return EltType->getBaseElementTypeUnsafe();
8120 /// \brief Check whether this array fits the idiom of a size-one tail padded
8121 /// array member of a struct.
8123 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
8124 /// commonly used to emulate flexible arrays in C89 code.
8125 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8126 const NamedDecl *ND) {
8127 if (Size != 1 || !ND) return false;
8129 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8130 if (!FD) return false;
8132 // Don't consider sizes resulting from macro expansions or template argument
8133 // substitution to form C89 tail-padded arrays.
8135 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
8137 TypeLoc TL = TInfo->getTypeLoc();
8138 // Look through typedefs.
8139 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8140 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
8141 TInfo = TDL->getTypeSourceInfo();
8144 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8145 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
8146 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8152 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
8153 if (!RD) return false;
8154 if (RD->isUnion()) return false;
8155 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8156 if (!CRD->isStandardLayout()) return false;
8159 // See if this is the last field decl in the record.
8161 while ((D = D->getNextDeclInContext()))
8162 if (isa<FieldDecl>(D))
8167 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
8168 const ArraySubscriptExpr *ASE,
8169 bool AllowOnePastEnd, bool IndexNegated) {
8170 IndexExpr = IndexExpr->IgnoreParenImpCasts();
8171 if (IndexExpr->isValueDependent())
8174 const Type *EffectiveType = getElementType(BaseExpr);
8175 BaseExpr = BaseExpr->IgnoreParenCasts();
8176 const ConstantArrayType *ArrayTy =
8177 Context.getAsConstantArrayType(BaseExpr->getType());
8182 if (!IndexExpr->EvaluateAsInt(index, Context))
8187 const NamedDecl *ND = nullptr;
8188 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8189 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8190 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8191 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8193 if (index.isUnsigned() || !index.isNegative()) {
8194 llvm::APInt size = ArrayTy->getSize();
8195 if (!size.isStrictlyPositive())
8198 const Type* BaseType = getElementType(BaseExpr);
8199 if (BaseType != EffectiveType) {
8200 // Make sure we're comparing apples to apples when comparing index to size
8201 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8202 uint64_t array_typesize = Context.getTypeSize(BaseType);
8203 // Handle ptrarith_typesize being zero, such as when casting to void*
8204 if (!ptrarith_typesize) ptrarith_typesize = 1;
8205 if (ptrarith_typesize != array_typesize) {
8206 // There's a cast to a different size type involved
8207 uint64_t ratio = array_typesize / ptrarith_typesize;
8208 // TODO: Be smarter about handling cases where array_typesize is not a
8209 // multiple of ptrarith_typesize
8210 if (ptrarith_typesize * ratio == array_typesize)
8211 size *= llvm::APInt(size.getBitWidth(), ratio);
8215 if (size.getBitWidth() > index.getBitWidth())
8216 index = index.zext(size.getBitWidth());
8217 else if (size.getBitWidth() < index.getBitWidth())
8218 size = size.zext(index.getBitWidth());
8220 // For array subscripting the index must be less than size, but for pointer
8221 // arithmetic also allow the index (offset) to be equal to size since
8222 // computing the next address after the end of the array is legal and
8223 // commonly done e.g. in C++ iterators and range-based for loops.
8224 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
8227 // Also don't warn for arrays of size 1 which are members of some
8228 // structure. These are often used to approximate flexible arrays in C89
8230 if (IsTailPaddedMemberArray(*this, size, ND))
8233 // Suppress the warning if the subscript expression (as identified by the
8234 // ']' location) and the index expression are both from macro expansions
8235 // within a system header.
8237 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8238 ASE->getRBracketLoc());
8239 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8240 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8241 IndexExpr->getLocStart());
8242 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
8247 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
8249 DiagID = diag::warn_array_index_exceeds_bounds;
8251 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8252 PDiag(DiagID) << index.toString(10, true)
8253 << size.toString(10, true)
8254 << (unsigned)size.getLimitedValue(~0U)
8255 << IndexExpr->getSourceRange());
8257 unsigned DiagID = diag::warn_array_index_precedes_bounds;
8259 DiagID = diag::warn_ptr_arith_precedes_bounds;
8260 if (index.isNegative()) index = -index;
8263 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8264 PDiag(DiagID) << index.toString(10, true)
8265 << IndexExpr->getSourceRange());
8269 // Try harder to find a NamedDecl to point at in the note.
8270 while (const ArraySubscriptExpr *ASE =
8271 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8272 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8273 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8274 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8275 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8276 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8280 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8281 PDiag(diag::note_array_index_out_of_bounds)
8282 << ND->getDeclName());
8285 void Sema::CheckArrayAccess(const Expr *expr) {
8286 int AllowOnePastEnd = 0;
8288 expr = expr->IgnoreParenImpCasts();
8289 switch (expr->getStmtClass()) {
8290 case Stmt::ArraySubscriptExprClass: {
8291 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
8292 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
8293 AllowOnePastEnd > 0);
8296 case Stmt::UnaryOperatorClass: {
8297 // Only unwrap the * and & unary operators
8298 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8299 expr = UO->getSubExpr();
8300 switch (UO->getOpcode()) {
8312 case Stmt::ConditionalOperatorClass: {
8313 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8314 if (const Expr *lhs = cond->getLHS())
8315 CheckArrayAccess(lhs);
8316 if (const Expr *rhs = cond->getRHS())
8317 CheckArrayAccess(rhs);
8326 //===--- CHECK: Objective-C retain cycles ----------------------------------//
8329 struct RetainCycleOwner {
8330 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
8336 void setLocsFrom(Expr *e) {
8337 Loc = e->getExprLoc();
8338 Range = e->getSourceRange();
8343 /// Consider whether capturing the given variable can possibly lead to
8345 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
8346 // In ARC, it's captured strongly iff the variable has __strong
8347 // lifetime. In MRR, it's captured strongly if the variable is
8348 // __block and has an appropriate type.
8349 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8352 owner.Variable = var;
8354 owner.setLocsFrom(ref);
8358 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
8360 e = e->IgnoreParens();
8361 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8362 switch (cast->getCastKind()) {
8364 case CK_LValueBitCast:
8365 case CK_LValueToRValue:
8366 case CK_ARCReclaimReturnedObject:
8367 e = cast->getSubExpr();
8375 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8376 ObjCIvarDecl *ivar = ref->getDecl();
8377 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8380 // Try to find a retain cycle in the base.
8381 if (!findRetainCycleOwner(S, ref->getBase(), owner))
8384 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8385 owner.Indirect = true;
8389 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8390 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8391 if (!var) return false;
8392 return considerVariable(var, ref, owner);
8395 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8396 if (member->isArrow()) return false;
8398 // Don't count this as an indirect ownership.
8399 e = member->getBase();
8403 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8404 // Only pay attention to pseudo-objects on property references.
8405 ObjCPropertyRefExpr *pre
8406 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8408 if (!pre) return false;
8409 if (pre->isImplicitProperty()) return false;
8410 ObjCPropertyDecl *property = pre->getExplicitProperty();
8411 if (!property->isRetaining() &&
8412 !(property->getPropertyIvarDecl() &&
8413 property->getPropertyIvarDecl()->getType()
8414 .getObjCLifetime() == Qualifiers::OCL_Strong))
8417 owner.Indirect = true;
8418 if (pre->isSuperReceiver()) {
8419 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8420 if (!owner.Variable)
8422 owner.Loc = pre->getLocation();
8423 owner.Range = pre->getSourceRange();
8426 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8438 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8439 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8440 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
8441 Context(Context), Variable(variable), Capturer(nullptr),
8442 VarWillBeReased(false) {}
8443 ASTContext &Context;
8446 bool VarWillBeReased;
8448 void VisitDeclRefExpr(DeclRefExpr *ref) {
8449 if (ref->getDecl() == Variable && !Capturer)
8453 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8454 if (Capturer) return;
8455 Visit(ref->getBase());
8456 if (Capturer && ref->isFreeIvar())
8460 void VisitBlockExpr(BlockExpr *block) {
8461 // Look inside nested blocks
8462 if (block->getBlockDecl()->capturesVariable(Variable))
8463 Visit(block->getBlockDecl()->getBody());
8466 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8467 if (Capturer) return;
8468 if (OVE->getSourceExpr())
8469 Visit(OVE->getSourceExpr());
8471 void VisitBinaryOperator(BinaryOperator *BinOp) {
8472 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8474 Expr *LHS = BinOp->getLHS();
8475 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8476 if (DRE->getDecl() != Variable)
8478 if (Expr *RHS = BinOp->getRHS()) {
8479 RHS = RHS->IgnoreParenCasts();
8482 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8489 /// Check whether the given argument is a block which captures a
8491 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8492 assert(owner.Variable && owner.Loc.isValid());
8494 e = e->IgnoreParenCasts();
8496 // Look through [^{...} copy] and Block_copy(^{...}).
8497 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8498 Selector Cmd = ME->getSelector();
8499 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8500 e = ME->getInstanceReceiver();
8503 e = e->IgnoreParenCasts();
8505 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8506 if (CE->getNumArgs() == 1) {
8507 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
8509 const IdentifierInfo *FnI = Fn->getIdentifier();
8510 if (FnI && FnI->isStr("_Block_copy")) {
8511 e = CE->getArg(0)->IgnoreParenCasts();
8517 BlockExpr *block = dyn_cast<BlockExpr>(e);
8518 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
8521 FindCaptureVisitor visitor(S.Context, owner.Variable);
8522 visitor.Visit(block->getBlockDecl()->getBody());
8523 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
8526 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8527 RetainCycleOwner &owner) {
8529 assert(owner.Variable && owner.Loc.isValid());
8531 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8532 << owner.Variable << capturer->getSourceRange();
8533 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8534 << owner.Indirect << owner.Range;
8537 /// Check for a keyword selector that starts with the word 'add' or
8539 static bool isSetterLikeSelector(Selector sel) {
8540 if (sel.isUnarySelector()) return false;
8542 StringRef str = sel.getNameForSlot(0);
8543 while (!str.empty() && str.front() == '_') str = str.substr(1);
8544 if (str.startswith("set"))
8545 str = str.substr(3);
8546 else if (str.startswith("add")) {
8547 // Specially whitelist 'addOperationWithBlock:'.
8548 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8550 str = str.substr(3);
8555 if (str.empty()) return true;
8556 return !isLowercase(str.front());
8559 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8560 ObjCMessageExpr *Message) {
8561 if (S.NSMutableArrayPointer.isNull()) {
8562 IdentifierInfo *NSMutableArrayId =
8563 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8564 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8565 Message->getLocStart(),
8566 Sema::LookupOrdinaryName);
8567 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8568 if (!InterfaceDecl) {
8571 QualType NSMutableArrayObject =
8572 S.Context.getObjCInterfaceType(InterfaceDecl);
8573 S.NSMutableArrayPointer =
8574 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8577 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8581 Selector Sel = Message->getSelector();
8583 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8584 S.NSAPIObj->getNSArrayMethodKind(Sel);
8589 NSAPI::NSArrayMethodKind MK = *MKOpt;
8592 case NSAPI::NSMutableArr_addObject:
8593 case NSAPI::NSMutableArr_insertObjectAtIndex:
8594 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8596 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8607 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8608 ObjCMessageExpr *Message) {
8610 if (S.NSMutableDictionaryPointer.isNull()) {
8611 IdentifierInfo *NSMutableDictionaryId =
8612 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8613 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8614 Message->getLocStart(),
8615 Sema::LookupOrdinaryName);
8616 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8617 if (!InterfaceDecl) {
8620 QualType NSMutableDictionaryObject =
8621 S.Context.getObjCInterfaceType(InterfaceDecl);
8622 S.NSMutableDictionaryPointer =
8623 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8626 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8630 Selector Sel = Message->getSelector();
8632 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8633 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8638 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8641 case NSAPI::NSMutableDict_setObjectForKey:
8642 case NSAPI::NSMutableDict_setValueForKey:
8643 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8653 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8655 ObjCInterfaceDecl *InterfaceDecl;
8656 if (S.NSMutableSetPointer.isNull()) {
8657 IdentifierInfo *NSMutableSetId =
8658 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8659 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8660 Message->getLocStart(),
8661 Sema::LookupOrdinaryName);
8662 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8663 if (InterfaceDecl) {
8664 QualType NSMutableSetObject =
8665 S.Context.getObjCInterfaceType(InterfaceDecl);
8666 S.NSMutableSetPointer =
8667 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8671 if (S.NSCountedSetPointer.isNull()) {
8672 IdentifierInfo *NSCountedSetId =
8673 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8674 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8675 Message->getLocStart(),
8676 Sema::LookupOrdinaryName);
8677 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8678 if (InterfaceDecl) {
8679 QualType NSCountedSetObject =
8680 S.Context.getObjCInterfaceType(InterfaceDecl);
8681 S.NSCountedSetPointer =
8682 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8686 if (S.NSMutableOrderedSetPointer.isNull()) {
8687 IdentifierInfo *NSOrderedSetId =
8688 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8689 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8690 Message->getLocStart(),
8691 Sema::LookupOrdinaryName);
8692 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8693 if (InterfaceDecl) {
8694 QualType NSOrderedSetObject =
8695 S.Context.getObjCInterfaceType(InterfaceDecl);
8696 S.NSMutableOrderedSetPointer =
8697 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8701 QualType ReceiverType = Message->getReceiverType();
8703 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8704 ReceiverType == S.NSMutableSetPointer;
8705 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8706 ReceiverType == S.NSMutableOrderedSetPointer;
8707 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8708 ReceiverType == S.NSCountedSetPointer;
8710 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8714 Selector Sel = Message->getSelector();
8716 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8721 NSAPI::NSSetMethodKind MK = *MKOpt;
8724 case NSAPI::NSMutableSet_addObject:
8725 case NSAPI::NSOrderedSet_setObjectAtIndex:
8726 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8727 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8729 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8736 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8737 if (!Message->isInstanceMessage()) {
8741 Optional<int> ArgOpt;
8743 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8744 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8745 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8749 int ArgIndex = *ArgOpt;
8751 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8752 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8753 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8756 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8757 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8758 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8761 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8762 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8763 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8764 ValueDecl *Decl = ReceiverRE->getDecl();
8765 Diag(Message->getSourceRange().getBegin(),
8766 diag::warn_objc_circular_container)
8768 Diag(Decl->getLocation(),
8769 diag::note_objc_circular_container_declared_here)
8773 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8774 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8775 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8776 ObjCIvarDecl *Decl = IvarRE->getDecl();
8777 Diag(Message->getSourceRange().getBegin(),
8778 diag::warn_objc_circular_container)
8780 Diag(Decl->getLocation(),
8781 diag::note_objc_circular_container_declared_here)
8789 /// Check a message send to see if it's likely to cause a retain cycle.
8790 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8791 // Only check instance methods whose selector looks like a setter.
8792 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8795 // Try to find a variable that the receiver is strongly owned by.
8796 RetainCycleOwner owner;
8797 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
8798 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
8801 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8802 owner.Variable = getCurMethodDecl()->getSelfDecl();
8803 owner.Loc = msg->getSuperLoc();
8804 owner.Range = msg->getSuperLoc();
8807 // Check whether the receiver is captured by any of the arguments.
8808 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8809 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8810 return diagnoseRetainCycle(*this, capturer, owner);
8813 /// Check a property assign to see if it's likely to cause a retain cycle.
8814 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8815 RetainCycleOwner owner;
8816 if (!findRetainCycleOwner(*this, receiver, owner))
8819 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8820 diagnoseRetainCycle(*this, capturer, owner);
8823 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8824 RetainCycleOwner Owner;
8825 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
8828 // Because we don't have an expression for the variable, we have to set the
8829 // location explicitly here.
8830 Owner.Loc = Var->getLocation();
8831 Owner.Range = Var->getSourceRange();
8833 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8834 diagnoseRetainCycle(*this, Capturer, Owner);
8837 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8838 Expr *RHS, bool isProperty) {
8839 // Check if RHS is an Objective-C object literal, which also can get
8840 // immediately zapped in a weak reference. Note that we explicitly
8841 // allow ObjCStringLiterals, since those are designed to never really die.
8842 RHS = RHS->IgnoreParenImpCasts();
8844 // This enum needs to match with the 'select' in
8845 // warn_objc_arc_literal_assign (off-by-1).
8846 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8847 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8850 S.Diag(Loc, diag::warn_arc_literal_assign)
8852 << (isProperty ? 0 : 1)
8853 << RHS->getSourceRange();
8858 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8859 Qualifiers::ObjCLifetime LT,
8860 Expr *RHS, bool isProperty) {
8861 // Strip off any implicit cast added to get to the one ARC-specific.
8862 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8863 if (cast->getCastKind() == CK_ARCConsumeObject) {
8864 S.Diag(Loc, diag::warn_arc_retained_assign)
8865 << (LT == Qualifiers::OCL_ExplicitNone)
8866 << (isProperty ? 0 : 1)
8867 << RHS->getSourceRange();
8870 RHS = cast->getSubExpr();
8873 if (LT == Qualifiers::OCL_Weak &&
8874 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8880 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8881 QualType LHS, Expr *RHS) {
8882 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8884 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8887 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8893 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8894 Expr *LHS, Expr *RHS) {
8896 // PropertyRef on LHS type need be directly obtained from
8897 // its declaration as it has a PseudoType.
8898 ObjCPropertyRefExpr *PRE
8899 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8900 if (PRE && !PRE->isImplicitProperty()) {
8901 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8903 LHSType = PD->getType();
8906 if (LHSType.isNull())
8907 LHSType = LHS->getType();
8909 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8911 if (LT == Qualifiers::OCL_Weak) {
8912 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
8913 getCurFunction()->markSafeWeakUse(LHS);
8916 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8919 // FIXME. Check for other life times.
8920 if (LT != Qualifiers::OCL_None)
8924 if (PRE->isImplicitProperty())
8926 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8930 unsigned Attributes = PD->getPropertyAttributes();
8931 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
8932 // when 'assign' attribute was not explicitly specified
8933 // by user, ignore it and rely on property type itself
8934 // for lifetime info.
8935 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8936 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8937 LHSType->isObjCRetainableType())
8940 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8941 if (cast->getCastKind() == CK_ARCConsumeObject) {
8942 Diag(Loc, diag::warn_arc_retained_property_assign)
8943 << RHS->getSourceRange();
8946 RHS = cast->getSubExpr();
8949 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
8950 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8956 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8959 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8960 SourceLocation StmtLoc,
8961 const NullStmt *Body) {
8962 // Do not warn if the body is a macro that expands to nothing, e.g:
8968 if (Body->hasLeadingEmptyMacro())
8971 // Get line numbers of statement and body.
8972 bool StmtLineInvalid;
8973 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
8975 if (StmtLineInvalid)
8978 bool BodyLineInvalid;
8979 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8981 if (BodyLineInvalid)
8984 // Warn if null statement and body are on the same line.
8985 if (StmtLine != BodyLine)
8990 } // Unnamed namespace
8992 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8995 // Since this is a syntactic check, don't emit diagnostic for template
8996 // instantiations, this just adds noise.
8997 if (CurrentInstantiationScope)
9000 // The body should be a null statement.
9001 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9005 // Do the usual checks.
9006 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9009 Diag(NBody->getSemiLoc(), DiagID);
9010 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9013 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9014 const Stmt *PossibleBody) {
9015 assert(!CurrentInstantiationScope); // Ensured by caller
9017 SourceLocation StmtLoc;
9020 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9021 StmtLoc = FS->getRParenLoc();
9022 Body = FS->getBody();
9023 DiagID = diag::warn_empty_for_body;
9024 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9025 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9026 Body = WS->getBody();
9027 DiagID = diag::warn_empty_while_body;
9029 return; // Neither `for' nor `while'.
9031 // The body should be a null statement.
9032 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9036 // Skip expensive checks if diagnostic is disabled.
9037 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
9040 // Do the usual checks.
9041 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9044 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9045 // noise level low, emit diagnostics only if for/while is followed by a
9046 // CompoundStmt, e.g.:
9047 // for (int i = 0; i < n; i++);
9051 // or if for/while is followed by a statement with more indentation
9052 // than for/while itself:
9053 // for (int i = 0; i < n; i++);
9055 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9056 if (!ProbableTypo) {
9057 bool BodyColInvalid;
9058 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9059 PossibleBody->getLocStart(),
9064 bool StmtColInvalid;
9065 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9071 if (BodyCol > StmtCol)
9072 ProbableTypo = true;
9076 Diag(NBody->getSemiLoc(), DiagID);
9077 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9081 //===--- CHECK: Warn on self move with std::move. -------------------------===//
9083 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9084 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9085 SourceLocation OpLoc) {
9087 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9090 if (!ActiveTemplateInstantiations.empty())
9093 // Strip parens and casts away.
9094 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9095 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9097 // Check for a call expression
9098 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9099 if (!CE || CE->getNumArgs() != 1)
9102 // Check for a call to std::move
9103 const FunctionDecl *FD = CE->getDirectCallee();
9104 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9105 !FD->getIdentifier()->isStr("move"))
9108 // Get argument from std::move
9109 RHSExpr = CE->getArg(0);
9111 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9112 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9114 // Two DeclRefExpr's, check that the decls are the same.
9115 if (LHSDeclRef && RHSDeclRef) {
9116 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9118 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9119 RHSDeclRef->getDecl()->getCanonicalDecl())
9122 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9123 << LHSExpr->getSourceRange()
9124 << RHSExpr->getSourceRange();
9128 // Member variables require a different approach to check for self moves.
9129 // MemberExpr's are the same if every nested MemberExpr refers to the same
9130 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9131 // the base Expr's are CXXThisExpr's.
9132 const Expr *LHSBase = LHSExpr;
9133 const Expr *RHSBase = RHSExpr;
9134 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9135 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9136 if (!LHSME || !RHSME)
9139 while (LHSME && RHSME) {
9140 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9141 RHSME->getMemberDecl()->getCanonicalDecl())
9144 LHSBase = LHSME->getBase();
9145 RHSBase = RHSME->getBase();
9146 LHSME = dyn_cast<MemberExpr>(LHSBase);
9147 RHSME = dyn_cast<MemberExpr>(RHSBase);
9150 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9151 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9152 if (LHSDeclRef && RHSDeclRef) {
9153 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9155 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9156 RHSDeclRef->getDecl()->getCanonicalDecl())
9159 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9160 << LHSExpr->getSourceRange()
9161 << RHSExpr->getSourceRange();
9165 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9166 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9167 << LHSExpr->getSourceRange()
9168 << RHSExpr->getSourceRange();
9171 //===--- Layout compatibility ----------------------------------------------//
9175 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9177 /// \brief Check if two enumeration types are layout-compatible.
9178 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9179 // C++11 [dcl.enum] p8:
9180 // Two enumeration types are layout-compatible if they have the same
9182 return ED1->isComplete() && ED2->isComplete() &&
9183 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9186 /// \brief Check if two fields are layout-compatible.
9187 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9188 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9191 if (Field1->isBitField() != Field2->isBitField())
9194 if (Field1->isBitField()) {
9195 // Make sure that the bit-fields are the same length.
9196 unsigned Bits1 = Field1->getBitWidthValue(C);
9197 unsigned Bits2 = Field2->getBitWidthValue(C);
9206 /// \brief Check if two standard-layout structs are layout-compatible.
9207 /// (C++11 [class.mem] p17)
9208 bool isLayoutCompatibleStruct(ASTContext &C,
9211 // If both records are C++ classes, check that base classes match.
9212 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9213 // If one of records is a CXXRecordDecl we are in C++ mode,
9214 // thus the other one is a CXXRecordDecl, too.
9215 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9216 // Check number of base classes.
9217 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9220 // Check the base classes.
9221 for (CXXRecordDecl::base_class_const_iterator
9222 Base1 = D1CXX->bases_begin(),
9223 BaseEnd1 = D1CXX->bases_end(),
9224 Base2 = D2CXX->bases_begin();
9227 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9230 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9231 // If only RD2 is a C++ class, it should have zero base classes.
9232 if (D2CXX->getNumBases() > 0)
9236 // Check the fields.
9237 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9238 Field2End = RD2->field_end(),
9239 Field1 = RD1->field_begin(),
9240 Field1End = RD1->field_end();
9241 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9242 if (!isLayoutCompatible(C, *Field1, *Field2))
9245 if (Field1 != Field1End || Field2 != Field2End)
9251 /// \brief Check if two standard-layout unions are layout-compatible.
9252 /// (C++11 [class.mem] p18)
9253 bool isLayoutCompatibleUnion(ASTContext &C,
9256 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
9257 for (auto *Field2 : RD2->fields())
9258 UnmatchedFields.insert(Field2);
9260 for (auto *Field1 : RD1->fields()) {
9261 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9262 I = UnmatchedFields.begin(),
9263 E = UnmatchedFields.end();
9265 for ( ; I != E; ++I) {
9266 if (isLayoutCompatible(C, Field1, *I)) {
9267 bool Result = UnmatchedFields.erase(*I);
9277 return UnmatchedFields.empty();
9280 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9281 if (RD1->isUnion() != RD2->isUnion())
9285 return isLayoutCompatibleUnion(C, RD1, RD2);
9287 return isLayoutCompatibleStruct(C, RD1, RD2);
9290 /// \brief Check if two types are layout-compatible in C++11 sense.
9291 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9292 if (T1.isNull() || T2.isNull())
9295 // C++11 [basic.types] p11:
9296 // If two types T1 and T2 are the same type, then T1 and T2 are
9297 // layout-compatible types.
9298 if (C.hasSameType(T1, T2))
9301 T1 = T1.getCanonicalType().getUnqualifiedType();
9302 T2 = T2.getCanonicalType().getUnqualifiedType();
9304 const Type::TypeClass TC1 = T1->getTypeClass();
9305 const Type::TypeClass TC2 = T2->getTypeClass();
9310 if (TC1 == Type::Enum) {
9311 return isLayoutCompatible(C,
9312 cast<EnumType>(T1)->getDecl(),
9313 cast<EnumType>(T2)->getDecl());
9314 } else if (TC1 == Type::Record) {
9315 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9318 return isLayoutCompatible(C,
9319 cast<RecordType>(T1)->getDecl(),
9320 cast<RecordType>(T2)->getDecl());
9327 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9330 /// \brief Given a type tag expression find the type tag itself.
9332 /// \param TypeExpr Type tag expression, as it appears in user's code.
9334 /// \param VD Declaration of an identifier that appears in a type tag.
9336 /// \param MagicValue Type tag magic value.
9337 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9338 const ValueDecl **VD, uint64_t *MagicValue) {
9343 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9345 switch (TypeExpr->getStmtClass()) {
9346 case Stmt::UnaryOperatorClass: {
9347 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9348 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9349 TypeExpr = UO->getSubExpr();
9355 case Stmt::DeclRefExprClass: {
9356 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9357 *VD = DRE->getDecl();
9361 case Stmt::IntegerLiteralClass: {
9362 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9363 llvm::APInt MagicValueAPInt = IL->getValue();
9364 if (MagicValueAPInt.getActiveBits() <= 64) {
9365 *MagicValue = MagicValueAPInt.getZExtValue();
9371 case Stmt::BinaryConditionalOperatorClass:
9372 case Stmt::ConditionalOperatorClass: {
9373 const AbstractConditionalOperator *ACO =
9374 cast<AbstractConditionalOperator>(TypeExpr);
9376 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9378 TypeExpr = ACO->getTrueExpr();
9380 TypeExpr = ACO->getFalseExpr();
9386 case Stmt::BinaryOperatorClass: {
9387 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9388 if (BO->getOpcode() == BO_Comma) {
9389 TypeExpr = BO->getRHS();
9401 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
9403 /// \param TypeExpr Expression that specifies a type tag.
9405 /// \param MagicValues Registered magic values.
9407 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9410 /// \param TypeInfo Information about the corresponding C type.
9412 /// \returns true if the corresponding C type was found.
9413 bool GetMatchingCType(
9414 const IdentifierInfo *ArgumentKind,
9415 const Expr *TypeExpr, const ASTContext &Ctx,
9416 const llvm::DenseMap<Sema::TypeTagMagicValue,
9417 Sema::TypeTagData> *MagicValues,
9418 bool &FoundWrongKind,
9419 Sema::TypeTagData &TypeInfo) {
9420 FoundWrongKind = false;
9422 // Variable declaration that has type_tag_for_datatype attribute.
9423 const ValueDecl *VD = nullptr;
9425 uint64_t MagicValue;
9427 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9431 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
9432 if (I->getArgumentKind() != ArgumentKind) {
9433 FoundWrongKind = true;
9436 TypeInfo.Type = I->getMatchingCType();
9437 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9438 TypeInfo.MustBeNull = I->getMustBeNull();
9447 llvm::DenseMap<Sema::TypeTagMagicValue,
9448 Sema::TypeTagData>::const_iterator I =
9449 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9450 if (I == MagicValues->end())
9453 TypeInfo = I->second;
9456 } // unnamed namespace
9458 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9459 uint64_t MagicValue, QualType Type,
9460 bool LayoutCompatible,
9462 if (!TypeTagForDatatypeMagicValues)
9463 TypeTagForDatatypeMagicValues.reset(
9464 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9466 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9467 (*TypeTagForDatatypeMagicValues)[Magic] =
9468 TypeTagData(Type, LayoutCompatible, MustBeNull);
9472 bool IsSameCharType(QualType T1, QualType T2) {
9473 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9477 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9481 BuiltinType::Kind T1Kind = BT1->getKind();
9482 BuiltinType::Kind T2Kind = BT2->getKind();
9484 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9485 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9486 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9487 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9489 } // unnamed namespace
9491 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9492 const Expr * const *ExprArgs) {
9493 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9494 bool IsPointerAttr = Attr->getIsPointer();
9496 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9497 bool FoundWrongKind;
9498 TypeTagData TypeInfo;
9499 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9500 TypeTagForDatatypeMagicValues.get(),
9501 FoundWrongKind, TypeInfo)) {
9503 Diag(TypeTagExpr->getExprLoc(),
9504 diag::warn_type_tag_for_datatype_wrong_kind)
9505 << TypeTagExpr->getSourceRange();
9509 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9510 if (IsPointerAttr) {
9511 // Skip implicit cast of pointer to `void *' (as a function argument).
9512 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
9513 if (ICE->getType()->isVoidPointerType() &&
9514 ICE->getCastKind() == CK_BitCast)
9515 ArgumentExpr = ICE->getSubExpr();
9517 QualType ArgumentType = ArgumentExpr->getType();
9519 // Passing a `void*' pointer shouldn't trigger a warning.
9520 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9523 if (TypeInfo.MustBeNull) {
9524 // Type tag with matching void type requires a null pointer.
9525 if (!ArgumentExpr->isNullPointerConstant(Context,
9526 Expr::NPC_ValueDependentIsNotNull)) {
9527 Diag(ArgumentExpr->getExprLoc(),
9528 diag::warn_type_safety_null_pointer_required)
9529 << ArgumentKind->getName()
9530 << ArgumentExpr->getSourceRange()
9531 << TypeTagExpr->getSourceRange();
9536 QualType RequiredType = TypeInfo.Type;
9538 RequiredType = Context.getPointerType(RequiredType);
9540 bool mismatch = false;
9541 if (!TypeInfo.LayoutCompatible) {
9542 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9544 // C++11 [basic.fundamental] p1:
9545 // Plain char, signed char, and unsigned char are three distinct types.
9547 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9548 // char' depending on the current char signedness mode.
9550 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9551 RequiredType->getPointeeType())) ||
9552 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9556 mismatch = !isLayoutCompatible(Context,
9557 ArgumentType->getPointeeType(),
9558 RequiredType->getPointeeType());
9560 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9563 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
9564 << ArgumentType << ArgumentKind
9565 << TypeInfo.LayoutCompatible << RequiredType
9566 << ArgumentExpr->getSourceRange()
9567 << TypeTagExpr->getSourceRange();