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/AST/APValue.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/ExprOpenMP.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/OperationKinds.h"
32 #include "clang/AST/Stmt.h"
33 #include "clang/AST/TemplateBase.h"
34 #include "clang/AST/Type.h"
35 #include "clang/AST/TypeLoc.h"
36 #include "clang/AST/UnresolvedSet.h"
37 #include "clang/Analysis/Analyses/FormatString.h"
38 #include "clang/Basic/AddressSpaces.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/OpenCLOptions.h"
45 #include "clang/Basic/OperatorKinds.h"
46 #include "clang/Basic/PartialDiagnostic.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
51 #include "clang/Basic/TargetBuiltins.h"
52 #include "clang/Basic/TargetCXXABI.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56 #include "clang/Sema/Initialization.h"
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/SemaInternal.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/APSInt.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSwitch.h"
78 #include "llvm/ADT/Triple.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
98 using namespace clang;
101 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
102 unsigned ByteNo) const {
103 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104 Context.getTargetInfo());
107 /// Checks that a call expression's argument count is the desired number.
108 /// This is useful when doing custom type-checking. Returns true on error.
109 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110 unsigned argCount = call->getNumArgs();
111 if (argCount == desiredArgCount) return false;
113 if (argCount < desiredArgCount)
114 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
115 << 0 /*function call*/ << desiredArgCount << argCount
116 << call->getSourceRange();
118 // Highlight all the excess arguments.
119 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
120 call->getArg(argCount - 1)->getLocEnd());
122 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123 << 0 /*function call*/ << desiredArgCount << argCount
124 << call->getArg(1)->getSourceRange();
127 /// Check that the first argument to __builtin_annotation is an integer
128 /// and the second argument is a non-wide string literal.
129 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130 if (checkArgCount(S, TheCall, 2))
133 // First argument should be an integer.
134 Expr *ValArg = TheCall->getArg(0);
135 QualType Ty = ValArg->getType();
136 if (!Ty->isIntegerType()) {
137 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
138 << ValArg->getSourceRange();
142 // Second argument should be a constant string.
143 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145 if (!Literal || !Literal->isAscii()) {
146 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
147 << StrArg->getSourceRange();
151 TheCall->setType(Ty);
155 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156 // We need at least one argument.
157 if (TheCall->getNumArgs() < 1) {
158 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
159 << 0 << 1 << TheCall->getNumArgs()
160 << TheCall->getCallee()->getSourceRange();
164 // All arguments should be wide string literals.
165 for (Expr *Arg : TheCall->arguments()) {
166 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167 if (!Literal || !Literal->isWide()) {
168 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
169 << Arg->getSourceRange();
177 /// Check that the argument to __builtin_addressof is a glvalue, and set the
178 /// result type to the corresponding pointer type.
179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180 if (checkArgCount(S, TheCall, 1))
183 ExprResult Arg(TheCall->getArg(0));
184 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
185 if (ResultType.isNull())
188 TheCall->setArg(0, Arg.get());
189 TheCall->setType(ResultType);
193 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194 if (checkArgCount(S, TheCall, 3))
197 // First two arguments should be integers.
198 for (unsigned I = 0; I < 2; ++I) {
199 Expr *Arg = TheCall->getArg(I);
200 QualType Ty = Arg->getType();
201 if (!Ty->isIntegerType()) {
202 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
203 << Ty << Arg->getSourceRange();
208 // Third argument should be a pointer to a non-const integer.
209 // IRGen correctly handles volatile, restrict, and address spaces, and
210 // the other qualifiers aren't possible.
212 Expr *Arg = TheCall->getArg(2);
213 QualType Ty = Arg->getType();
214 const auto *PtrTy = Ty->getAs<PointerType>();
215 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
216 !PtrTy->getPointeeType().isConstQualified())) {
217 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
218 << Ty << Arg->getSourceRange();
226 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
227 CallExpr *TheCall, unsigned SizeIdx,
228 unsigned DstSizeIdx) {
229 if (TheCall->getNumArgs() <= SizeIdx ||
230 TheCall->getNumArgs() <= DstSizeIdx)
233 const Expr *SizeArg = TheCall->getArg(SizeIdx);
234 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
236 llvm::APSInt Size, DstSize;
238 // find out if both sizes are known at compile time
239 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
240 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
243 if (Size.ule(DstSize))
246 // confirmed overflow so generate the diagnostic.
247 IdentifierInfo *FnName = FDecl->getIdentifier();
248 SourceLocation SL = TheCall->getLocStart();
249 SourceRange SR = TheCall->getSourceRange();
251 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
254 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
255 if (checkArgCount(S, BuiltinCall, 2))
258 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
259 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
260 Expr *Call = BuiltinCall->getArg(0);
261 Expr *Chain = BuiltinCall->getArg(1);
263 if (Call->getStmtClass() != Stmt::CallExprClass) {
264 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
265 << Call->getSourceRange();
269 auto CE = cast<CallExpr>(Call);
270 if (CE->getCallee()->getType()->isBlockPointerType()) {
271 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
272 << Call->getSourceRange();
276 const Decl *TargetDecl = CE->getCalleeDecl();
277 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
278 if (FD->getBuiltinID()) {
279 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
280 << Call->getSourceRange();
284 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
285 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
286 << Call->getSourceRange();
290 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
291 if (ChainResult.isInvalid())
293 if (!ChainResult.get()->getType()->isPointerType()) {
294 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
295 << Chain->getSourceRange();
299 QualType ReturnTy = CE->getCallReturnType(S.Context);
300 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
301 QualType BuiltinTy = S.Context.getFunctionType(
302 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
303 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
306 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
308 BuiltinCall->setType(CE->getType());
309 BuiltinCall->setValueKind(CE->getValueKind());
310 BuiltinCall->setObjectKind(CE->getObjectKind());
311 BuiltinCall->setCallee(Builtin);
312 BuiltinCall->setArg(1, ChainResult.get());
317 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
318 Scope::ScopeFlags NeededScopeFlags,
320 // Scopes aren't available during instantiation. Fortunately, builtin
321 // functions cannot be template args so they cannot be formed through template
322 // instantiation. Therefore checking once during the parse is sufficient.
323 if (SemaRef.inTemplateInstantiation())
326 Scope *S = SemaRef.getCurScope();
327 while (S && !S->isSEHExceptScope())
329 if (!S || !(S->getFlags() & NeededScopeFlags)) {
330 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
331 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
332 << DRE->getDecl()->getIdentifier();
339 static inline bool isBlockPointer(Expr *Arg) {
340 return Arg->getType()->isBlockPointerType();
343 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
344 /// void*, which is a requirement of device side enqueue.
345 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
346 const BlockPointerType *BPT =
347 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
348 ArrayRef<QualType> Params =
349 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
350 unsigned ArgCounter = 0;
351 bool IllegalParams = false;
352 // Iterate through the block parameters until either one is found that is not
353 // a local void*, or the block is valid.
354 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
355 I != E; ++I, ++ArgCounter) {
356 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
357 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
358 LangAS::opencl_local) {
359 // Get the location of the error. If a block literal has been passed
360 // (BlockExpr) then we can point straight to the offending argument,
361 // else we just point to the variable reference.
362 SourceLocation ErrorLoc;
363 if (isa<BlockExpr>(BlockArg)) {
364 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
365 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
366 } else if (isa<DeclRefExpr>(BlockArg)) {
367 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
370 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
371 IllegalParams = true;
375 return IllegalParams;
378 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
379 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
380 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
381 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
387 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
388 if (checkArgCount(S, TheCall, 2))
391 if (checkOpenCLSubgroupExt(S, TheCall))
394 // First argument is an ndrange_t type.
395 Expr *NDRangeArg = TheCall->getArg(0);
396 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
397 S.Diag(NDRangeArg->getLocStart(),
398 diag::err_opencl_builtin_expected_type)
399 << TheCall->getDirectCallee() << "'ndrange_t'";
403 Expr *BlockArg = TheCall->getArg(1);
404 if (!isBlockPointer(BlockArg)) {
405 S.Diag(BlockArg->getLocStart(),
406 diag::err_opencl_builtin_expected_type)
407 << TheCall->getDirectCallee() << "block";
410 return checkOpenCLBlockArgs(S, BlockArg);
413 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
414 /// get_kernel_work_group_size
415 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
416 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
417 if (checkArgCount(S, TheCall, 1))
420 Expr *BlockArg = TheCall->getArg(0);
421 if (!isBlockPointer(BlockArg)) {
422 S.Diag(BlockArg->getLocStart(),
423 diag::err_opencl_builtin_expected_type)
424 << TheCall->getDirectCallee() << "block";
427 return checkOpenCLBlockArgs(S, BlockArg);
430 /// Diagnose integer type and any valid implicit conversion to it.
431 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
432 const QualType &IntType);
434 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
435 unsigned Start, unsigned End) {
436 bool IllegalParams = false;
437 for (unsigned I = Start; I <= End; ++I)
438 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
439 S.Context.getSizeType());
440 return IllegalParams;
443 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
444 /// 'local void*' parameter of passed block.
445 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
447 unsigned NumNonVarArgs) {
448 const BlockPointerType *BPT =
449 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
450 unsigned NumBlockParams =
451 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
452 unsigned TotalNumArgs = TheCall->getNumArgs();
454 // For each argument passed to the block, a corresponding uint needs to
455 // be passed to describe the size of the local memory.
456 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
457 S.Diag(TheCall->getLocStart(),
458 diag::err_opencl_enqueue_kernel_local_size_args);
462 // Check that the sizes of the local memory are specified by integers.
463 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
467 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
468 /// overload formats specified in Table 6.13.17.1.
469 /// int enqueue_kernel(queue_t queue,
470 /// kernel_enqueue_flags_t flags,
471 /// const ndrange_t ndrange,
472 /// void (^block)(void))
473 /// int enqueue_kernel(queue_t queue,
474 /// kernel_enqueue_flags_t flags,
475 /// const ndrange_t ndrange,
476 /// uint num_events_in_wait_list,
477 /// clk_event_t *event_wait_list,
478 /// clk_event_t *event_ret,
479 /// void (^block)(void))
480 /// int enqueue_kernel(queue_t queue,
481 /// kernel_enqueue_flags_t flags,
482 /// const ndrange_t ndrange,
483 /// void (^block)(local void*, ...),
485 /// int enqueue_kernel(queue_t queue,
486 /// kernel_enqueue_flags_t flags,
487 /// const ndrange_t ndrange,
488 /// uint num_events_in_wait_list,
489 /// clk_event_t *event_wait_list,
490 /// clk_event_t *event_ret,
491 /// void (^block)(local void*, ...),
493 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
494 unsigned NumArgs = TheCall->getNumArgs();
497 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
501 Expr *Arg0 = TheCall->getArg(0);
502 Expr *Arg1 = TheCall->getArg(1);
503 Expr *Arg2 = TheCall->getArg(2);
504 Expr *Arg3 = TheCall->getArg(3);
506 // First argument always needs to be a queue_t type.
507 if (!Arg0->getType()->isQueueT()) {
508 S.Diag(TheCall->getArg(0)->getLocStart(),
509 diag::err_opencl_builtin_expected_type)
510 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
514 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
515 if (!Arg1->getType()->isIntegerType()) {
516 S.Diag(TheCall->getArg(1)->getLocStart(),
517 diag::err_opencl_builtin_expected_type)
518 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
522 // Third argument is always an ndrange_t type.
523 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
524 S.Diag(TheCall->getArg(2)->getLocStart(),
525 diag::err_opencl_builtin_expected_type)
526 << TheCall->getDirectCallee() << "'ndrange_t'";
530 // With four arguments, there is only one form that the function could be
531 // called in: no events and no variable arguments.
533 // check that the last argument is the right block type.
534 if (!isBlockPointer(Arg3)) {
535 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
536 << TheCall->getDirectCallee() << "block";
539 // we have a block type, check the prototype
540 const BlockPointerType *BPT =
541 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
542 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
543 S.Diag(Arg3->getLocStart(),
544 diag::err_opencl_enqueue_kernel_blocks_no_args);
549 // we can have block + varargs.
550 if (isBlockPointer(Arg3))
551 return (checkOpenCLBlockArgs(S, Arg3) ||
552 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
553 // last two cases with either exactly 7 args or 7 args and varargs.
555 // check common block argument.
556 Expr *Arg6 = TheCall->getArg(6);
557 if (!isBlockPointer(Arg6)) {
558 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
559 << TheCall->getDirectCallee() << "block";
562 if (checkOpenCLBlockArgs(S, Arg6))
565 // Forth argument has to be any integer type.
566 if (!Arg3->getType()->isIntegerType()) {
567 S.Diag(TheCall->getArg(3)->getLocStart(),
568 diag::err_opencl_builtin_expected_type)
569 << TheCall->getDirectCallee() << "integer";
572 // check remaining common arguments.
573 Expr *Arg4 = TheCall->getArg(4);
574 Expr *Arg5 = TheCall->getArg(5);
576 // Fifth argument is always passed as a pointer to clk_event_t.
577 if (!Arg4->isNullPointerConstant(S.Context,
578 Expr::NPC_ValueDependentIsNotNull) &&
579 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
580 S.Diag(TheCall->getArg(4)->getLocStart(),
581 diag::err_opencl_builtin_expected_type)
582 << TheCall->getDirectCallee()
583 << S.Context.getPointerType(S.Context.OCLClkEventTy);
587 // Sixth argument is always passed as a pointer to clk_event_t.
588 if (!Arg5->isNullPointerConstant(S.Context,
589 Expr::NPC_ValueDependentIsNotNull) &&
590 !(Arg5->getType()->isPointerType() &&
591 Arg5->getType()->getPointeeType()->isClkEventT())) {
592 S.Diag(TheCall->getArg(5)->getLocStart(),
593 diag::err_opencl_builtin_expected_type)
594 << TheCall->getDirectCallee()
595 << S.Context.getPointerType(S.Context.OCLClkEventTy);
602 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
605 // None of the specific case has been detected, give generic error
606 S.Diag(TheCall->getLocStart(),
607 diag::err_opencl_enqueue_kernel_incorrect_args);
611 /// Returns OpenCL access qual.
612 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
613 return D->getAttr<OpenCLAccessAttr>();
616 /// Returns true if pipe element type is different from the pointer.
617 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
618 const Expr *Arg0 = Call->getArg(0);
619 // First argument type should always be pipe.
620 if (!Arg0->getType()->isPipeType()) {
621 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
622 << Call->getDirectCallee() << Arg0->getSourceRange();
625 OpenCLAccessAttr *AccessQual =
626 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
627 // Validates the access qualifier is compatible with the call.
628 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
629 // read_only and write_only, and assumed to be read_only if no qualifier is
631 switch (Call->getDirectCallee()->getBuiltinID()) {
632 case Builtin::BIread_pipe:
633 case Builtin::BIreserve_read_pipe:
634 case Builtin::BIcommit_read_pipe:
635 case Builtin::BIwork_group_reserve_read_pipe:
636 case Builtin::BIsub_group_reserve_read_pipe:
637 case Builtin::BIwork_group_commit_read_pipe:
638 case Builtin::BIsub_group_commit_read_pipe:
639 if (!(!AccessQual || AccessQual->isReadOnly())) {
640 S.Diag(Arg0->getLocStart(),
641 diag::err_opencl_builtin_pipe_invalid_access_modifier)
642 << "read_only" << Arg0->getSourceRange();
646 case Builtin::BIwrite_pipe:
647 case Builtin::BIreserve_write_pipe:
648 case Builtin::BIcommit_write_pipe:
649 case Builtin::BIwork_group_reserve_write_pipe:
650 case Builtin::BIsub_group_reserve_write_pipe:
651 case Builtin::BIwork_group_commit_write_pipe:
652 case Builtin::BIsub_group_commit_write_pipe:
653 if (!(AccessQual && AccessQual->isWriteOnly())) {
654 S.Diag(Arg0->getLocStart(),
655 diag::err_opencl_builtin_pipe_invalid_access_modifier)
656 << "write_only" << Arg0->getSourceRange();
666 /// Returns true if pipe element type is different from the pointer.
667 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
668 const Expr *Arg0 = Call->getArg(0);
669 const Expr *ArgIdx = Call->getArg(Idx);
670 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
671 const QualType EltTy = PipeTy->getElementType();
672 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
673 // The Idx argument should be a pointer and the type of the pointer and
674 // the type of pipe element should also be the same.
676 !S.Context.hasSameType(
677 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
678 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
679 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
680 << ArgIdx->getType() << ArgIdx->getSourceRange();
686 // \brief Performs semantic analysis for the read/write_pipe call.
687 // \param S Reference to the semantic analyzer.
688 // \param Call A pointer to the builtin call.
689 // \return True if a semantic error has been found, false otherwise.
690 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
691 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
692 // functions have two forms.
693 switch (Call->getNumArgs()) {
695 if (checkOpenCLPipeArg(S, Call))
697 // The call with 2 arguments should be
698 // read/write_pipe(pipe T, T*).
699 // Check packet type T.
700 if (checkOpenCLPipePacketType(S, Call, 1))
705 if (checkOpenCLPipeArg(S, Call))
707 // The call with 4 arguments should be
708 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
709 // Check reserve_id_t.
710 if (!Call->getArg(1)->getType()->isReserveIDT()) {
711 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
712 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
713 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
718 const Expr *Arg2 = Call->getArg(2);
719 if (!Arg2->getType()->isIntegerType() &&
720 !Arg2->getType()->isUnsignedIntegerType()) {
721 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
722 << Call->getDirectCallee() << S.Context.UnsignedIntTy
723 << Arg2->getType() << Arg2->getSourceRange();
727 // Check packet type T.
728 if (checkOpenCLPipePacketType(S, Call, 3))
732 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
733 << Call->getDirectCallee() << Call->getSourceRange();
740 // \brief Performs a semantic analysis on the {work_group_/sub_group_
741 // /_}reserve_{read/write}_pipe
742 // \param S Reference to the semantic analyzer.
743 // \param Call The call to the builtin function to be analyzed.
744 // \return True if a semantic error was found, false otherwise.
745 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
746 if (checkArgCount(S, Call, 2))
749 if (checkOpenCLPipeArg(S, Call))
752 // Check the reserve size.
753 if (!Call->getArg(1)->getType()->isIntegerType() &&
754 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
755 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
756 << Call->getDirectCallee() << S.Context.UnsignedIntTy
757 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
761 // Since return type of reserve_read/write_pipe built-in function is
762 // reserve_id_t, which is not defined in the builtin def file , we used int
763 // as return type and need to override the return type of these functions.
764 Call->setType(S.Context.OCLReserveIDTy);
769 // \brief Performs a semantic analysis on {work_group_/sub_group_
770 // /_}commit_{read/write}_pipe
771 // \param S Reference to the semantic analyzer.
772 // \param Call The call to the builtin function to be analyzed.
773 // \return True if a semantic error was found, false otherwise.
774 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
775 if (checkArgCount(S, Call, 2))
778 if (checkOpenCLPipeArg(S, Call))
781 // Check reserve_id_t.
782 if (!Call->getArg(1)->getType()->isReserveIDT()) {
783 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
784 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
785 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
792 // \brief Performs a semantic analysis on the call to built-in Pipe
794 // \param S Reference to the semantic analyzer.
795 // \param Call The call to the builtin function to be analyzed.
796 // \return True if a semantic error was found, false otherwise.
797 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
798 if (checkArgCount(S, Call, 1))
801 if (!Call->getArg(0)->getType()->isPipeType()) {
802 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
803 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
810 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
811 // \brief Performs semantic analysis for the to_global/local/private call.
812 // \param S Reference to the semantic analyzer.
813 // \param BuiltinID ID of the builtin function.
814 // \param Call A pointer to the builtin call.
815 // \return True if a semantic error has been found, false otherwise.
816 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
818 if (Call->getNumArgs() != 1) {
819 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
820 << Call->getDirectCallee() << Call->getSourceRange();
824 auto RT = Call->getArg(0)->getType();
825 if (!RT->isPointerType() || RT->getPointeeType()
826 .getAddressSpace() == LangAS::opencl_constant) {
827 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
828 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
832 RT = RT->getPointeeType();
833 auto Qual = RT.getQualifiers();
835 case Builtin::BIto_global:
836 Qual.setAddressSpace(LangAS::opencl_global);
838 case Builtin::BIto_local:
839 Qual.setAddressSpace(LangAS::opencl_local);
841 case Builtin::BIto_private:
842 Qual.setAddressSpace(LangAS::opencl_private);
845 llvm_unreachable("Invalid builtin function");
847 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
848 RT.getUnqualifiedType(), Qual)));
854 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
856 ExprResult TheCallResult(TheCall);
858 // Find out if any arguments are required to be integer constant expressions.
859 unsigned ICEArguments = 0;
860 ASTContext::GetBuiltinTypeError Error;
861 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
862 if (Error != ASTContext::GE_None)
863 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
865 // If any arguments are required to be ICE's, check and diagnose.
866 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
867 // Skip arguments not required to be ICE's.
868 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
871 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
873 ICEArguments &= ~(1 << ArgNo);
877 case Builtin::BI__builtin___CFStringMakeConstantString:
878 assert(TheCall->getNumArgs() == 1 &&
879 "Wrong # arguments to builtin CFStringMakeConstantString");
880 if (CheckObjCString(TheCall->getArg(0)))
883 case Builtin::BI__builtin_ms_va_start:
884 case Builtin::BI__builtin_stdarg_start:
885 case Builtin::BI__builtin_va_start:
886 if (SemaBuiltinVAStart(BuiltinID, TheCall))
889 case Builtin::BI__va_start: {
890 switch (Context.getTargetInfo().getTriple().getArch()) {
891 case llvm::Triple::arm:
892 case llvm::Triple::thumb:
893 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
897 if (SemaBuiltinVAStart(BuiltinID, TheCall))
903 case Builtin::BI__builtin_isgreater:
904 case Builtin::BI__builtin_isgreaterequal:
905 case Builtin::BI__builtin_isless:
906 case Builtin::BI__builtin_islessequal:
907 case Builtin::BI__builtin_islessgreater:
908 case Builtin::BI__builtin_isunordered:
909 if (SemaBuiltinUnorderedCompare(TheCall))
912 case Builtin::BI__builtin_fpclassify:
913 if (SemaBuiltinFPClassification(TheCall, 6))
916 case Builtin::BI__builtin_isfinite:
917 case Builtin::BI__builtin_isinf:
918 case Builtin::BI__builtin_isinf_sign:
919 case Builtin::BI__builtin_isnan:
920 case Builtin::BI__builtin_isnormal:
921 if (SemaBuiltinFPClassification(TheCall, 1))
924 case Builtin::BI__builtin_shufflevector:
925 return SemaBuiltinShuffleVector(TheCall);
926 // TheCall will be freed by the smart pointer here, but that's fine, since
927 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
928 case Builtin::BI__builtin_prefetch:
929 if (SemaBuiltinPrefetch(TheCall))
932 case Builtin::BI__builtin_alloca_with_align:
933 if (SemaBuiltinAllocaWithAlign(TheCall))
936 case Builtin::BI__assume:
937 case Builtin::BI__builtin_assume:
938 if (SemaBuiltinAssume(TheCall))
941 case Builtin::BI__builtin_assume_aligned:
942 if (SemaBuiltinAssumeAligned(TheCall))
945 case Builtin::BI__builtin_object_size:
946 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
949 case Builtin::BI__builtin_longjmp:
950 if (SemaBuiltinLongjmp(TheCall))
953 case Builtin::BI__builtin_setjmp:
954 if (SemaBuiltinSetjmp(TheCall))
957 case Builtin::BI_setjmp:
958 case Builtin::BI_setjmpex:
959 if (checkArgCount(*this, TheCall, 1))
962 case Builtin::BI__builtin_classify_type:
963 if (checkArgCount(*this, TheCall, 1)) return true;
964 TheCall->setType(Context.IntTy);
966 case Builtin::BI__builtin_constant_p:
967 if (checkArgCount(*this, TheCall, 1)) return true;
968 TheCall->setType(Context.IntTy);
970 case Builtin::BI__sync_fetch_and_add:
971 case Builtin::BI__sync_fetch_and_add_1:
972 case Builtin::BI__sync_fetch_and_add_2:
973 case Builtin::BI__sync_fetch_and_add_4:
974 case Builtin::BI__sync_fetch_and_add_8:
975 case Builtin::BI__sync_fetch_and_add_16:
976 case Builtin::BI__sync_fetch_and_sub:
977 case Builtin::BI__sync_fetch_and_sub_1:
978 case Builtin::BI__sync_fetch_and_sub_2:
979 case Builtin::BI__sync_fetch_and_sub_4:
980 case Builtin::BI__sync_fetch_and_sub_8:
981 case Builtin::BI__sync_fetch_and_sub_16:
982 case Builtin::BI__sync_fetch_and_or:
983 case Builtin::BI__sync_fetch_and_or_1:
984 case Builtin::BI__sync_fetch_and_or_2:
985 case Builtin::BI__sync_fetch_and_or_4:
986 case Builtin::BI__sync_fetch_and_or_8:
987 case Builtin::BI__sync_fetch_and_or_16:
988 case Builtin::BI__sync_fetch_and_and:
989 case Builtin::BI__sync_fetch_and_and_1:
990 case Builtin::BI__sync_fetch_and_and_2:
991 case Builtin::BI__sync_fetch_and_and_4:
992 case Builtin::BI__sync_fetch_and_and_8:
993 case Builtin::BI__sync_fetch_and_and_16:
994 case Builtin::BI__sync_fetch_and_xor:
995 case Builtin::BI__sync_fetch_and_xor_1:
996 case Builtin::BI__sync_fetch_and_xor_2:
997 case Builtin::BI__sync_fetch_and_xor_4:
998 case Builtin::BI__sync_fetch_and_xor_8:
999 case Builtin::BI__sync_fetch_and_xor_16:
1000 case Builtin::BI__sync_fetch_and_nand:
1001 case Builtin::BI__sync_fetch_and_nand_1:
1002 case Builtin::BI__sync_fetch_and_nand_2:
1003 case Builtin::BI__sync_fetch_and_nand_4:
1004 case Builtin::BI__sync_fetch_and_nand_8:
1005 case Builtin::BI__sync_fetch_and_nand_16:
1006 case Builtin::BI__sync_add_and_fetch:
1007 case Builtin::BI__sync_add_and_fetch_1:
1008 case Builtin::BI__sync_add_and_fetch_2:
1009 case Builtin::BI__sync_add_and_fetch_4:
1010 case Builtin::BI__sync_add_and_fetch_8:
1011 case Builtin::BI__sync_add_and_fetch_16:
1012 case Builtin::BI__sync_sub_and_fetch:
1013 case Builtin::BI__sync_sub_and_fetch_1:
1014 case Builtin::BI__sync_sub_and_fetch_2:
1015 case Builtin::BI__sync_sub_and_fetch_4:
1016 case Builtin::BI__sync_sub_and_fetch_8:
1017 case Builtin::BI__sync_sub_and_fetch_16:
1018 case Builtin::BI__sync_and_and_fetch:
1019 case Builtin::BI__sync_and_and_fetch_1:
1020 case Builtin::BI__sync_and_and_fetch_2:
1021 case Builtin::BI__sync_and_and_fetch_4:
1022 case Builtin::BI__sync_and_and_fetch_8:
1023 case Builtin::BI__sync_and_and_fetch_16:
1024 case Builtin::BI__sync_or_and_fetch:
1025 case Builtin::BI__sync_or_and_fetch_1:
1026 case Builtin::BI__sync_or_and_fetch_2:
1027 case Builtin::BI__sync_or_and_fetch_4:
1028 case Builtin::BI__sync_or_and_fetch_8:
1029 case Builtin::BI__sync_or_and_fetch_16:
1030 case Builtin::BI__sync_xor_and_fetch:
1031 case Builtin::BI__sync_xor_and_fetch_1:
1032 case Builtin::BI__sync_xor_and_fetch_2:
1033 case Builtin::BI__sync_xor_and_fetch_4:
1034 case Builtin::BI__sync_xor_and_fetch_8:
1035 case Builtin::BI__sync_xor_and_fetch_16:
1036 case Builtin::BI__sync_nand_and_fetch:
1037 case Builtin::BI__sync_nand_and_fetch_1:
1038 case Builtin::BI__sync_nand_and_fetch_2:
1039 case Builtin::BI__sync_nand_and_fetch_4:
1040 case Builtin::BI__sync_nand_and_fetch_8:
1041 case Builtin::BI__sync_nand_and_fetch_16:
1042 case Builtin::BI__sync_val_compare_and_swap:
1043 case Builtin::BI__sync_val_compare_and_swap_1:
1044 case Builtin::BI__sync_val_compare_and_swap_2:
1045 case Builtin::BI__sync_val_compare_and_swap_4:
1046 case Builtin::BI__sync_val_compare_and_swap_8:
1047 case Builtin::BI__sync_val_compare_and_swap_16:
1048 case Builtin::BI__sync_bool_compare_and_swap:
1049 case Builtin::BI__sync_bool_compare_and_swap_1:
1050 case Builtin::BI__sync_bool_compare_and_swap_2:
1051 case Builtin::BI__sync_bool_compare_and_swap_4:
1052 case Builtin::BI__sync_bool_compare_and_swap_8:
1053 case Builtin::BI__sync_bool_compare_and_swap_16:
1054 case Builtin::BI__sync_lock_test_and_set:
1055 case Builtin::BI__sync_lock_test_and_set_1:
1056 case Builtin::BI__sync_lock_test_and_set_2:
1057 case Builtin::BI__sync_lock_test_and_set_4:
1058 case Builtin::BI__sync_lock_test_and_set_8:
1059 case Builtin::BI__sync_lock_test_and_set_16:
1060 case Builtin::BI__sync_lock_release:
1061 case Builtin::BI__sync_lock_release_1:
1062 case Builtin::BI__sync_lock_release_2:
1063 case Builtin::BI__sync_lock_release_4:
1064 case Builtin::BI__sync_lock_release_8:
1065 case Builtin::BI__sync_lock_release_16:
1066 case Builtin::BI__sync_swap:
1067 case Builtin::BI__sync_swap_1:
1068 case Builtin::BI__sync_swap_2:
1069 case Builtin::BI__sync_swap_4:
1070 case Builtin::BI__sync_swap_8:
1071 case Builtin::BI__sync_swap_16:
1072 return SemaBuiltinAtomicOverloaded(TheCallResult);
1073 case Builtin::BI__builtin_nontemporal_load:
1074 case Builtin::BI__builtin_nontemporal_store:
1075 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1076 #define BUILTIN(ID, TYPE, ATTRS)
1077 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1078 case Builtin::BI##ID: \
1079 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1080 #include "clang/Basic/Builtins.def"
1081 case Builtin::BI__annotation:
1082 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1085 case Builtin::BI__builtin_annotation:
1086 if (SemaBuiltinAnnotation(*this, TheCall))
1089 case Builtin::BI__builtin_addressof:
1090 if (SemaBuiltinAddressof(*this, TheCall))
1093 case Builtin::BI__builtin_add_overflow:
1094 case Builtin::BI__builtin_sub_overflow:
1095 case Builtin::BI__builtin_mul_overflow:
1096 if (SemaBuiltinOverflow(*this, TheCall))
1099 case Builtin::BI__builtin_operator_new:
1100 case Builtin::BI__builtin_operator_delete:
1101 if (!getLangOpts().CPlusPlus) {
1102 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1103 << (BuiltinID == Builtin::BI__builtin_operator_new
1104 ? "__builtin_operator_new"
1105 : "__builtin_operator_delete")
1109 // CodeGen assumes it can find the global new and delete to call,
1110 // so ensure that they are declared.
1111 DeclareGlobalNewDelete();
1114 // check secure string manipulation functions where overflows
1115 // are detectable at compile time
1116 case Builtin::BI__builtin___memcpy_chk:
1117 case Builtin::BI__builtin___memmove_chk:
1118 case Builtin::BI__builtin___memset_chk:
1119 case Builtin::BI__builtin___strlcat_chk:
1120 case Builtin::BI__builtin___strlcpy_chk:
1121 case Builtin::BI__builtin___strncat_chk:
1122 case Builtin::BI__builtin___strncpy_chk:
1123 case Builtin::BI__builtin___stpncpy_chk:
1124 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1126 case Builtin::BI__builtin___memccpy_chk:
1127 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1129 case Builtin::BI__builtin___snprintf_chk:
1130 case Builtin::BI__builtin___vsnprintf_chk:
1131 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1133 case Builtin::BI__builtin_call_with_static_chain:
1134 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1137 case Builtin::BI__exception_code:
1138 case Builtin::BI_exception_code:
1139 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1140 diag::err_seh___except_block))
1143 case Builtin::BI__exception_info:
1144 case Builtin::BI_exception_info:
1145 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1146 diag::err_seh___except_filter))
1149 case Builtin::BI__GetExceptionInfo:
1150 if (checkArgCount(*this, TheCall, 1))
1153 if (CheckCXXThrowOperand(
1154 TheCall->getLocStart(),
1155 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1159 TheCall->setType(Context.VoidPtrTy);
1161 // OpenCL v2.0, s6.13.16 - Pipe functions
1162 case Builtin::BIread_pipe:
1163 case Builtin::BIwrite_pipe:
1164 // Since those two functions are declared with var args, we need a semantic
1165 // check for the argument.
1166 if (SemaBuiltinRWPipe(*this, TheCall))
1168 TheCall->setType(Context.IntTy);
1170 case Builtin::BIreserve_read_pipe:
1171 case Builtin::BIreserve_write_pipe:
1172 case Builtin::BIwork_group_reserve_read_pipe:
1173 case Builtin::BIwork_group_reserve_write_pipe:
1174 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1177 case Builtin::BIsub_group_reserve_read_pipe:
1178 case Builtin::BIsub_group_reserve_write_pipe:
1179 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1180 SemaBuiltinReserveRWPipe(*this, TheCall))
1183 case Builtin::BIcommit_read_pipe:
1184 case Builtin::BIcommit_write_pipe:
1185 case Builtin::BIwork_group_commit_read_pipe:
1186 case Builtin::BIwork_group_commit_write_pipe:
1187 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1190 case Builtin::BIsub_group_commit_read_pipe:
1191 case Builtin::BIsub_group_commit_write_pipe:
1192 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1193 SemaBuiltinCommitRWPipe(*this, TheCall))
1196 case Builtin::BIget_pipe_num_packets:
1197 case Builtin::BIget_pipe_max_packets:
1198 if (SemaBuiltinPipePackets(*this, TheCall))
1200 TheCall->setType(Context.UnsignedIntTy);
1202 case Builtin::BIto_global:
1203 case Builtin::BIto_local:
1204 case Builtin::BIto_private:
1205 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1208 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1209 case Builtin::BIenqueue_kernel:
1210 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1213 case Builtin::BIget_kernel_work_group_size:
1214 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1215 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1219 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1220 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1221 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1224 case Builtin::BI__builtin_os_log_format:
1225 case Builtin::BI__builtin_os_log_format_buffer_size:
1226 if (SemaBuiltinOSLogFormat(TheCall))
1231 // Since the target specific builtins for each arch overlap, only check those
1232 // of the arch we are compiling for.
1233 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1234 switch (Context.getTargetInfo().getTriple().getArch()) {
1235 case llvm::Triple::arm:
1236 case llvm::Triple::armeb:
1237 case llvm::Triple::thumb:
1238 case llvm::Triple::thumbeb:
1239 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1242 case llvm::Triple::aarch64:
1243 case llvm::Triple::aarch64_be:
1244 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1247 case llvm::Triple::mips:
1248 case llvm::Triple::mipsel:
1249 case llvm::Triple::mips64:
1250 case llvm::Triple::mips64el:
1251 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1254 case llvm::Triple::systemz:
1255 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1258 case llvm::Triple::x86:
1259 case llvm::Triple::x86_64:
1260 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1263 case llvm::Triple::ppc:
1264 case llvm::Triple::ppc64:
1265 case llvm::Triple::ppc64le:
1266 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1274 return TheCallResult;
1277 // Get the valid immediate range for the specified NEON type code.
1278 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1279 NeonTypeFlags Type(t);
1280 int IsQuad = ForceQuad ? true : Type.isQuad();
1281 switch (Type.getEltType()) {
1282 case NeonTypeFlags::Int8:
1283 case NeonTypeFlags::Poly8:
1284 return shift ? 7 : (8 << IsQuad) - 1;
1285 case NeonTypeFlags::Int16:
1286 case NeonTypeFlags::Poly16:
1287 return shift ? 15 : (4 << IsQuad) - 1;
1288 case NeonTypeFlags::Int32:
1289 return shift ? 31 : (2 << IsQuad) - 1;
1290 case NeonTypeFlags::Int64:
1291 case NeonTypeFlags::Poly64:
1292 return shift ? 63 : (1 << IsQuad) - 1;
1293 case NeonTypeFlags::Poly128:
1294 return shift ? 127 : (1 << IsQuad) - 1;
1295 case NeonTypeFlags::Float16:
1296 assert(!shift && "cannot shift float types!");
1297 return (4 << IsQuad) - 1;
1298 case NeonTypeFlags::Float32:
1299 assert(!shift && "cannot shift float types!");
1300 return (2 << IsQuad) - 1;
1301 case NeonTypeFlags::Float64:
1302 assert(!shift && "cannot shift float types!");
1303 return (1 << IsQuad) - 1;
1305 llvm_unreachable("Invalid NeonTypeFlag!");
1308 /// getNeonEltType - Return the QualType corresponding to the elements of
1309 /// the vector type specified by the NeonTypeFlags. This is used to check
1310 /// the pointer arguments for Neon load/store intrinsics.
1311 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1312 bool IsPolyUnsigned, bool IsInt64Long) {
1313 switch (Flags.getEltType()) {
1314 case NeonTypeFlags::Int8:
1315 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1316 case NeonTypeFlags::Int16:
1317 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1318 case NeonTypeFlags::Int32:
1319 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1320 case NeonTypeFlags::Int64:
1322 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1324 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1325 : Context.LongLongTy;
1326 case NeonTypeFlags::Poly8:
1327 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1328 case NeonTypeFlags::Poly16:
1329 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1330 case NeonTypeFlags::Poly64:
1332 return Context.UnsignedLongTy;
1334 return Context.UnsignedLongLongTy;
1335 case NeonTypeFlags::Poly128:
1337 case NeonTypeFlags::Float16:
1338 return Context.HalfTy;
1339 case NeonTypeFlags::Float32:
1340 return Context.FloatTy;
1341 case NeonTypeFlags::Float64:
1342 return Context.DoubleTy;
1344 llvm_unreachable("Invalid NeonTypeFlag!");
1347 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1348 llvm::APSInt Result;
1352 bool HasConstPtr = false;
1353 switch (BuiltinID) {
1354 #define GET_NEON_OVERLOAD_CHECK
1355 #include "clang/Basic/arm_neon.inc"
1356 #undef GET_NEON_OVERLOAD_CHECK
1359 // For NEON intrinsics which are overloaded on vector element type, validate
1360 // the immediate which specifies which variant to emit.
1361 unsigned ImmArg = TheCall->getNumArgs()-1;
1363 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1366 TV = Result.getLimitedValue(64);
1367 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1368 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1369 << TheCall->getArg(ImmArg)->getSourceRange();
1372 if (PtrArgNum >= 0) {
1373 // Check that pointer arguments have the specified type.
1374 Expr *Arg = TheCall->getArg(PtrArgNum);
1375 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1376 Arg = ICE->getSubExpr();
1377 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1378 QualType RHSTy = RHS.get()->getType();
1380 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1381 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1382 Arch == llvm::Triple::aarch64_be;
1384 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1386 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1388 EltTy = EltTy.withConst();
1389 QualType LHSTy = Context.getPointerType(EltTy);
1390 AssignConvertType ConvTy;
1391 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1392 if (RHS.isInvalid())
1394 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1395 RHS.get(), AA_Assigning))
1399 // For NEON intrinsics which take an immediate value as part of the
1400 // instruction, range check them here.
1401 unsigned i = 0, l = 0, u = 0;
1402 switch (BuiltinID) {
1405 #define GET_NEON_IMMEDIATE_CHECK
1406 #include "clang/Basic/arm_neon.inc"
1407 #undef GET_NEON_IMMEDIATE_CHECK
1410 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1413 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1414 unsigned MaxWidth) {
1415 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1416 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1417 BuiltinID == ARM::BI__builtin_arm_strex ||
1418 BuiltinID == ARM::BI__builtin_arm_stlex ||
1419 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1420 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1421 BuiltinID == AArch64::BI__builtin_arm_strex ||
1422 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1423 "unexpected ARM builtin");
1424 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1425 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1426 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1427 BuiltinID == AArch64::BI__builtin_arm_ldaex;
1429 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1431 // Ensure that we have the proper number of arguments.
1432 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1435 // Inspect the pointer argument of the atomic builtin. This should always be
1436 // a pointer type, whose element is an integral scalar or pointer type.
1437 // Because it is a pointer type, we don't have to worry about any implicit
1439 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1440 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1441 if (PointerArgRes.isInvalid())
1443 PointerArg = PointerArgRes.get();
1445 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1447 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1448 << PointerArg->getType() << PointerArg->getSourceRange();
1452 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1453 // task is to insert the appropriate casts into the AST. First work out just
1454 // what the appropriate type is.
1455 QualType ValType = pointerType->getPointeeType();
1456 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1458 AddrType.addConst();
1460 // Issue a warning if the cast is dodgy.
1461 CastKind CastNeeded = CK_NoOp;
1462 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1463 CastNeeded = CK_BitCast;
1464 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1465 << PointerArg->getType()
1466 << Context.getPointerType(AddrType)
1467 << AA_Passing << PointerArg->getSourceRange();
1470 // Finally, do the cast and replace the argument with the corrected version.
1471 AddrType = Context.getPointerType(AddrType);
1472 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1473 if (PointerArgRes.isInvalid())
1475 PointerArg = PointerArgRes.get();
1477 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1479 // In general, we allow ints, floats and pointers to be loaded and stored.
1480 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1481 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1482 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1483 << PointerArg->getType() << PointerArg->getSourceRange();
1487 // But ARM doesn't have instructions to deal with 128-bit versions.
1488 if (Context.getTypeSize(ValType) > MaxWidth) {
1489 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1490 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1491 << PointerArg->getType() << PointerArg->getSourceRange();
1495 switch (ValType.getObjCLifetime()) {
1496 case Qualifiers::OCL_None:
1497 case Qualifiers::OCL_ExplicitNone:
1501 case Qualifiers::OCL_Weak:
1502 case Qualifiers::OCL_Strong:
1503 case Qualifiers::OCL_Autoreleasing:
1504 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1505 << ValType << PointerArg->getSourceRange();
1510 TheCall->setType(ValType);
1514 // Initialize the argument to be stored.
1515 ExprResult ValArg = TheCall->getArg(0);
1516 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1517 Context, ValType, /*consume*/ false);
1518 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1519 if (ValArg.isInvalid())
1521 TheCall->setArg(0, ValArg.get());
1523 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1524 // but the custom checker bypasses all default analysis.
1525 TheCall->setType(Context.IntTy);
1529 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1530 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1531 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1532 BuiltinID == ARM::BI__builtin_arm_strex ||
1533 BuiltinID == ARM::BI__builtin_arm_stlex) {
1534 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1537 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1538 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1539 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1542 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1543 BuiltinID == ARM::BI__builtin_arm_wsr64)
1544 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1546 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1547 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1548 BuiltinID == ARM::BI__builtin_arm_wsr ||
1549 BuiltinID == ARM::BI__builtin_arm_wsrp)
1550 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1552 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1555 // For intrinsics which take an immediate value as part of the instruction,
1556 // range check them here.
1557 // FIXME: VFP Intrinsics should error if VFP not present.
1558 switch (BuiltinID) {
1559 default: return false;
1560 case ARM::BI__builtin_arm_ssat:
1561 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1562 case ARM::BI__builtin_arm_usat:
1563 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1564 case ARM::BI__builtin_arm_ssat16:
1565 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1566 case ARM::BI__builtin_arm_usat16:
1567 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1568 case ARM::BI__builtin_arm_vcvtr_f:
1569 case ARM::BI__builtin_arm_vcvtr_d:
1570 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1571 case ARM::BI__builtin_arm_dmb:
1572 case ARM::BI__builtin_arm_dsb:
1573 case ARM::BI__builtin_arm_isb:
1574 case ARM::BI__builtin_arm_dbg:
1575 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1579 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1580 CallExpr *TheCall) {
1581 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1582 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1583 BuiltinID == AArch64::BI__builtin_arm_strex ||
1584 BuiltinID == AArch64::BI__builtin_arm_stlex) {
1585 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1588 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1589 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1590 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1591 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1592 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1595 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1596 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1597 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1599 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1600 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1601 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1602 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1603 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1605 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1608 // For intrinsics which take an immediate value as part of the instruction,
1609 // range check them here.
1610 unsigned i = 0, l = 0, u = 0;
1611 switch (BuiltinID) {
1612 default: return false;
1613 case AArch64::BI__builtin_arm_dmb:
1614 case AArch64::BI__builtin_arm_dsb:
1615 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1618 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1621 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1622 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1623 // ordering for DSP is unspecified. MSA is ordered by the data format used
1624 // by the underlying instruction i.e., df/m, df/n and then by size.
1626 // FIXME: The size tests here should instead be tablegen'd along with the
1627 // definitions from include/clang/Basic/BuiltinsMips.def.
1628 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1630 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1631 unsigned i = 0, l = 0, u = 0, m = 0;
1632 switch (BuiltinID) {
1633 default: return false;
1634 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1635 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1636 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1637 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1638 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1639 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1640 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1641 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1643 // These intrinsics take an unsigned 3 bit immediate.
1644 case Mips::BI__builtin_msa_bclri_b:
1645 case Mips::BI__builtin_msa_bnegi_b:
1646 case Mips::BI__builtin_msa_bseti_b:
1647 case Mips::BI__builtin_msa_sat_s_b:
1648 case Mips::BI__builtin_msa_sat_u_b:
1649 case Mips::BI__builtin_msa_slli_b:
1650 case Mips::BI__builtin_msa_srai_b:
1651 case Mips::BI__builtin_msa_srari_b:
1652 case Mips::BI__builtin_msa_srli_b:
1653 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1654 case Mips::BI__builtin_msa_binsli_b:
1655 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1656 // These intrinsics take an unsigned 4 bit immediate.
1657 case Mips::BI__builtin_msa_bclri_h:
1658 case Mips::BI__builtin_msa_bnegi_h:
1659 case Mips::BI__builtin_msa_bseti_h:
1660 case Mips::BI__builtin_msa_sat_s_h:
1661 case Mips::BI__builtin_msa_sat_u_h:
1662 case Mips::BI__builtin_msa_slli_h:
1663 case Mips::BI__builtin_msa_srai_h:
1664 case Mips::BI__builtin_msa_srari_h:
1665 case Mips::BI__builtin_msa_srli_h:
1666 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1667 case Mips::BI__builtin_msa_binsli_h:
1668 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1669 // These intrinsics take an unsigned 5 bit immedate.
1670 // The first block of intrinsics actually have an unsigned 5 bit field,
1671 // not a df/n field.
1672 case Mips::BI__builtin_msa_clei_u_b:
1673 case Mips::BI__builtin_msa_clei_u_h:
1674 case Mips::BI__builtin_msa_clei_u_w:
1675 case Mips::BI__builtin_msa_clei_u_d:
1676 case Mips::BI__builtin_msa_clti_u_b:
1677 case Mips::BI__builtin_msa_clti_u_h:
1678 case Mips::BI__builtin_msa_clti_u_w:
1679 case Mips::BI__builtin_msa_clti_u_d:
1680 case Mips::BI__builtin_msa_maxi_u_b:
1681 case Mips::BI__builtin_msa_maxi_u_h:
1682 case Mips::BI__builtin_msa_maxi_u_w:
1683 case Mips::BI__builtin_msa_maxi_u_d:
1684 case Mips::BI__builtin_msa_mini_u_b:
1685 case Mips::BI__builtin_msa_mini_u_h:
1686 case Mips::BI__builtin_msa_mini_u_w:
1687 case Mips::BI__builtin_msa_mini_u_d:
1688 case Mips::BI__builtin_msa_addvi_b:
1689 case Mips::BI__builtin_msa_addvi_h:
1690 case Mips::BI__builtin_msa_addvi_w:
1691 case Mips::BI__builtin_msa_addvi_d:
1692 case Mips::BI__builtin_msa_bclri_w:
1693 case Mips::BI__builtin_msa_bnegi_w:
1694 case Mips::BI__builtin_msa_bseti_w:
1695 case Mips::BI__builtin_msa_sat_s_w:
1696 case Mips::BI__builtin_msa_sat_u_w:
1697 case Mips::BI__builtin_msa_slli_w:
1698 case Mips::BI__builtin_msa_srai_w:
1699 case Mips::BI__builtin_msa_srari_w:
1700 case Mips::BI__builtin_msa_srli_w:
1701 case Mips::BI__builtin_msa_srlri_w:
1702 case Mips::BI__builtin_msa_subvi_b:
1703 case Mips::BI__builtin_msa_subvi_h:
1704 case Mips::BI__builtin_msa_subvi_w:
1705 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1706 case Mips::BI__builtin_msa_binsli_w:
1707 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1708 // These intrinsics take an unsigned 6 bit immediate.
1709 case Mips::BI__builtin_msa_bclri_d:
1710 case Mips::BI__builtin_msa_bnegi_d:
1711 case Mips::BI__builtin_msa_bseti_d:
1712 case Mips::BI__builtin_msa_sat_s_d:
1713 case Mips::BI__builtin_msa_sat_u_d:
1714 case Mips::BI__builtin_msa_slli_d:
1715 case Mips::BI__builtin_msa_srai_d:
1716 case Mips::BI__builtin_msa_srari_d:
1717 case Mips::BI__builtin_msa_srli_d:
1718 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1719 case Mips::BI__builtin_msa_binsli_d:
1720 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1721 // These intrinsics take a signed 5 bit immediate.
1722 case Mips::BI__builtin_msa_ceqi_b:
1723 case Mips::BI__builtin_msa_ceqi_h:
1724 case Mips::BI__builtin_msa_ceqi_w:
1725 case Mips::BI__builtin_msa_ceqi_d:
1726 case Mips::BI__builtin_msa_clti_s_b:
1727 case Mips::BI__builtin_msa_clti_s_h:
1728 case Mips::BI__builtin_msa_clti_s_w:
1729 case Mips::BI__builtin_msa_clti_s_d:
1730 case Mips::BI__builtin_msa_clei_s_b:
1731 case Mips::BI__builtin_msa_clei_s_h:
1732 case Mips::BI__builtin_msa_clei_s_w:
1733 case Mips::BI__builtin_msa_clei_s_d:
1734 case Mips::BI__builtin_msa_maxi_s_b:
1735 case Mips::BI__builtin_msa_maxi_s_h:
1736 case Mips::BI__builtin_msa_maxi_s_w:
1737 case Mips::BI__builtin_msa_maxi_s_d:
1738 case Mips::BI__builtin_msa_mini_s_b:
1739 case Mips::BI__builtin_msa_mini_s_h:
1740 case Mips::BI__builtin_msa_mini_s_w:
1741 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1742 // These intrinsics take an unsigned 8 bit immediate.
1743 case Mips::BI__builtin_msa_andi_b:
1744 case Mips::BI__builtin_msa_nori_b:
1745 case Mips::BI__builtin_msa_ori_b:
1746 case Mips::BI__builtin_msa_shf_b:
1747 case Mips::BI__builtin_msa_shf_h:
1748 case Mips::BI__builtin_msa_shf_w:
1749 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1750 case Mips::BI__builtin_msa_bseli_b:
1751 case Mips::BI__builtin_msa_bmnzi_b:
1752 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1754 // These intrinsics take an unsigned 4 bit immediate.
1755 case Mips::BI__builtin_msa_copy_s_b:
1756 case Mips::BI__builtin_msa_copy_u_b:
1757 case Mips::BI__builtin_msa_insve_b:
1758 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1759 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1760 // These intrinsics take an unsigned 3 bit immediate.
1761 case Mips::BI__builtin_msa_copy_s_h:
1762 case Mips::BI__builtin_msa_copy_u_h:
1763 case Mips::BI__builtin_msa_insve_h:
1764 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1765 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1766 // These intrinsics take an unsigned 2 bit immediate.
1767 case Mips::BI__builtin_msa_copy_s_w:
1768 case Mips::BI__builtin_msa_copy_u_w:
1769 case Mips::BI__builtin_msa_insve_w:
1770 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1771 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1772 // These intrinsics take an unsigned 1 bit immediate.
1773 case Mips::BI__builtin_msa_copy_s_d:
1774 case Mips::BI__builtin_msa_copy_u_d:
1775 case Mips::BI__builtin_msa_insve_d:
1776 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1777 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1778 // Memory offsets and immediate loads.
1779 // These intrinsics take a signed 10 bit immediate.
1780 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1781 case Mips::BI__builtin_msa_ldi_h:
1782 case Mips::BI__builtin_msa_ldi_w:
1783 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1784 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1785 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1786 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1787 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1788 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1789 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1790 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1791 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1795 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1797 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1798 SemaBuiltinConstantArgMultiple(TheCall, i, m);
1801 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1802 unsigned i = 0, l = 0, u = 0;
1803 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1804 BuiltinID == PPC::BI__builtin_divdeu ||
1805 BuiltinID == PPC::BI__builtin_bpermd;
1806 bool IsTarget64Bit = Context.getTargetInfo()
1807 .getTypeWidth(Context
1809 .getIntPtrType()) == 64;
1810 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1811 BuiltinID == PPC::BI__builtin_divweu ||
1812 BuiltinID == PPC::BI__builtin_divde ||
1813 BuiltinID == PPC::BI__builtin_divdeu;
1815 if (Is64BitBltin && !IsTarget64Bit)
1816 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1817 << TheCall->getSourceRange();
1819 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1820 (BuiltinID == PPC::BI__builtin_bpermd &&
1821 !Context.getTargetInfo().hasFeature("bpermd")))
1822 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1823 << TheCall->getSourceRange();
1825 switch (BuiltinID) {
1826 default: return false;
1827 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1828 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1829 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1830 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1831 case PPC::BI__builtin_tbegin:
1832 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1833 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1834 case PPC::BI__builtin_tabortwc:
1835 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1836 case PPC::BI__builtin_tabortwci:
1837 case PPC::BI__builtin_tabortdci:
1838 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1839 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1840 case PPC::BI__builtin_vsx_xxpermdi:
1841 case PPC::BI__builtin_vsx_xxsldwi:
1842 return SemaBuiltinVSX(TheCall);
1844 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1847 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1848 CallExpr *TheCall) {
1849 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1850 Expr *Arg = TheCall->getArg(0);
1851 llvm::APSInt AbortCode(32);
1852 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1853 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1854 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1855 << Arg->getSourceRange();
1858 // For intrinsics which take an immediate value as part of the instruction,
1859 // range check them here.
1860 unsigned i = 0, l = 0, u = 0;
1861 switch (BuiltinID) {
1862 default: return false;
1863 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1864 case SystemZ::BI__builtin_s390_verimb:
1865 case SystemZ::BI__builtin_s390_verimh:
1866 case SystemZ::BI__builtin_s390_verimf:
1867 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1868 case SystemZ::BI__builtin_s390_vfaeb:
1869 case SystemZ::BI__builtin_s390_vfaeh:
1870 case SystemZ::BI__builtin_s390_vfaef:
1871 case SystemZ::BI__builtin_s390_vfaebs:
1872 case SystemZ::BI__builtin_s390_vfaehs:
1873 case SystemZ::BI__builtin_s390_vfaefs:
1874 case SystemZ::BI__builtin_s390_vfaezb:
1875 case SystemZ::BI__builtin_s390_vfaezh:
1876 case SystemZ::BI__builtin_s390_vfaezf:
1877 case SystemZ::BI__builtin_s390_vfaezbs:
1878 case SystemZ::BI__builtin_s390_vfaezhs:
1879 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1880 case SystemZ::BI__builtin_s390_vfisb:
1881 case SystemZ::BI__builtin_s390_vfidb:
1882 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1883 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1884 case SystemZ::BI__builtin_s390_vftcisb:
1885 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1886 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1887 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1888 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1889 case SystemZ::BI__builtin_s390_vstrcb:
1890 case SystemZ::BI__builtin_s390_vstrch:
1891 case SystemZ::BI__builtin_s390_vstrcf:
1892 case SystemZ::BI__builtin_s390_vstrczb:
1893 case SystemZ::BI__builtin_s390_vstrczh:
1894 case SystemZ::BI__builtin_s390_vstrczf:
1895 case SystemZ::BI__builtin_s390_vstrcbs:
1896 case SystemZ::BI__builtin_s390_vstrchs:
1897 case SystemZ::BI__builtin_s390_vstrcfs:
1898 case SystemZ::BI__builtin_s390_vstrczbs:
1899 case SystemZ::BI__builtin_s390_vstrczhs:
1900 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1901 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1902 case SystemZ::BI__builtin_s390_vfminsb:
1903 case SystemZ::BI__builtin_s390_vfmaxsb:
1904 case SystemZ::BI__builtin_s390_vfmindb:
1905 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1907 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1910 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1911 /// This checks that the target supports __builtin_cpu_supports and
1912 /// that the string argument is constant and valid.
1913 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1914 Expr *Arg = TheCall->getArg(0);
1916 // Check if the argument is a string literal.
1917 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1918 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1919 << Arg->getSourceRange();
1921 // Check the contents of the string.
1923 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1924 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1925 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1926 << Arg->getSourceRange();
1930 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1931 /// This checks that the target supports __builtin_cpu_is and
1932 /// that the string argument is constant and valid.
1933 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1934 Expr *Arg = TheCall->getArg(0);
1936 // Check if the argument is a string literal.
1937 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1938 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1939 << Arg->getSourceRange();
1941 // Check the contents of the string.
1943 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1944 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1945 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1946 << Arg->getSourceRange();
1950 // Check if the rounding mode is legal.
1951 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1952 // Indicates if this instruction has rounding control or just SAE.
1955 unsigned ArgNum = 0;
1956 switch (BuiltinID) {
1959 case X86::BI__builtin_ia32_vcvttsd2si32:
1960 case X86::BI__builtin_ia32_vcvttsd2si64:
1961 case X86::BI__builtin_ia32_vcvttsd2usi32:
1962 case X86::BI__builtin_ia32_vcvttsd2usi64:
1963 case X86::BI__builtin_ia32_vcvttss2si32:
1964 case X86::BI__builtin_ia32_vcvttss2si64:
1965 case X86::BI__builtin_ia32_vcvttss2usi32:
1966 case X86::BI__builtin_ia32_vcvttss2usi64:
1969 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1970 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1971 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1972 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1973 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1974 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1975 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1976 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1977 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1978 case X86::BI__builtin_ia32_exp2pd_mask:
1979 case X86::BI__builtin_ia32_exp2ps_mask:
1980 case X86::BI__builtin_ia32_getexppd512_mask:
1981 case X86::BI__builtin_ia32_getexpps512_mask:
1982 case X86::BI__builtin_ia32_rcp28pd_mask:
1983 case X86::BI__builtin_ia32_rcp28ps_mask:
1984 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1985 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1986 case X86::BI__builtin_ia32_vcomisd:
1987 case X86::BI__builtin_ia32_vcomiss:
1988 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1991 case X86::BI__builtin_ia32_cmppd512_mask:
1992 case X86::BI__builtin_ia32_cmpps512_mask:
1993 case X86::BI__builtin_ia32_cmpsd_mask:
1994 case X86::BI__builtin_ia32_cmpss_mask:
1995 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1996 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1997 case X86::BI__builtin_ia32_getexpss128_round_mask:
1998 case X86::BI__builtin_ia32_maxpd512_mask:
1999 case X86::BI__builtin_ia32_maxps512_mask:
2000 case X86::BI__builtin_ia32_maxsd_round_mask:
2001 case X86::BI__builtin_ia32_maxss_round_mask:
2002 case X86::BI__builtin_ia32_minpd512_mask:
2003 case X86::BI__builtin_ia32_minps512_mask:
2004 case X86::BI__builtin_ia32_minsd_round_mask:
2005 case X86::BI__builtin_ia32_minss_round_mask:
2006 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2007 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2008 case X86::BI__builtin_ia32_reducepd512_mask:
2009 case X86::BI__builtin_ia32_reduceps512_mask:
2010 case X86::BI__builtin_ia32_rndscalepd_mask:
2011 case X86::BI__builtin_ia32_rndscaleps_mask:
2012 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2013 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2016 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2017 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2018 case X86::BI__builtin_ia32_fixupimmps512_mask:
2019 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2020 case X86::BI__builtin_ia32_fixupimmsd_mask:
2021 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2022 case X86::BI__builtin_ia32_fixupimmss_mask:
2023 case X86::BI__builtin_ia32_fixupimmss_maskz:
2024 case X86::BI__builtin_ia32_rangepd512_mask:
2025 case X86::BI__builtin_ia32_rangeps512_mask:
2026 case X86::BI__builtin_ia32_rangesd128_round_mask:
2027 case X86::BI__builtin_ia32_rangess128_round_mask:
2028 case X86::BI__builtin_ia32_reducesd_mask:
2029 case X86::BI__builtin_ia32_reducess_mask:
2030 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2031 case X86::BI__builtin_ia32_rndscaless_round_mask:
2034 case X86::BI__builtin_ia32_vcvtsd2si64:
2035 case X86::BI__builtin_ia32_vcvtsd2si32:
2036 case X86::BI__builtin_ia32_vcvtsd2usi32:
2037 case X86::BI__builtin_ia32_vcvtsd2usi64:
2038 case X86::BI__builtin_ia32_vcvtss2si32:
2039 case X86::BI__builtin_ia32_vcvtss2si64:
2040 case X86::BI__builtin_ia32_vcvtss2usi32:
2041 case X86::BI__builtin_ia32_vcvtss2usi64:
2045 case X86::BI__builtin_ia32_cvtsi2sd64:
2046 case X86::BI__builtin_ia32_cvtsi2ss32:
2047 case X86::BI__builtin_ia32_cvtsi2ss64:
2048 case X86::BI__builtin_ia32_cvtusi2sd64:
2049 case X86::BI__builtin_ia32_cvtusi2ss32:
2050 case X86::BI__builtin_ia32_cvtusi2ss64:
2054 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2055 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2056 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2057 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2058 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2059 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2060 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2061 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2062 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2063 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2064 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2065 case X86::BI__builtin_ia32_sqrtpd512_mask:
2066 case X86::BI__builtin_ia32_sqrtps512_mask:
2070 case X86::BI__builtin_ia32_addpd512_mask:
2071 case X86::BI__builtin_ia32_addps512_mask:
2072 case X86::BI__builtin_ia32_divpd512_mask:
2073 case X86::BI__builtin_ia32_divps512_mask:
2074 case X86::BI__builtin_ia32_mulpd512_mask:
2075 case X86::BI__builtin_ia32_mulps512_mask:
2076 case X86::BI__builtin_ia32_subpd512_mask:
2077 case X86::BI__builtin_ia32_subps512_mask:
2078 case X86::BI__builtin_ia32_addss_round_mask:
2079 case X86::BI__builtin_ia32_addsd_round_mask:
2080 case X86::BI__builtin_ia32_divss_round_mask:
2081 case X86::BI__builtin_ia32_divsd_round_mask:
2082 case X86::BI__builtin_ia32_mulss_round_mask:
2083 case X86::BI__builtin_ia32_mulsd_round_mask:
2084 case X86::BI__builtin_ia32_subss_round_mask:
2085 case X86::BI__builtin_ia32_subsd_round_mask:
2086 case X86::BI__builtin_ia32_scalefpd512_mask:
2087 case X86::BI__builtin_ia32_scalefps512_mask:
2088 case X86::BI__builtin_ia32_scalefsd_round_mask:
2089 case X86::BI__builtin_ia32_scalefss_round_mask:
2090 case X86::BI__builtin_ia32_getmantpd512_mask:
2091 case X86::BI__builtin_ia32_getmantps512_mask:
2092 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2093 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2094 case X86::BI__builtin_ia32_sqrtss_round_mask:
2095 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2096 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2097 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2098 case X86::BI__builtin_ia32_vfmaddps512_mask:
2099 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2100 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2101 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2102 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2103 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2104 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2105 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2106 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2107 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2108 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2109 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2110 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2111 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2112 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2113 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2114 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2115 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2116 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2117 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2118 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2119 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2120 case X86::BI__builtin_ia32_vfmaddss3_mask:
2121 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2122 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2126 case X86::BI__builtin_ia32_getmantsd_round_mask:
2127 case X86::BI__builtin_ia32_getmantss_round_mask:
2133 llvm::APSInt Result;
2135 // We can't check the value of a dependent argument.
2136 Expr *Arg = TheCall->getArg(ArgNum);
2137 if (Arg->isTypeDependent() || Arg->isValueDependent())
2140 // Check constant-ness first.
2141 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2144 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2145 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2146 // combined with ROUND_NO_EXC.
2147 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2148 Result == 8/*ROUND_NO_EXC*/ ||
2149 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2152 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2153 << Arg->getSourceRange();
2156 // Check if the gather/scatter scale is legal.
2157 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2158 CallExpr *TheCall) {
2159 unsigned ArgNum = 0;
2160 switch (BuiltinID) {
2163 case X86::BI__builtin_ia32_gatherpfdpd:
2164 case X86::BI__builtin_ia32_gatherpfdps:
2165 case X86::BI__builtin_ia32_gatherpfqpd:
2166 case X86::BI__builtin_ia32_gatherpfqps:
2167 case X86::BI__builtin_ia32_scatterpfdpd:
2168 case X86::BI__builtin_ia32_scatterpfdps:
2169 case X86::BI__builtin_ia32_scatterpfqpd:
2170 case X86::BI__builtin_ia32_scatterpfqps:
2173 case X86::BI__builtin_ia32_gatherd_pd:
2174 case X86::BI__builtin_ia32_gatherd_pd256:
2175 case X86::BI__builtin_ia32_gatherq_pd:
2176 case X86::BI__builtin_ia32_gatherq_pd256:
2177 case X86::BI__builtin_ia32_gatherd_ps:
2178 case X86::BI__builtin_ia32_gatherd_ps256:
2179 case X86::BI__builtin_ia32_gatherq_ps:
2180 case X86::BI__builtin_ia32_gatherq_ps256:
2181 case X86::BI__builtin_ia32_gatherd_q:
2182 case X86::BI__builtin_ia32_gatherd_q256:
2183 case X86::BI__builtin_ia32_gatherq_q:
2184 case X86::BI__builtin_ia32_gatherq_q256:
2185 case X86::BI__builtin_ia32_gatherd_d:
2186 case X86::BI__builtin_ia32_gatherd_d256:
2187 case X86::BI__builtin_ia32_gatherq_d:
2188 case X86::BI__builtin_ia32_gatherq_d256:
2189 case X86::BI__builtin_ia32_gather3div2df:
2190 case X86::BI__builtin_ia32_gather3div2di:
2191 case X86::BI__builtin_ia32_gather3div4df:
2192 case X86::BI__builtin_ia32_gather3div4di:
2193 case X86::BI__builtin_ia32_gather3div4sf:
2194 case X86::BI__builtin_ia32_gather3div4si:
2195 case X86::BI__builtin_ia32_gather3div8sf:
2196 case X86::BI__builtin_ia32_gather3div8si:
2197 case X86::BI__builtin_ia32_gather3siv2df:
2198 case X86::BI__builtin_ia32_gather3siv2di:
2199 case X86::BI__builtin_ia32_gather3siv4df:
2200 case X86::BI__builtin_ia32_gather3siv4di:
2201 case X86::BI__builtin_ia32_gather3siv4sf:
2202 case X86::BI__builtin_ia32_gather3siv4si:
2203 case X86::BI__builtin_ia32_gather3siv8sf:
2204 case X86::BI__builtin_ia32_gather3siv8si:
2205 case X86::BI__builtin_ia32_gathersiv8df:
2206 case X86::BI__builtin_ia32_gathersiv16sf:
2207 case X86::BI__builtin_ia32_gatherdiv8df:
2208 case X86::BI__builtin_ia32_gatherdiv16sf:
2209 case X86::BI__builtin_ia32_gathersiv8di:
2210 case X86::BI__builtin_ia32_gathersiv16si:
2211 case X86::BI__builtin_ia32_gatherdiv8di:
2212 case X86::BI__builtin_ia32_gatherdiv16si:
2213 case X86::BI__builtin_ia32_scatterdiv2df:
2214 case X86::BI__builtin_ia32_scatterdiv2di:
2215 case X86::BI__builtin_ia32_scatterdiv4df:
2216 case X86::BI__builtin_ia32_scatterdiv4di:
2217 case X86::BI__builtin_ia32_scatterdiv4sf:
2218 case X86::BI__builtin_ia32_scatterdiv4si:
2219 case X86::BI__builtin_ia32_scatterdiv8sf:
2220 case X86::BI__builtin_ia32_scatterdiv8si:
2221 case X86::BI__builtin_ia32_scattersiv2df:
2222 case X86::BI__builtin_ia32_scattersiv2di:
2223 case X86::BI__builtin_ia32_scattersiv4df:
2224 case X86::BI__builtin_ia32_scattersiv4di:
2225 case X86::BI__builtin_ia32_scattersiv4sf:
2226 case X86::BI__builtin_ia32_scattersiv4si:
2227 case X86::BI__builtin_ia32_scattersiv8sf:
2228 case X86::BI__builtin_ia32_scattersiv8si:
2229 case X86::BI__builtin_ia32_scattersiv8df:
2230 case X86::BI__builtin_ia32_scattersiv16sf:
2231 case X86::BI__builtin_ia32_scatterdiv8df:
2232 case X86::BI__builtin_ia32_scatterdiv16sf:
2233 case X86::BI__builtin_ia32_scattersiv8di:
2234 case X86::BI__builtin_ia32_scattersiv16si:
2235 case X86::BI__builtin_ia32_scatterdiv8di:
2236 case X86::BI__builtin_ia32_scatterdiv16si:
2241 llvm::APSInt Result;
2243 // We can't check the value of a dependent argument.
2244 Expr *Arg = TheCall->getArg(ArgNum);
2245 if (Arg->isTypeDependent() || Arg->isValueDependent())
2248 // Check constant-ness first.
2249 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2252 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2255 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2256 << Arg->getSourceRange();
2259 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2260 if (BuiltinID == X86::BI__builtin_cpu_supports)
2261 return SemaBuiltinCpuSupports(*this, TheCall);
2263 if (BuiltinID == X86::BI__builtin_cpu_is)
2264 return SemaBuiltinCpuIs(*this, TheCall);
2266 // If the intrinsic has rounding or SAE make sure its valid.
2267 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2270 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2271 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2274 // For intrinsics which take an immediate value as part of the instruction,
2275 // range check them here.
2276 int i = 0, l = 0, u = 0;
2277 switch (BuiltinID) {
2280 case X86::BI_mm_prefetch:
2281 i = 1; l = 0; u = 7;
2283 case X86::BI__builtin_ia32_sha1rnds4:
2284 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2285 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2286 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2287 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2288 i = 2; l = 0; u = 3;
2290 case X86::BI__builtin_ia32_vpermil2pd:
2291 case X86::BI__builtin_ia32_vpermil2pd256:
2292 case X86::BI__builtin_ia32_vpermil2ps:
2293 case X86::BI__builtin_ia32_vpermil2ps256:
2294 i = 3; l = 0; u = 3;
2296 case X86::BI__builtin_ia32_cmpb128_mask:
2297 case X86::BI__builtin_ia32_cmpw128_mask:
2298 case X86::BI__builtin_ia32_cmpd128_mask:
2299 case X86::BI__builtin_ia32_cmpq128_mask:
2300 case X86::BI__builtin_ia32_cmpb256_mask:
2301 case X86::BI__builtin_ia32_cmpw256_mask:
2302 case X86::BI__builtin_ia32_cmpd256_mask:
2303 case X86::BI__builtin_ia32_cmpq256_mask:
2304 case X86::BI__builtin_ia32_cmpb512_mask:
2305 case X86::BI__builtin_ia32_cmpw512_mask:
2306 case X86::BI__builtin_ia32_cmpd512_mask:
2307 case X86::BI__builtin_ia32_cmpq512_mask:
2308 case X86::BI__builtin_ia32_ucmpb128_mask:
2309 case X86::BI__builtin_ia32_ucmpw128_mask:
2310 case X86::BI__builtin_ia32_ucmpd128_mask:
2311 case X86::BI__builtin_ia32_ucmpq128_mask:
2312 case X86::BI__builtin_ia32_ucmpb256_mask:
2313 case X86::BI__builtin_ia32_ucmpw256_mask:
2314 case X86::BI__builtin_ia32_ucmpd256_mask:
2315 case X86::BI__builtin_ia32_ucmpq256_mask:
2316 case X86::BI__builtin_ia32_ucmpb512_mask:
2317 case X86::BI__builtin_ia32_ucmpw512_mask:
2318 case X86::BI__builtin_ia32_ucmpd512_mask:
2319 case X86::BI__builtin_ia32_ucmpq512_mask:
2320 case X86::BI__builtin_ia32_vpcomub:
2321 case X86::BI__builtin_ia32_vpcomuw:
2322 case X86::BI__builtin_ia32_vpcomud:
2323 case X86::BI__builtin_ia32_vpcomuq:
2324 case X86::BI__builtin_ia32_vpcomb:
2325 case X86::BI__builtin_ia32_vpcomw:
2326 case X86::BI__builtin_ia32_vpcomd:
2327 case X86::BI__builtin_ia32_vpcomq:
2328 i = 2; l = 0; u = 7;
2330 case X86::BI__builtin_ia32_roundps:
2331 case X86::BI__builtin_ia32_roundpd:
2332 case X86::BI__builtin_ia32_roundps256:
2333 case X86::BI__builtin_ia32_roundpd256:
2334 i = 1; l = 0; u = 15;
2336 case X86::BI__builtin_ia32_roundss:
2337 case X86::BI__builtin_ia32_roundsd:
2338 case X86::BI__builtin_ia32_rangepd128_mask:
2339 case X86::BI__builtin_ia32_rangepd256_mask:
2340 case X86::BI__builtin_ia32_rangepd512_mask:
2341 case X86::BI__builtin_ia32_rangeps128_mask:
2342 case X86::BI__builtin_ia32_rangeps256_mask:
2343 case X86::BI__builtin_ia32_rangeps512_mask:
2344 case X86::BI__builtin_ia32_getmantsd_round_mask:
2345 case X86::BI__builtin_ia32_getmantss_round_mask:
2346 i = 2; l = 0; u = 15;
2348 case X86::BI__builtin_ia32_cmpps:
2349 case X86::BI__builtin_ia32_cmpss:
2350 case X86::BI__builtin_ia32_cmppd:
2351 case X86::BI__builtin_ia32_cmpsd:
2352 case X86::BI__builtin_ia32_cmpps256:
2353 case X86::BI__builtin_ia32_cmppd256:
2354 case X86::BI__builtin_ia32_cmpps128_mask:
2355 case X86::BI__builtin_ia32_cmppd128_mask:
2356 case X86::BI__builtin_ia32_cmpps256_mask:
2357 case X86::BI__builtin_ia32_cmppd256_mask:
2358 case X86::BI__builtin_ia32_cmpps512_mask:
2359 case X86::BI__builtin_ia32_cmppd512_mask:
2360 case X86::BI__builtin_ia32_cmpsd_mask:
2361 case X86::BI__builtin_ia32_cmpss_mask:
2362 i = 2; l = 0; u = 31;
2364 case X86::BI__builtin_ia32_xabort:
2365 i = 0; l = -128; u = 255;
2367 case X86::BI__builtin_ia32_pshufw:
2368 case X86::BI__builtin_ia32_aeskeygenassist128:
2369 i = 1; l = -128; u = 255;
2371 case X86::BI__builtin_ia32_vcvtps2ph:
2372 case X86::BI__builtin_ia32_vcvtps2ph_mask:
2373 case X86::BI__builtin_ia32_vcvtps2ph256:
2374 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2375 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2376 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2377 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2378 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2379 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2380 case X86::BI__builtin_ia32_rndscaleps_mask:
2381 case X86::BI__builtin_ia32_rndscalepd_mask:
2382 case X86::BI__builtin_ia32_reducepd128_mask:
2383 case X86::BI__builtin_ia32_reducepd256_mask:
2384 case X86::BI__builtin_ia32_reducepd512_mask:
2385 case X86::BI__builtin_ia32_reduceps128_mask:
2386 case X86::BI__builtin_ia32_reduceps256_mask:
2387 case X86::BI__builtin_ia32_reduceps512_mask:
2388 case X86::BI__builtin_ia32_prold512_mask:
2389 case X86::BI__builtin_ia32_prolq512_mask:
2390 case X86::BI__builtin_ia32_prold128_mask:
2391 case X86::BI__builtin_ia32_prold256_mask:
2392 case X86::BI__builtin_ia32_prolq128_mask:
2393 case X86::BI__builtin_ia32_prolq256_mask:
2394 case X86::BI__builtin_ia32_prord128_mask:
2395 case X86::BI__builtin_ia32_prord256_mask:
2396 case X86::BI__builtin_ia32_prorq128_mask:
2397 case X86::BI__builtin_ia32_prorq256_mask:
2398 case X86::BI__builtin_ia32_fpclasspd128_mask:
2399 case X86::BI__builtin_ia32_fpclasspd256_mask:
2400 case X86::BI__builtin_ia32_fpclassps128_mask:
2401 case X86::BI__builtin_ia32_fpclassps256_mask:
2402 case X86::BI__builtin_ia32_fpclassps512_mask:
2403 case X86::BI__builtin_ia32_fpclasspd512_mask:
2404 case X86::BI__builtin_ia32_fpclasssd_mask:
2405 case X86::BI__builtin_ia32_fpclassss_mask:
2406 i = 1; l = 0; u = 255;
2408 case X86::BI__builtin_ia32_palignr:
2409 case X86::BI__builtin_ia32_insertps128:
2410 case X86::BI__builtin_ia32_dpps:
2411 case X86::BI__builtin_ia32_dppd:
2412 case X86::BI__builtin_ia32_dpps256:
2413 case X86::BI__builtin_ia32_mpsadbw128:
2414 case X86::BI__builtin_ia32_mpsadbw256:
2415 case X86::BI__builtin_ia32_pcmpistrm128:
2416 case X86::BI__builtin_ia32_pcmpistri128:
2417 case X86::BI__builtin_ia32_pcmpistria128:
2418 case X86::BI__builtin_ia32_pcmpistric128:
2419 case X86::BI__builtin_ia32_pcmpistrio128:
2420 case X86::BI__builtin_ia32_pcmpistris128:
2421 case X86::BI__builtin_ia32_pcmpistriz128:
2422 case X86::BI__builtin_ia32_pclmulqdq128:
2423 case X86::BI__builtin_ia32_vperm2f128_pd256:
2424 case X86::BI__builtin_ia32_vperm2f128_ps256:
2425 case X86::BI__builtin_ia32_vperm2f128_si256:
2426 case X86::BI__builtin_ia32_permti256:
2427 i = 2; l = -128; u = 255;
2429 case X86::BI__builtin_ia32_palignr128:
2430 case X86::BI__builtin_ia32_palignr256:
2431 case X86::BI__builtin_ia32_palignr512_mask:
2432 case X86::BI__builtin_ia32_vcomisd:
2433 case X86::BI__builtin_ia32_vcomiss:
2434 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2435 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2436 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2437 case X86::BI__builtin_ia32_shuf_i64x2_mask:
2438 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2439 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2440 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2441 i = 2; l = 0; u = 255;
2443 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2444 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2445 case X86::BI__builtin_ia32_fixupimmps512_mask:
2446 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2447 case X86::BI__builtin_ia32_fixupimmsd_mask:
2448 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2449 case X86::BI__builtin_ia32_fixupimmss_mask:
2450 case X86::BI__builtin_ia32_fixupimmss_maskz:
2451 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2452 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2453 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2454 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2455 case X86::BI__builtin_ia32_fixupimmps128_mask:
2456 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2457 case X86::BI__builtin_ia32_fixupimmps256_mask:
2458 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2459 case X86::BI__builtin_ia32_pternlogd512_mask:
2460 case X86::BI__builtin_ia32_pternlogd512_maskz:
2461 case X86::BI__builtin_ia32_pternlogq512_mask:
2462 case X86::BI__builtin_ia32_pternlogq512_maskz:
2463 case X86::BI__builtin_ia32_pternlogd128_mask:
2464 case X86::BI__builtin_ia32_pternlogd128_maskz:
2465 case X86::BI__builtin_ia32_pternlogd256_mask:
2466 case X86::BI__builtin_ia32_pternlogd256_maskz:
2467 case X86::BI__builtin_ia32_pternlogq128_mask:
2468 case X86::BI__builtin_ia32_pternlogq128_maskz:
2469 case X86::BI__builtin_ia32_pternlogq256_mask:
2470 case X86::BI__builtin_ia32_pternlogq256_maskz:
2471 i = 3; l = 0; u = 255;
2473 case X86::BI__builtin_ia32_gatherpfdpd:
2474 case X86::BI__builtin_ia32_gatherpfdps:
2475 case X86::BI__builtin_ia32_gatherpfqpd:
2476 case X86::BI__builtin_ia32_gatherpfqps:
2477 case X86::BI__builtin_ia32_scatterpfdpd:
2478 case X86::BI__builtin_ia32_scatterpfdps:
2479 case X86::BI__builtin_ia32_scatterpfqpd:
2480 case X86::BI__builtin_ia32_scatterpfqps:
2481 i = 4; l = 2; u = 3;
2483 case X86::BI__builtin_ia32_pcmpestrm128:
2484 case X86::BI__builtin_ia32_pcmpestri128:
2485 case X86::BI__builtin_ia32_pcmpestria128:
2486 case X86::BI__builtin_ia32_pcmpestric128:
2487 case X86::BI__builtin_ia32_pcmpestrio128:
2488 case X86::BI__builtin_ia32_pcmpestris128:
2489 case X86::BI__builtin_ia32_pcmpestriz128:
2490 i = 4; l = -128; u = 255;
2492 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2493 case X86::BI__builtin_ia32_rndscaless_round_mask:
2494 i = 4; l = 0; u = 255;
2497 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2500 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2501 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2502 /// Returns true when the format fits the function and the FormatStringInfo has
2504 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2505 FormatStringInfo *FSI) {
2506 FSI->HasVAListArg = Format->getFirstArg() == 0;
2507 FSI->FormatIdx = Format->getFormatIdx() - 1;
2508 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2510 // The way the format attribute works in GCC, the implicit this argument
2511 // of member functions is counted. However, it doesn't appear in our own
2512 // lists, so decrement format_idx in that case.
2514 if(FSI->FormatIdx == 0)
2517 if (FSI->FirstDataArg != 0)
2518 --FSI->FirstDataArg;
2523 /// Checks if a the given expression evaluates to null.
2525 /// \brief Returns true if the value evaluates to null.
2526 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2527 // If the expression has non-null type, it doesn't evaluate to null.
2528 if (auto nullability
2529 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2530 if (*nullability == NullabilityKind::NonNull)
2534 // As a special case, transparent unions initialized with zero are
2535 // considered null for the purposes of the nonnull attribute.
2536 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2537 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2538 if (const CompoundLiteralExpr *CLE =
2539 dyn_cast<CompoundLiteralExpr>(Expr))
2540 if (const InitListExpr *ILE =
2541 dyn_cast<InitListExpr>(CLE->getInitializer()))
2542 Expr = ILE->getInit(0);
2546 return (!Expr->isValueDependent() &&
2547 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2551 static void CheckNonNullArgument(Sema &S,
2552 const Expr *ArgExpr,
2553 SourceLocation CallSiteLoc) {
2554 if (CheckNonNullExpr(S, ArgExpr))
2555 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2556 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2559 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2560 FormatStringInfo FSI;
2561 if ((GetFormatStringType(Format) == FST_NSString) &&
2562 getFormatStringInfo(Format, false, &FSI)) {
2563 Idx = FSI.FormatIdx;
2569 /// \brief Diagnose use of %s directive in an NSString which is being passed
2570 /// as formatting string to formatting method.
2572 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2573 const NamedDecl *FDecl,
2577 bool Format = false;
2578 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2579 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2584 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2585 if (S.GetFormatNSStringIdx(I, Idx)) {
2590 if (!Format || NumArgs <= Idx)
2592 const Expr *FormatExpr = Args[Idx];
2593 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2594 FormatExpr = CSCE->getSubExpr();
2595 const StringLiteral *FormatString;
2596 if (const ObjCStringLiteral *OSL =
2597 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2598 FormatString = OSL->getString();
2600 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2603 if (S.FormatStringHasSArg(FormatString)) {
2604 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2606 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2607 << FDecl->getDeclName();
2611 /// Determine whether the given type has a non-null nullability annotation.
2612 static bool isNonNullType(ASTContext &ctx, QualType type) {
2613 if (auto nullability = type->getNullability(ctx))
2614 return *nullability == NullabilityKind::NonNull;
2619 static void CheckNonNullArguments(Sema &S,
2620 const NamedDecl *FDecl,
2621 const FunctionProtoType *Proto,
2622 ArrayRef<const Expr *> Args,
2623 SourceLocation CallSiteLoc) {
2624 assert((FDecl || Proto) && "Need a function declaration or prototype");
2626 // Check the attributes attached to the method/function itself.
2627 llvm::SmallBitVector NonNullArgs;
2629 // Handle the nonnull attribute on the function/method declaration itself.
2630 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2631 if (!NonNull->args_size()) {
2632 // Easy case: all pointer arguments are nonnull.
2633 for (const auto *Arg : Args)
2634 if (S.isValidPointerAttrType(Arg->getType()))
2635 CheckNonNullArgument(S, Arg, CallSiteLoc);
2639 for (unsigned Val : NonNull->args()) {
2640 if (Val >= Args.size())
2642 if (NonNullArgs.empty())
2643 NonNullArgs.resize(Args.size());
2644 NonNullArgs.set(Val);
2649 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2650 // Handle the nonnull attribute on the parameters of the
2652 ArrayRef<ParmVarDecl*> parms;
2653 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2654 parms = FD->parameters();
2656 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2658 unsigned ParamIndex = 0;
2659 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2660 I != E; ++I, ++ParamIndex) {
2661 const ParmVarDecl *PVD = *I;
2662 if (PVD->hasAttr<NonNullAttr>() ||
2663 isNonNullType(S.Context, PVD->getType())) {
2664 if (NonNullArgs.empty())
2665 NonNullArgs.resize(Args.size());
2667 NonNullArgs.set(ParamIndex);
2671 // If we have a non-function, non-method declaration but no
2672 // function prototype, try to dig out the function prototype.
2674 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2675 QualType type = VD->getType().getNonReferenceType();
2676 if (auto pointerType = type->getAs<PointerType>())
2677 type = pointerType->getPointeeType();
2678 else if (auto blockType = type->getAs<BlockPointerType>())
2679 type = blockType->getPointeeType();
2680 // FIXME: data member pointers?
2682 // Dig out the function prototype, if there is one.
2683 Proto = type->getAs<FunctionProtoType>();
2687 // Fill in non-null argument information from the nullability
2688 // information on the parameter types (if we have them).
2691 for (auto paramType : Proto->getParamTypes()) {
2692 if (isNonNullType(S.Context, paramType)) {
2693 if (NonNullArgs.empty())
2694 NonNullArgs.resize(Args.size());
2696 NonNullArgs.set(Index);
2704 // Check for non-null arguments.
2705 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2706 ArgIndex != ArgIndexEnd; ++ArgIndex) {
2707 if (NonNullArgs[ArgIndex])
2708 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2712 /// Handles the checks for format strings, non-POD arguments to vararg
2713 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2715 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2716 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2717 bool IsMemberFunction, SourceLocation Loc,
2718 SourceRange Range, VariadicCallType CallType) {
2719 // FIXME: We should check as much as we can in the template definition.
2720 if (CurContext->isDependentContext())
2723 // Printf and scanf checking.
2724 llvm::SmallBitVector CheckedVarArgs;
2726 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2727 // Only create vector if there are format attributes.
2728 CheckedVarArgs.resize(Args.size());
2730 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2735 // Refuse POD arguments that weren't caught by the format string
2737 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2738 if (CallType != VariadicDoesNotApply &&
2739 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2740 unsigned NumParams = Proto ? Proto->getNumParams()
2741 : FDecl && isa<FunctionDecl>(FDecl)
2742 ? cast<FunctionDecl>(FDecl)->getNumParams()
2743 : FDecl && isa<ObjCMethodDecl>(FDecl)
2744 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2747 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2748 // Args[ArgIdx] can be null in malformed code.
2749 if (const Expr *Arg = Args[ArgIdx]) {
2750 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2751 checkVariadicArgument(Arg, CallType);
2756 if (FDecl || Proto) {
2757 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2759 // Type safety checking.
2761 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2762 CheckArgumentWithTypeTag(I, Args, Loc);
2767 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2770 /// CheckConstructorCall - Check a constructor call for correctness and safety
2771 /// properties not enforced by the C type system.
2772 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2773 ArrayRef<const Expr *> Args,
2774 const FunctionProtoType *Proto,
2775 SourceLocation Loc) {
2776 VariadicCallType CallType =
2777 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2778 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2779 Loc, SourceRange(), CallType);
2782 /// CheckFunctionCall - Check a direct function call for various correctness
2783 /// and safety properties not strictly enforced by the C type system.
2784 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2785 const FunctionProtoType *Proto) {
2786 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2787 isa<CXXMethodDecl>(FDecl);
2788 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2789 IsMemberOperatorCall;
2790 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2791 TheCall->getCallee());
2792 Expr** Args = TheCall->getArgs();
2793 unsigned NumArgs = TheCall->getNumArgs();
2795 Expr *ImplicitThis = nullptr;
2796 if (IsMemberOperatorCall) {
2797 // If this is a call to a member operator, hide the first argument
2799 // FIXME: Our choice of AST representation here is less than ideal.
2800 ImplicitThis = Args[0];
2803 } else if (IsMemberFunction)
2805 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2807 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2808 IsMemberFunction, TheCall->getRParenLoc(),
2809 TheCall->getCallee()->getSourceRange(), CallType);
2811 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2812 // None of the checks below are needed for functions that don't have
2813 // simple names (e.g., C++ conversion functions).
2817 CheckAbsoluteValueFunction(TheCall, FDecl);
2818 CheckMaxUnsignedZero(TheCall, FDecl);
2820 if (getLangOpts().ObjC1)
2821 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2823 unsigned CMId = FDecl->getMemoryFunctionKind();
2827 // Handle memory setting and copying functions.
2828 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2829 CheckStrlcpycatArguments(TheCall, FnInfo);
2830 else if (CMId == Builtin::BIstrncat)
2831 CheckStrncatArguments(TheCall, FnInfo);
2833 CheckMemaccessArguments(TheCall, CMId, FnInfo);
2838 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2839 ArrayRef<const Expr *> Args) {
2840 VariadicCallType CallType =
2841 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2843 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2844 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2850 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2851 const FunctionProtoType *Proto) {
2853 if (const auto *V = dyn_cast<VarDecl>(NDecl))
2854 Ty = V->getType().getNonReferenceType();
2855 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2856 Ty = F->getType().getNonReferenceType();
2860 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2861 !Ty->isFunctionProtoType())
2864 VariadicCallType CallType;
2865 if (!Proto || !Proto->isVariadic()) {
2866 CallType = VariadicDoesNotApply;
2867 } else if (Ty->isBlockPointerType()) {
2868 CallType = VariadicBlock;
2869 } else { // Ty->isFunctionPointerType()
2870 CallType = VariadicFunction;
2873 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2874 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2875 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2876 TheCall->getCallee()->getSourceRange(), CallType);
2881 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2882 /// such as function pointers returned from functions.
2883 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2884 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2885 TheCall->getCallee());
2886 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2887 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2888 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2889 TheCall->getCallee()->getSourceRange(), CallType);
2894 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2895 if (!llvm::isValidAtomicOrderingCABI(Ordering))
2898 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2900 case AtomicExpr::AO__c11_atomic_init:
2901 case AtomicExpr::AO__opencl_atomic_init:
2902 llvm_unreachable("There is no ordering argument for an init");
2904 case AtomicExpr::AO__c11_atomic_load:
2905 case AtomicExpr::AO__opencl_atomic_load:
2906 case AtomicExpr::AO__atomic_load_n:
2907 case AtomicExpr::AO__atomic_load:
2908 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2909 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2911 case AtomicExpr::AO__c11_atomic_store:
2912 case AtomicExpr::AO__opencl_atomic_store:
2913 case AtomicExpr::AO__atomic_store:
2914 case AtomicExpr::AO__atomic_store_n:
2915 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2916 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2917 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2924 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2925 AtomicExpr::AtomicOp Op) {
2926 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2927 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2929 // All the non-OpenCL operations take one of the following forms.
2930 // The OpenCL operations take the __c11 forms with one extra argument for
2931 // synchronization scope.
2933 // C __c11_atomic_init(A *, C)
2936 // C __c11_atomic_load(A *, int)
2939 // void __atomic_load(A *, CP, int)
2942 // void __atomic_store(A *, CP, int)
2945 // C __c11_atomic_add(A *, M, int)
2948 // C __atomic_exchange_n(A *, CP, int)
2951 // void __atomic_exchange(A *, C *, CP, int)
2954 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2957 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2961 const unsigned NumForm = GNUCmpXchg + 1;
2962 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2963 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2965 // C is an appropriate type,
2966 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2967 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2968 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2969 // the int parameters are for orderings.
2971 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2972 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2973 "need to update code for modified forms");
2974 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2975 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2976 AtomicExpr::AO__atomic_load,
2977 "need to update code for modified C11 atomics");
2978 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2979 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2980 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2981 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2983 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2984 Op == AtomicExpr::AO__atomic_store_n ||
2985 Op == AtomicExpr::AO__atomic_exchange_n ||
2986 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2987 bool IsAddSub = false;
2990 case AtomicExpr::AO__c11_atomic_init:
2991 case AtomicExpr::AO__opencl_atomic_init:
2995 case AtomicExpr::AO__c11_atomic_load:
2996 case AtomicExpr::AO__opencl_atomic_load:
2997 case AtomicExpr::AO__atomic_load_n:
3001 case AtomicExpr::AO__atomic_load:
3005 case AtomicExpr::AO__c11_atomic_store:
3006 case AtomicExpr::AO__opencl_atomic_store:
3007 case AtomicExpr::AO__atomic_store:
3008 case AtomicExpr::AO__atomic_store_n:
3012 case AtomicExpr::AO__c11_atomic_fetch_add:
3013 case AtomicExpr::AO__c11_atomic_fetch_sub:
3014 case AtomicExpr::AO__opencl_atomic_fetch_add:
3015 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3016 case AtomicExpr::AO__opencl_atomic_fetch_min:
3017 case AtomicExpr::AO__opencl_atomic_fetch_max:
3018 case AtomicExpr::AO__atomic_fetch_add:
3019 case AtomicExpr::AO__atomic_fetch_sub:
3020 case AtomicExpr::AO__atomic_add_fetch:
3021 case AtomicExpr::AO__atomic_sub_fetch:
3024 case AtomicExpr::AO__c11_atomic_fetch_and:
3025 case AtomicExpr::AO__c11_atomic_fetch_or:
3026 case AtomicExpr::AO__c11_atomic_fetch_xor:
3027 case AtomicExpr::AO__opencl_atomic_fetch_and:
3028 case AtomicExpr::AO__opencl_atomic_fetch_or:
3029 case AtomicExpr::AO__opencl_atomic_fetch_xor:
3030 case AtomicExpr::AO__atomic_fetch_and:
3031 case AtomicExpr::AO__atomic_fetch_or:
3032 case AtomicExpr::AO__atomic_fetch_xor:
3033 case AtomicExpr::AO__atomic_fetch_nand:
3034 case AtomicExpr::AO__atomic_and_fetch:
3035 case AtomicExpr::AO__atomic_or_fetch:
3036 case AtomicExpr::AO__atomic_xor_fetch:
3037 case AtomicExpr::AO__atomic_nand_fetch:
3041 case AtomicExpr::AO__c11_atomic_exchange:
3042 case AtomicExpr::AO__opencl_atomic_exchange:
3043 case AtomicExpr::AO__atomic_exchange_n:
3047 case AtomicExpr::AO__atomic_exchange:
3051 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3052 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3053 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3054 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3058 case AtomicExpr::AO__atomic_compare_exchange:
3059 case AtomicExpr::AO__atomic_compare_exchange_n:
3064 unsigned AdjustedNumArgs = NumArgs[Form];
3065 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3067 // Check we have the right number of arguments.
3068 if (TheCall->getNumArgs() < AdjustedNumArgs) {
3069 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3070 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3071 << TheCall->getCallee()->getSourceRange();
3073 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3074 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3075 diag::err_typecheck_call_too_many_args)
3076 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3077 << TheCall->getCallee()->getSourceRange();
3081 // Inspect the first argument of the atomic operation.
3082 Expr *Ptr = TheCall->getArg(0);
3083 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3084 if (ConvertedPtr.isInvalid())
3087 Ptr = ConvertedPtr.get();
3088 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3090 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3091 << Ptr->getType() << Ptr->getSourceRange();
3095 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3096 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3097 QualType ValType = AtomTy; // 'C'
3099 if (!AtomTy->isAtomicType()) {
3100 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3101 << Ptr->getType() << Ptr->getSourceRange();
3104 if (AtomTy.isConstQualified() ||
3105 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3106 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3107 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3108 << Ptr->getSourceRange();
3111 ValType = AtomTy->getAs<AtomicType>()->getValueType();
3112 } else if (Form != Load && Form != LoadCopy) {
3113 if (ValType.isConstQualified()) {
3114 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3115 << Ptr->getType() << Ptr->getSourceRange();
3120 // For an arithmetic operation, the implied arithmetic must be well-formed.
3121 if (Form == Arithmetic) {
3122 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3123 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3124 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3125 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3128 if (!IsAddSub && !ValType->isIntegerType()) {
3129 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3130 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3133 if (IsC11 && ValType->isPointerType() &&
3134 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3135 diag::err_incomplete_type)) {
3138 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3139 // For __atomic_*_n operations, the value type must be a scalar integral or
3140 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3141 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3142 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3146 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3147 !AtomTy->isScalarType()) {
3148 // For GNU atomics, require a trivially-copyable type. This is not part of
3149 // the GNU atomics specification, but we enforce it for sanity.
3150 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3151 << Ptr->getType() << Ptr->getSourceRange();
3155 switch (ValType.getObjCLifetime()) {
3156 case Qualifiers::OCL_None:
3157 case Qualifiers::OCL_ExplicitNone:
3161 case Qualifiers::OCL_Weak:
3162 case Qualifiers::OCL_Strong:
3163 case Qualifiers::OCL_Autoreleasing:
3164 // FIXME: Can this happen? By this point, ValType should be known
3165 // to be trivially copyable.
3166 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3167 << ValType << Ptr->getSourceRange();
3171 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3172 // volatile-ness of the pointee-type inject itself into the result or the
3173 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3174 ValType.removeLocalVolatile();
3175 ValType.removeLocalConst();
3176 QualType ResultType = ValType;
3177 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3179 ResultType = Context.VoidTy;
3180 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3181 ResultType = Context.BoolTy;
3183 // The type of a parameter passed 'by value'. In the GNU atomics, such
3184 // arguments are actually passed as pointers.
3185 QualType ByValType = ValType; // 'CP'
3187 ByValType = Ptr->getType();
3189 // The first argument --- the pointer --- has a fixed type; we
3190 // deduce the types of the rest of the arguments accordingly. Walk
3191 // the remaining arguments, converting them to the deduced value type.
3192 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3194 if (i < NumVals[Form] + 1) {
3197 // The second argument is the non-atomic operand. For arithmetic, this
3198 // is always passed by value, and for a compare_exchange it is always
3199 // passed by address. For the rest, GNU uses by-address and C11 uses
3201 assert(Form != Load);
3202 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3204 else if (Form == Copy || Form == Xchg)
3206 else if (Form == Arithmetic)
3207 Ty = Context.getPointerDiffType();
3209 Expr *ValArg = TheCall->getArg(i);
3210 // Treat this argument as _Nonnull as we want to show a warning if
3211 // NULL is passed into it.
3212 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3213 LangAS AS = LangAS::Default;
3214 // Keep address space of non-atomic pointer type.
3215 if (const PointerType *PtrTy =
3216 ValArg->getType()->getAs<PointerType>()) {
3217 AS = PtrTy->getPointeeType().getAddressSpace();
3219 Ty = Context.getPointerType(
3220 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3224 // The third argument to compare_exchange / GNU exchange is a
3225 // (pointer to a) desired value.
3229 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3230 Ty = Context.BoolTy;
3234 // The order(s) and scope are always converted to int.
3238 InitializedEntity Entity =
3239 InitializedEntity::InitializeParameter(Context, Ty, false);
3240 ExprResult Arg = TheCall->getArg(i);
3241 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3242 if (Arg.isInvalid())
3244 TheCall->setArg(i, Arg.get());
3247 // Permute the arguments into a 'consistent' order.
3248 SmallVector<Expr*, 5> SubExprs;
3249 SubExprs.push_back(Ptr);
3252 // Note, AtomicExpr::getVal1() has a special case for this atomic.
3253 SubExprs.push_back(TheCall->getArg(1)); // Val1
3256 SubExprs.push_back(TheCall->getArg(1)); // Order
3262 SubExprs.push_back(TheCall->getArg(2)); // Order
3263 SubExprs.push_back(TheCall->getArg(1)); // Val1
3266 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3267 SubExprs.push_back(TheCall->getArg(3)); // Order
3268 SubExprs.push_back(TheCall->getArg(1)); // Val1
3269 SubExprs.push_back(TheCall->getArg(2)); // Val2
3272 SubExprs.push_back(TheCall->getArg(3)); // Order
3273 SubExprs.push_back(TheCall->getArg(1)); // Val1
3274 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3275 SubExprs.push_back(TheCall->getArg(2)); // Val2
3278 SubExprs.push_back(TheCall->getArg(4)); // Order
3279 SubExprs.push_back(TheCall->getArg(1)); // Val1
3280 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3281 SubExprs.push_back(TheCall->getArg(2)); // Val2
3282 SubExprs.push_back(TheCall->getArg(3)); // Weak
3286 if (SubExprs.size() >= 2 && Form != Init) {
3287 llvm::APSInt Result(32);
3288 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3289 !isValidOrderingForOp(Result.getSExtValue(), Op))
3290 Diag(SubExprs[1]->getLocStart(),
3291 diag::warn_atomic_op_has_invalid_memory_order)
3292 << SubExprs[1]->getSourceRange();
3295 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3296 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3297 llvm::APSInt Result(32);
3298 if (Scope->isIntegerConstantExpr(Result, Context) &&
3299 !ScopeModel->isValid(Result.getZExtValue())) {
3300 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3301 << Scope->getSourceRange();
3303 SubExprs.push_back(Scope);
3306 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3307 SubExprs, ResultType, Op,
3308 TheCall->getRParenLoc());
3310 if ((Op == AtomicExpr::AO__c11_atomic_load ||
3311 Op == AtomicExpr::AO__c11_atomic_store ||
3312 Op == AtomicExpr::AO__opencl_atomic_load ||
3313 Op == AtomicExpr::AO__opencl_atomic_store ) &&
3314 Context.AtomicUsesUnsupportedLibcall(AE))
3315 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3316 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3317 Op == AtomicExpr::AO__opencl_atomic_load)
3323 /// checkBuiltinArgument - Given a call to a builtin function, perform
3324 /// normal type-checking on the given argument, updating the call in
3325 /// place. This is useful when a builtin function requires custom
3326 /// type-checking for some of its arguments but not necessarily all of
3329 /// Returns true on error.
3330 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3331 FunctionDecl *Fn = E->getDirectCallee();
3332 assert(Fn && "builtin call without direct callee!");
3334 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3335 InitializedEntity Entity =
3336 InitializedEntity::InitializeParameter(S.Context, Param);
3338 ExprResult Arg = E->getArg(0);
3339 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3340 if (Arg.isInvalid())
3343 E->setArg(ArgIndex, Arg.get());
3347 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3348 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3349 /// type of its first argument. The main ActOnCallExpr routines have already
3350 /// promoted the types of arguments because all of these calls are prototyped as
3353 /// This function goes through and does final semantic checking for these
3356 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3357 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3358 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3359 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3361 // Ensure that we have at least one argument to do type inference from.
3362 if (TheCall->getNumArgs() < 1) {
3363 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3364 << 0 << 1 << TheCall->getNumArgs()
3365 << TheCall->getCallee()->getSourceRange();
3369 // Inspect the first argument of the atomic builtin. This should always be
3370 // a pointer type, whose element is an integral scalar or pointer type.
3371 // Because it is a pointer type, we don't have to worry about any implicit
3373 // FIXME: We don't allow floating point scalars as input.
3374 Expr *FirstArg = TheCall->getArg(0);
3375 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3376 if (FirstArgResult.isInvalid())
3378 FirstArg = FirstArgResult.get();
3379 TheCall->setArg(0, FirstArg);
3381 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3383 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3384 << FirstArg->getType() << FirstArg->getSourceRange();
3388 QualType ValType = pointerType->getPointeeType();
3389 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3390 !ValType->isBlockPointerType()) {
3391 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3392 << FirstArg->getType() << FirstArg->getSourceRange();
3396 switch (ValType.getObjCLifetime()) {
3397 case Qualifiers::OCL_None:
3398 case Qualifiers::OCL_ExplicitNone:
3402 case Qualifiers::OCL_Weak:
3403 case Qualifiers::OCL_Strong:
3404 case Qualifiers::OCL_Autoreleasing:
3405 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3406 << ValType << FirstArg->getSourceRange();
3410 // Strip any qualifiers off ValType.
3411 ValType = ValType.getUnqualifiedType();
3413 // The majority of builtins return a value, but a few have special return
3414 // types, so allow them to override appropriately below.
3415 QualType ResultType = ValType;
3417 // We need to figure out which concrete builtin this maps onto. For example,
3418 // __sync_fetch_and_add with a 2 byte object turns into
3419 // __sync_fetch_and_add_2.
3420 #define BUILTIN_ROW(x) \
3421 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3422 Builtin::BI##x##_8, Builtin::BI##x##_16 }
3424 static const unsigned BuiltinIndices[][5] = {
3425 BUILTIN_ROW(__sync_fetch_and_add),
3426 BUILTIN_ROW(__sync_fetch_and_sub),
3427 BUILTIN_ROW(__sync_fetch_and_or),
3428 BUILTIN_ROW(__sync_fetch_and_and),
3429 BUILTIN_ROW(__sync_fetch_and_xor),
3430 BUILTIN_ROW(__sync_fetch_and_nand),
3432 BUILTIN_ROW(__sync_add_and_fetch),
3433 BUILTIN_ROW(__sync_sub_and_fetch),
3434 BUILTIN_ROW(__sync_and_and_fetch),
3435 BUILTIN_ROW(__sync_or_and_fetch),
3436 BUILTIN_ROW(__sync_xor_and_fetch),
3437 BUILTIN_ROW(__sync_nand_and_fetch),
3439 BUILTIN_ROW(__sync_val_compare_and_swap),
3440 BUILTIN_ROW(__sync_bool_compare_and_swap),
3441 BUILTIN_ROW(__sync_lock_test_and_set),
3442 BUILTIN_ROW(__sync_lock_release),
3443 BUILTIN_ROW(__sync_swap)
3447 // Determine the index of the size.
3449 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3450 case 1: SizeIndex = 0; break;
3451 case 2: SizeIndex = 1; break;
3452 case 4: SizeIndex = 2; break;
3453 case 8: SizeIndex = 3; break;
3454 case 16: SizeIndex = 4; break;
3456 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3457 << FirstArg->getType() << FirstArg->getSourceRange();
3461 // Each of these builtins has one pointer argument, followed by some number of
3462 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3463 // that we ignore. Find out which row of BuiltinIndices to read from as well
3464 // as the number of fixed args.
3465 unsigned BuiltinID = FDecl->getBuiltinID();
3466 unsigned BuiltinIndex, NumFixed = 1;
3467 bool WarnAboutSemanticsChange = false;
3468 switch (BuiltinID) {
3469 default: llvm_unreachable("Unknown overloaded atomic builtin!");
3470 case Builtin::BI__sync_fetch_and_add:
3471 case Builtin::BI__sync_fetch_and_add_1:
3472 case Builtin::BI__sync_fetch_and_add_2:
3473 case Builtin::BI__sync_fetch_and_add_4:
3474 case Builtin::BI__sync_fetch_and_add_8:
3475 case Builtin::BI__sync_fetch_and_add_16:
3479 case Builtin::BI__sync_fetch_and_sub:
3480 case Builtin::BI__sync_fetch_and_sub_1:
3481 case Builtin::BI__sync_fetch_and_sub_2:
3482 case Builtin::BI__sync_fetch_and_sub_4:
3483 case Builtin::BI__sync_fetch_and_sub_8:
3484 case Builtin::BI__sync_fetch_and_sub_16:
3488 case Builtin::BI__sync_fetch_and_or:
3489 case Builtin::BI__sync_fetch_and_or_1:
3490 case Builtin::BI__sync_fetch_and_or_2:
3491 case Builtin::BI__sync_fetch_and_or_4:
3492 case Builtin::BI__sync_fetch_and_or_8:
3493 case Builtin::BI__sync_fetch_and_or_16:
3497 case Builtin::BI__sync_fetch_and_and:
3498 case Builtin::BI__sync_fetch_and_and_1:
3499 case Builtin::BI__sync_fetch_and_and_2:
3500 case Builtin::BI__sync_fetch_and_and_4:
3501 case Builtin::BI__sync_fetch_and_and_8:
3502 case Builtin::BI__sync_fetch_and_and_16:
3506 case Builtin::BI__sync_fetch_and_xor:
3507 case Builtin::BI__sync_fetch_and_xor_1:
3508 case Builtin::BI__sync_fetch_and_xor_2:
3509 case Builtin::BI__sync_fetch_and_xor_4:
3510 case Builtin::BI__sync_fetch_and_xor_8:
3511 case Builtin::BI__sync_fetch_and_xor_16:
3515 case Builtin::BI__sync_fetch_and_nand:
3516 case Builtin::BI__sync_fetch_and_nand_1:
3517 case Builtin::BI__sync_fetch_and_nand_2:
3518 case Builtin::BI__sync_fetch_and_nand_4:
3519 case Builtin::BI__sync_fetch_and_nand_8:
3520 case Builtin::BI__sync_fetch_and_nand_16:
3522 WarnAboutSemanticsChange = true;
3525 case Builtin::BI__sync_add_and_fetch:
3526 case Builtin::BI__sync_add_and_fetch_1:
3527 case Builtin::BI__sync_add_and_fetch_2:
3528 case Builtin::BI__sync_add_and_fetch_4:
3529 case Builtin::BI__sync_add_and_fetch_8:
3530 case Builtin::BI__sync_add_and_fetch_16:
3534 case Builtin::BI__sync_sub_and_fetch:
3535 case Builtin::BI__sync_sub_and_fetch_1:
3536 case Builtin::BI__sync_sub_and_fetch_2:
3537 case Builtin::BI__sync_sub_and_fetch_4:
3538 case Builtin::BI__sync_sub_and_fetch_8:
3539 case Builtin::BI__sync_sub_and_fetch_16:
3543 case Builtin::BI__sync_and_and_fetch:
3544 case Builtin::BI__sync_and_and_fetch_1:
3545 case Builtin::BI__sync_and_and_fetch_2:
3546 case Builtin::BI__sync_and_and_fetch_4:
3547 case Builtin::BI__sync_and_and_fetch_8:
3548 case Builtin::BI__sync_and_and_fetch_16:
3552 case Builtin::BI__sync_or_and_fetch:
3553 case Builtin::BI__sync_or_and_fetch_1:
3554 case Builtin::BI__sync_or_and_fetch_2:
3555 case Builtin::BI__sync_or_and_fetch_4:
3556 case Builtin::BI__sync_or_and_fetch_8:
3557 case Builtin::BI__sync_or_and_fetch_16:
3561 case Builtin::BI__sync_xor_and_fetch:
3562 case Builtin::BI__sync_xor_and_fetch_1:
3563 case Builtin::BI__sync_xor_and_fetch_2:
3564 case Builtin::BI__sync_xor_and_fetch_4:
3565 case Builtin::BI__sync_xor_and_fetch_8:
3566 case Builtin::BI__sync_xor_and_fetch_16:
3570 case Builtin::BI__sync_nand_and_fetch:
3571 case Builtin::BI__sync_nand_and_fetch_1:
3572 case Builtin::BI__sync_nand_and_fetch_2:
3573 case Builtin::BI__sync_nand_and_fetch_4:
3574 case Builtin::BI__sync_nand_and_fetch_8:
3575 case Builtin::BI__sync_nand_and_fetch_16:
3577 WarnAboutSemanticsChange = true;
3580 case Builtin::BI__sync_val_compare_and_swap:
3581 case Builtin::BI__sync_val_compare_and_swap_1:
3582 case Builtin::BI__sync_val_compare_and_swap_2:
3583 case Builtin::BI__sync_val_compare_and_swap_4:
3584 case Builtin::BI__sync_val_compare_and_swap_8:
3585 case Builtin::BI__sync_val_compare_and_swap_16:
3590 case Builtin::BI__sync_bool_compare_and_swap:
3591 case Builtin::BI__sync_bool_compare_and_swap_1:
3592 case Builtin::BI__sync_bool_compare_and_swap_2:
3593 case Builtin::BI__sync_bool_compare_and_swap_4:
3594 case Builtin::BI__sync_bool_compare_and_swap_8:
3595 case Builtin::BI__sync_bool_compare_and_swap_16:
3598 ResultType = Context.BoolTy;
3601 case Builtin::BI__sync_lock_test_and_set:
3602 case Builtin::BI__sync_lock_test_and_set_1:
3603 case Builtin::BI__sync_lock_test_and_set_2:
3604 case Builtin::BI__sync_lock_test_and_set_4:
3605 case Builtin::BI__sync_lock_test_and_set_8:
3606 case Builtin::BI__sync_lock_test_and_set_16:
3610 case Builtin::BI__sync_lock_release:
3611 case Builtin::BI__sync_lock_release_1:
3612 case Builtin::BI__sync_lock_release_2:
3613 case Builtin::BI__sync_lock_release_4:
3614 case Builtin::BI__sync_lock_release_8:
3615 case Builtin::BI__sync_lock_release_16:
3618 ResultType = Context.VoidTy;
3621 case Builtin::BI__sync_swap:
3622 case Builtin::BI__sync_swap_1:
3623 case Builtin::BI__sync_swap_2:
3624 case Builtin::BI__sync_swap_4:
3625 case Builtin::BI__sync_swap_8:
3626 case Builtin::BI__sync_swap_16:
3631 // Now that we know how many fixed arguments we expect, first check that we
3632 // have at least that many.
3633 if (TheCall->getNumArgs() < 1+NumFixed) {
3634 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3635 << 0 << 1+NumFixed << TheCall->getNumArgs()
3636 << TheCall->getCallee()->getSourceRange();
3640 if (WarnAboutSemanticsChange) {
3641 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3642 << TheCall->getCallee()->getSourceRange();
3645 // Get the decl for the concrete builtin from this, we can tell what the
3646 // concrete integer type we should convert to is.
3647 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3648 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3649 FunctionDecl *NewBuiltinDecl;
3650 if (NewBuiltinID == BuiltinID)
3651 NewBuiltinDecl = FDecl;
3653 // Perform builtin lookup to avoid redeclaring it.
3654 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3655 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3656 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3657 assert(Res.getFoundDecl());
3658 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3659 if (!NewBuiltinDecl)
3663 // The first argument --- the pointer --- has a fixed type; we
3664 // deduce the types of the rest of the arguments accordingly. Walk
3665 // the remaining arguments, converting them to the deduced value type.
3666 for (unsigned i = 0; i != NumFixed; ++i) {
3667 ExprResult Arg = TheCall->getArg(i+1);
3669 // GCC does an implicit conversion to the pointer or integer ValType. This
3670 // can fail in some cases (1i -> int**), check for this error case now.
3671 // Initialize the argument.
3672 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3673 ValType, /*consume*/ false);
3674 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3675 if (Arg.isInvalid())
3678 // Okay, we have something that *can* be converted to the right type. Check
3679 // to see if there is a potentially weird extension going on here. This can
3680 // happen when you do an atomic operation on something like an char* and
3681 // pass in 42. The 42 gets converted to char. This is even more strange
3682 // for things like 45.123 -> char, etc.
3683 // FIXME: Do this check.
3684 TheCall->setArg(i+1, Arg.get());
3687 ASTContext& Context = this->getASTContext();
3689 // Create a new DeclRefExpr to refer to the new decl.
3690 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3692 DRE->getQualifierLoc(),
3695 /*enclosing*/ false,
3697 Context.BuiltinFnTy,
3698 DRE->getValueKind());
3700 // Set the callee in the CallExpr.
3701 // FIXME: This loses syntactic information.
3702 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3703 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3704 CK_BuiltinFnToFnPtr);
3705 TheCall->setCallee(PromotedCall.get());
3707 // Change the result type of the call to match the original value type. This
3708 // is arbitrary, but the codegen for these builtins ins design to handle it
3710 TheCall->setType(ResultType);
3712 return TheCallResult;
3715 /// SemaBuiltinNontemporalOverloaded - We have a call to
3716 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3717 /// overloaded function based on the pointer type of its last argument.
3719 /// This function goes through and does final semantic checking for these
3721 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3722 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3724 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3725 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3726 unsigned BuiltinID = FDecl->getBuiltinID();
3727 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3728 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3729 "Unexpected nontemporal load/store builtin!");
3730 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3731 unsigned numArgs = isStore ? 2 : 1;
3733 // Ensure that we have the proper number of arguments.
3734 if (checkArgCount(*this, TheCall, numArgs))
3737 // Inspect the last argument of the nontemporal builtin. This should always
3738 // be a pointer type, from which we imply the type of the memory access.
3739 // Because it is a pointer type, we don't have to worry about any implicit
3741 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3742 ExprResult PointerArgResult =
3743 DefaultFunctionArrayLvalueConversion(PointerArg);
3745 if (PointerArgResult.isInvalid())
3747 PointerArg = PointerArgResult.get();
3748 TheCall->setArg(numArgs - 1, PointerArg);
3750 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3752 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3753 << PointerArg->getType() << PointerArg->getSourceRange();
3757 QualType ValType = pointerType->getPointeeType();
3759 // Strip any qualifiers off ValType.
3760 ValType = ValType.getUnqualifiedType();
3761 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3762 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3763 !ValType->isVectorType()) {
3764 Diag(DRE->getLocStart(),
3765 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3766 << PointerArg->getType() << PointerArg->getSourceRange();
3771 TheCall->setType(ValType);
3772 return TheCallResult;
3775 ExprResult ValArg = TheCall->getArg(0);
3776 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3777 Context, ValType, /*consume*/ false);
3778 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3779 if (ValArg.isInvalid())
3782 TheCall->setArg(0, ValArg.get());
3783 TheCall->setType(Context.VoidTy);
3784 return TheCallResult;
3787 /// CheckObjCString - Checks that the argument to the builtin
3788 /// CFString constructor is correct
3789 /// Note: It might also make sense to do the UTF-16 conversion here (would
3790 /// simplify the backend).
3791 bool Sema::CheckObjCString(Expr *Arg) {
3792 Arg = Arg->IgnoreParenCasts();
3793 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3795 if (!Literal || !Literal->isAscii()) {
3796 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3797 << Arg->getSourceRange();
3801 if (Literal->containsNonAsciiOrNull()) {
3802 StringRef String = Literal->getString();
3803 unsigned NumBytes = String.size();
3804 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3805 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3806 llvm::UTF16 *ToPtr = &ToBuf[0];
3808 llvm::ConversionResult Result =
3809 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3810 ToPtr + NumBytes, llvm::strictConversion);
3811 // Check for conversion failure.
3812 if (Result != llvm::conversionOK)
3813 Diag(Arg->getLocStart(),
3814 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3819 /// CheckObjCString - Checks that the format string argument to the os_log()
3820 /// and os_trace() functions is correct, and converts it to const char *.
3821 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3822 Arg = Arg->IgnoreParenCasts();
3823 auto *Literal = dyn_cast<StringLiteral>(Arg);
3825 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3826 Literal = ObjcLiteral->getString();
3830 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3832 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3833 << Arg->getSourceRange());
3836 ExprResult Result(Literal);
3837 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3838 InitializedEntity Entity =
3839 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3840 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3844 /// Check that the user is calling the appropriate va_start builtin for the
3845 /// target and calling convention.
3846 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3847 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3848 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3849 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3850 bool IsWindows = TT.isOSWindows();
3851 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3852 if (IsX64 || IsAArch64) {
3853 CallingConv CC = CC_C;
3854 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3855 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3857 // Don't allow this in System V ABI functions.
3858 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3859 return S.Diag(Fn->getLocStart(),
3860 diag::err_ms_va_start_used_in_sysv_function);
3862 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3863 // On x64 Windows, don't allow this in System V ABI functions.
3864 // (Yes, that means there's no corresponding way to support variadic
3865 // System V ABI functions on Windows.)
3866 if ((IsWindows && CC == CC_X86_64SysV) ||
3867 (!IsWindows && CC == CC_Win64))
3868 return S.Diag(Fn->getLocStart(),
3869 diag::err_va_start_used_in_wrong_abi_function)
3876 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3880 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3881 ParmVarDecl **LastParam = nullptr) {
3882 // Determine whether the current function, block, or obj-c method is variadic
3883 // and get its parameter list.
3884 bool IsVariadic = false;
3885 ArrayRef<ParmVarDecl *> Params;
3886 DeclContext *Caller = S.CurContext;
3887 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3888 IsVariadic = Block->isVariadic();
3889 Params = Block->parameters();
3890 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3891 IsVariadic = FD->isVariadic();
3892 Params = FD->parameters();
3893 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3894 IsVariadic = MD->isVariadic();
3895 // FIXME: This isn't correct for methods (results in bogus warning).
3896 Params = MD->parameters();
3897 } else if (isa<CapturedDecl>(Caller)) {
3898 // We don't support va_start in a CapturedDecl.
3899 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3902 // This must be some other declcontext that parses exprs.
3903 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3908 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3913 *LastParam = Params.empty() ? nullptr : Params.back();
3918 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3919 /// for validity. Emit an error and return true on failure; return false
3921 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3922 Expr *Fn = TheCall->getCallee();
3924 if (checkVAStartABI(*this, BuiltinID, Fn))
3927 if (TheCall->getNumArgs() > 2) {
3928 Diag(TheCall->getArg(2)->getLocStart(),
3929 diag::err_typecheck_call_too_many_args)
3930 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3931 << Fn->getSourceRange()
3932 << SourceRange(TheCall->getArg(2)->getLocStart(),
3933 (*(TheCall->arg_end()-1))->getLocEnd());
3937 if (TheCall->getNumArgs() < 2) {
3938 return Diag(TheCall->getLocEnd(),
3939 diag::err_typecheck_call_too_few_args_at_least)
3940 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3943 // Type-check the first argument normally.
3944 if (checkBuiltinArgument(*this, TheCall, 0))
3947 // Check that the current function is variadic, and get its last parameter.
3948 ParmVarDecl *LastParam;
3949 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3952 // Verify that the second argument to the builtin is the last argument of the
3953 // current function or method.
3954 bool SecondArgIsLastNamedArgument = false;
3955 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3957 // These are valid if SecondArgIsLastNamedArgument is false after the next
3960 SourceLocation ParamLoc;
3961 bool IsCRegister = false;
3963 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3964 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3965 SecondArgIsLastNamedArgument = PV == LastParam;
3967 Type = PV->getType();
3968 ParamLoc = PV->getLocation();
3970 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3974 if (!SecondArgIsLastNamedArgument)
3975 Diag(TheCall->getArg(1)->getLocStart(),
3976 diag::warn_second_arg_of_va_start_not_last_named_param);
3977 else if (IsCRegister || Type->isReferenceType() ||
3978 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3979 // Promotable integers are UB, but enumerations need a bit of
3980 // extra checking to see what their promotable type actually is.
3981 if (!Type->isPromotableIntegerType())
3983 if (!Type->isEnumeralType())
3985 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3987 Context.typesAreCompatible(ED->getPromotionType(), Type));
3989 unsigned Reason = 0;
3990 if (Type->isReferenceType()) Reason = 1;
3991 else if (IsCRegister) Reason = 2;
3992 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3993 Diag(ParamLoc, diag::note_parameter_type) << Type;
3996 TheCall->setType(Context.VoidTy);
4000 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
4001 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4002 // const char *named_addr);
4004 Expr *Func = Call->getCallee();
4006 if (Call->getNumArgs() < 3)
4007 return Diag(Call->getLocEnd(),
4008 diag::err_typecheck_call_too_few_args_at_least)
4009 << 0 /*function call*/ << 3 << Call->getNumArgs();
4011 // Type-check the first argument normally.
4012 if (checkBuiltinArgument(*this, Call, 0))
4015 // Check that the current function is variadic.
4016 if (checkVAStartIsInVariadicFunction(*this, Func))
4019 // __va_start on Windows does not validate the parameter qualifiers
4021 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4022 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4024 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4025 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4027 const QualType &ConstCharPtrTy =
4028 Context.getPointerType(Context.CharTy.withConst());
4029 if (!Arg1Ty->isPointerType() ||
4030 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4031 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4032 << Arg1->getType() << ConstCharPtrTy
4033 << 1 /* different class */
4034 << 0 /* qualifier difference */
4035 << 3 /* parameter mismatch */
4036 << 2 << Arg1->getType() << ConstCharPtrTy;
4038 const QualType SizeTy = Context.getSizeType();
4039 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4040 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4041 << Arg2->getType() << SizeTy
4042 << 1 /* different class */
4043 << 0 /* qualifier difference */
4044 << 3 /* parameter mismatch */
4045 << 3 << Arg2->getType() << SizeTy;
4050 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4051 /// friends. This is declared to take (...), so we have to check everything.
4052 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4053 if (TheCall->getNumArgs() < 2)
4054 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4055 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4056 if (TheCall->getNumArgs() > 2)
4057 return Diag(TheCall->getArg(2)->getLocStart(),
4058 diag::err_typecheck_call_too_many_args)
4059 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4060 << SourceRange(TheCall->getArg(2)->getLocStart(),
4061 (*(TheCall->arg_end()-1))->getLocEnd());
4063 ExprResult OrigArg0 = TheCall->getArg(0);
4064 ExprResult OrigArg1 = TheCall->getArg(1);
4066 // Do standard promotions between the two arguments, returning their common
4068 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4069 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4072 // Make sure any conversions are pushed back into the call; this is
4073 // type safe since unordered compare builtins are declared as "_Bool
4075 TheCall->setArg(0, OrigArg0.get());
4076 TheCall->setArg(1, OrigArg1.get());
4078 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4081 // If the common type isn't a real floating type, then the arguments were
4082 // invalid for this operation.
4083 if (Res.isNull() || !Res->isRealFloatingType())
4084 return Diag(OrigArg0.get()->getLocStart(),
4085 diag::err_typecheck_call_invalid_ordered_compare)
4086 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4087 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4092 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4093 /// __builtin_isnan and friends. This is declared to take (...), so we have
4094 /// to check everything. We expect the last argument to be a floating point
4096 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4097 if (TheCall->getNumArgs() < NumArgs)
4098 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4099 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4100 if (TheCall->getNumArgs() > NumArgs)
4101 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4102 diag::err_typecheck_call_too_many_args)
4103 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4104 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4105 (*(TheCall->arg_end()-1))->getLocEnd());
4107 Expr *OrigArg = TheCall->getArg(NumArgs-1);
4109 if (OrigArg->isTypeDependent())
4112 // This operation requires a non-_Complex floating-point number.
4113 if (!OrigArg->getType()->isRealFloatingType())
4114 return Diag(OrigArg->getLocStart(),
4115 diag::err_typecheck_call_invalid_unary_fp)
4116 << OrigArg->getType() << OrigArg->getSourceRange();
4118 // If this is an implicit conversion from float -> float or double, remove it.
4119 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4120 // Only remove standard FloatCasts, leaving other casts inplace
4121 if (Cast->getCastKind() == CK_FloatingCast) {
4122 Expr *CastArg = Cast->getSubExpr();
4123 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4124 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4125 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4126 "promotion from float to either float or double is the only expected cast here");
4127 Cast->setSubExpr(nullptr);
4128 TheCall->setArg(NumArgs-1, CastArg);
4136 // Customized Sema Checking for VSX builtins that have the following signature:
4137 // vector [...] builtinName(vector [...], vector [...], const int);
4138 // Which takes the same type of vectors (any legal vector type) for the first
4139 // two arguments and takes compile time constant for the third argument.
4140 // Example builtins are :
4141 // vector double vec_xxpermdi(vector double, vector double, int);
4142 // vector short vec_xxsldwi(vector short, vector short, int);
4143 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4144 unsigned ExpectedNumArgs = 3;
4145 if (TheCall->getNumArgs() < ExpectedNumArgs)
4146 return Diag(TheCall->getLocEnd(),
4147 diag::err_typecheck_call_too_few_args_at_least)
4148 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4149 << TheCall->getSourceRange();
4151 if (TheCall->getNumArgs() > ExpectedNumArgs)
4152 return Diag(TheCall->getLocEnd(),
4153 diag::err_typecheck_call_too_many_args_at_most)
4154 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4155 << TheCall->getSourceRange();
4157 // Check the third argument is a compile time constant
4159 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4160 return Diag(TheCall->getLocStart(),
4161 diag::err_vsx_builtin_nonconstant_argument)
4162 << 3 /* argument index */ << TheCall->getDirectCallee()
4163 << SourceRange(TheCall->getArg(2)->getLocStart(),
4164 TheCall->getArg(2)->getLocEnd());
4166 QualType Arg1Ty = TheCall->getArg(0)->getType();
4167 QualType Arg2Ty = TheCall->getArg(1)->getType();
4169 // Check the type of argument 1 and argument 2 are vectors.
4170 SourceLocation BuiltinLoc = TheCall->getLocStart();
4171 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4172 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4173 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4174 << TheCall->getDirectCallee()
4175 << SourceRange(TheCall->getArg(0)->getLocStart(),
4176 TheCall->getArg(1)->getLocEnd());
4179 // Check the first two arguments are the same type.
4180 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4181 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4182 << TheCall->getDirectCallee()
4183 << SourceRange(TheCall->getArg(0)->getLocStart(),
4184 TheCall->getArg(1)->getLocEnd());
4187 // When default clang type checking is turned off and the customized type
4188 // checking is used, the returning type of the function must be explicitly
4189 // set. Otherwise it is _Bool by default.
4190 TheCall->setType(Arg1Ty);
4195 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4196 // This is declared to take (...), so we have to check everything.
4197 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4198 if (TheCall->getNumArgs() < 2)
4199 return ExprError(Diag(TheCall->getLocEnd(),
4200 diag::err_typecheck_call_too_few_args_at_least)
4201 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4202 << TheCall->getSourceRange());
4204 // Determine which of the following types of shufflevector we're checking:
4205 // 1) unary, vector mask: (lhs, mask)
4206 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4207 QualType resType = TheCall->getArg(0)->getType();
4208 unsigned numElements = 0;
4210 if (!TheCall->getArg(0)->isTypeDependent() &&
4211 !TheCall->getArg(1)->isTypeDependent()) {
4212 QualType LHSType = TheCall->getArg(0)->getType();
4213 QualType RHSType = TheCall->getArg(1)->getType();
4215 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4216 return ExprError(Diag(TheCall->getLocStart(),
4217 diag::err_vec_builtin_non_vector)
4218 << TheCall->getDirectCallee()
4219 << SourceRange(TheCall->getArg(0)->getLocStart(),
4220 TheCall->getArg(1)->getLocEnd()));
4222 numElements = LHSType->getAs<VectorType>()->getNumElements();
4223 unsigned numResElements = TheCall->getNumArgs() - 2;
4225 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4226 // with mask. If so, verify that RHS is an integer vector type with the
4227 // same number of elts as lhs.
4228 if (TheCall->getNumArgs() == 2) {
4229 if (!RHSType->hasIntegerRepresentation() ||
4230 RHSType->getAs<VectorType>()->getNumElements() != numElements)
4231 return ExprError(Diag(TheCall->getLocStart(),
4232 diag::err_vec_builtin_incompatible_vector)
4233 << TheCall->getDirectCallee()
4234 << SourceRange(TheCall->getArg(1)->getLocStart(),
4235 TheCall->getArg(1)->getLocEnd()));
4236 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4237 return ExprError(Diag(TheCall->getLocStart(),
4238 diag::err_vec_builtin_incompatible_vector)
4239 << TheCall->getDirectCallee()
4240 << SourceRange(TheCall->getArg(0)->getLocStart(),
4241 TheCall->getArg(1)->getLocEnd()));
4242 } else if (numElements != numResElements) {
4243 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4244 resType = Context.getVectorType(eltType, numResElements,
4245 VectorType::GenericVector);
4249 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4250 if (TheCall->getArg(i)->isTypeDependent() ||
4251 TheCall->getArg(i)->isValueDependent())
4254 llvm::APSInt Result(32);
4255 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4256 return ExprError(Diag(TheCall->getLocStart(),
4257 diag::err_shufflevector_nonconstant_argument)
4258 << TheCall->getArg(i)->getSourceRange());
4260 // Allow -1 which will be translated to undef in the IR.
4261 if (Result.isSigned() && Result.isAllOnesValue())
4264 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4265 return ExprError(Diag(TheCall->getLocStart(),
4266 diag::err_shufflevector_argument_too_large)
4267 << TheCall->getArg(i)->getSourceRange());
4270 SmallVector<Expr*, 32> exprs;
4272 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4273 exprs.push_back(TheCall->getArg(i));
4274 TheCall->setArg(i, nullptr);
4277 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4278 TheCall->getCallee()->getLocStart(),
4279 TheCall->getRParenLoc());
4282 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4283 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4284 SourceLocation BuiltinLoc,
4285 SourceLocation RParenLoc) {
4286 ExprValueKind VK = VK_RValue;
4287 ExprObjectKind OK = OK_Ordinary;
4288 QualType DstTy = TInfo->getType();
4289 QualType SrcTy = E->getType();
4291 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4292 return ExprError(Diag(BuiltinLoc,
4293 diag::err_convertvector_non_vector)
4294 << E->getSourceRange());
4295 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4296 return ExprError(Diag(BuiltinLoc,
4297 diag::err_convertvector_non_vector_type));
4299 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4300 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4301 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4302 if (SrcElts != DstElts)
4303 return ExprError(Diag(BuiltinLoc,
4304 diag::err_convertvector_incompatible_vector)
4305 << E->getSourceRange());
4308 return new (Context)
4309 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4312 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4313 // This is declared to take (const void*, ...) and can take two
4314 // optional constant int args.
4315 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4316 unsigned NumArgs = TheCall->getNumArgs();
4319 return Diag(TheCall->getLocEnd(),
4320 diag::err_typecheck_call_too_many_args_at_most)
4321 << 0 /*function call*/ << 3 << NumArgs
4322 << TheCall->getSourceRange();
4324 // Argument 0 is checked for us and the remaining arguments must be
4325 // constant integers.
4326 for (unsigned i = 1; i != NumArgs; ++i)
4327 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4333 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4334 // __assume does not evaluate its arguments, and should warn if its argument
4335 // has side effects.
4336 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4337 Expr *Arg = TheCall->getArg(0);
4338 if (Arg->isInstantiationDependent()) return false;
4340 if (Arg->HasSideEffects(Context))
4341 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4342 << Arg->getSourceRange()
4343 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4348 /// Handle __builtin_alloca_with_align. This is declared
4349 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4351 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4352 // The alignment must be a constant integer.
4353 Expr *Arg = TheCall->getArg(1);
4355 // We can't check the value of a dependent argument.
4356 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4357 if (const auto *UE =
4358 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4359 if (UE->getKind() == UETT_AlignOf)
4360 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4361 << Arg->getSourceRange();
4363 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4365 if (!Result.isPowerOf2())
4366 return Diag(TheCall->getLocStart(),
4367 diag::err_alignment_not_power_of_two)
4368 << Arg->getSourceRange();
4370 if (Result < Context.getCharWidth())
4371 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4372 << (unsigned)Context.getCharWidth()
4373 << Arg->getSourceRange();
4375 if (Result > std::numeric_limits<int32_t>::max())
4376 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4377 << std::numeric_limits<int32_t>::max()
4378 << Arg->getSourceRange();
4384 /// Handle __builtin_assume_aligned. This is declared
4385 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4386 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4387 unsigned NumArgs = TheCall->getNumArgs();
4390 return Diag(TheCall->getLocEnd(),
4391 diag::err_typecheck_call_too_many_args_at_most)
4392 << 0 /*function call*/ << 3 << NumArgs
4393 << TheCall->getSourceRange();
4395 // The alignment must be a constant integer.
4396 Expr *Arg = TheCall->getArg(1);
4398 // We can't check the value of a dependent argument.
4399 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4400 llvm::APSInt Result;
4401 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4404 if (!Result.isPowerOf2())
4405 return Diag(TheCall->getLocStart(),
4406 diag::err_alignment_not_power_of_two)
4407 << Arg->getSourceRange();
4411 ExprResult Arg(TheCall->getArg(2));
4412 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4413 Context.getSizeType(), false);
4414 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4415 if (Arg.isInvalid()) return true;
4416 TheCall->setArg(2, Arg.get());
4422 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4423 unsigned BuiltinID =
4424 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4425 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4427 unsigned NumArgs = TheCall->getNumArgs();
4428 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4429 if (NumArgs < NumRequiredArgs) {
4430 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4431 << 0 /* function call */ << NumRequiredArgs << NumArgs
4432 << TheCall->getSourceRange();
4434 if (NumArgs >= NumRequiredArgs + 0x100) {
4435 return Diag(TheCall->getLocEnd(),
4436 diag::err_typecheck_call_too_many_args_at_most)
4437 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4438 << TheCall->getSourceRange();
4442 // For formatting call, check buffer arg.
4444 ExprResult Arg(TheCall->getArg(i));
4445 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4446 Context, Context.VoidPtrTy, false);
4447 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4448 if (Arg.isInvalid())
4450 TheCall->setArg(i, Arg.get());
4454 // Check string literal arg.
4455 unsigned FormatIdx = i;
4457 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4458 if (Arg.isInvalid())
4460 TheCall->setArg(i, Arg.get());
4464 // Make sure variadic args are scalar.
4465 unsigned FirstDataArg = i;
4466 while (i < NumArgs) {
4467 ExprResult Arg = DefaultVariadicArgumentPromotion(
4468 TheCall->getArg(i), VariadicFunction, nullptr);
4469 if (Arg.isInvalid())
4471 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4472 if (ArgSize.getQuantity() >= 0x100) {
4473 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4474 << i << (int)ArgSize.getQuantity() << 0xff
4475 << TheCall->getSourceRange();
4477 TheCall->setArg(i, Arg.get());
4481 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4482 // call to avoid duplicate diagnostics.
4484 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4485 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4486 bool Success = CheckFormatArguments(
4487 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4488 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4495 TheCall->setType(Context.getSizeType());
4497 TheCall->setType(Context.VoidPtrTy);
4502 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4503 /// TheCall is a constant expression.
4504 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4505 llvm::APSInt &Result) {
4506 Expr *Arg = TheCall->getArg(ArgNum);
4507 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4508 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4510 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4512 if (!Arg->isIntegerConstantExpr(Result, Context))
4513 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4514 << FDecl->getDeclName() << Arg->getSourceRange();
4519 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4520 /// TheCall is a constant expression in the range [Low, High].
4521 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4522 int Low, int High) {
4523 llvm::APSInt Result;
4525 // We can't check the value of a dependent argument.
4526 Expr *Arg = TheCall->getArg(ArgNum);
4527 if (Arg->isTypeDependent() || Arg->isValueDependent())
4530 // Check constant-ness first.
4531 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4534 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4535 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4536 << Low << High << Arg->getSourceRange();
4541 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4542 /// TheCall is a constant expression is a multiple of Num..
4543 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4545 llvm::APSInt Result;
4547 // We can't check the value of a dependent argument.
4548 Expr *Arg = TheCall->getArg(ArgNum);
4549 if (Arg->isTypeDependent() || Arg->isValueDependent())
4552 // Check constant-ness first.
4553 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4556 if (Result.getSExtValue() % Num != 0)
4557 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4558 << Num << Arg->getSourceRange();
4563 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4564 /// TheCall is an ARM/AArch64 special register string literal.
4565 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4566 int ArgNum, unsigned ExpectedFieldNum,
4568 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4569 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4570 BuiltinID == ARM::BI__builtin_arm_rsr ||
4571 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4572 BuiltinID == ARM::BI__builtin_arm_wsr ||
4573 BuiltinID == ARM::BI__builtin_arm_wsrp;
4574 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4575 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4576 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4577 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4578 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4579 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4580 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4582 // We can't check the value of a dependent argument.
4583 Expr *Arg = TheCall->getArg(ArgNum);
4584 if (Arg->isTypeDependent() || Arg->isValueDependent())
4587 // Check if the argument is a string literal.
4588 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4589 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4590 << Arg->getSourceRange();
4592 // Check the type of special register given.
4593 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4594 SmallVector<StringRef, 6> Fields;
4595 Reg.split(Fields, ":");
4597 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4598 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4599 << Arg->getSourceRange();
4601 // If the string is the name of a register then we cannot check that it is
4602 // valid here but if the string is of one the forms described in ACLE then we
4603 // can check that the supplied fields are integers and within the valid
4605 if (Fields.size() > 1) {
4606 bool FiveFields = Fields.size() == 5;
4608 bool ValidString = true;
4610 ValidString &= Fields[0].startswith_lower("cp") ||
4611 Fields[0].startswith_lower("p");
4614 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4616 ValidString &= Fields[2].startswith_lower("c");
4618 Fields[2] = Fields[2].drop_front(1);
4621 ValidString &= Fields[3].startswith_lower("c");
4623 Fields[3] = Fields[3].drop_front(1);
4627 SmallVector<int, 5> Ranges;
4629 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4631 Ranges.append({15, 7, 15});
4633 for (unsigned i=0; i<Fields.size(); ++i) {
4635 ValidString &= !Fields[i].getAsInteger(10, IntField);
4636 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4640 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4641 << Arg->getSourceRange();
4642 } else if (IsAArch64Builtin && Fields.size() == 1) {
4643 // If the register name is one of those that appear in the condition below
4644 // and the special register builtin being used is one of the write builtins,
4645 // then we require that the argument provided for writing to the register
4646 // is an integer constant expression. This is because it will be lowered to
4647 // an MSR (immediate) instruction, so we need to know the immediate at
4649 if (TheCall->getNumArgs() != 2)
4652 std::string RegLower = Reg.lower();
4653 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4654 RegLower != "pan" && RegLower != "uao")
4657 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4663 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4664 /// This checks that the target supports __builtin_longjmp and
4665 /// that val is a constant 1.
4666 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4667 if (!Context.getTargetInfo().hasSjLjLowering())
4668 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4669 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4671 Expr *Arg = TheCall->getArg(1);
4672 llvm::APSInt Result;
4674 // TODO: This is less than ideal. Overload this to take a value.
4675 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4679 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4680 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4685 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4686 /// This checks that the target supports __builtin_setjmp.
4687 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4688 if (!Context.getTargetInfo().hasSjLjLowering())
4689 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4690 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4696 class UncoveredArgHandler {
4697 enum { Unknown = -1, AllCovered = -2 };
4699 signed FirstUncoveredArg = Unknown;
4700 SmallVector<const Expr *, 4> DiagnosticExprs;
4703 UncoveredArgHandler() = default;
4705 bool hasUncoveredArg() const {
4706 return (FirstUncoveredArg >= 0);
4709 unsigned getUncoveredArg() const {
4710 assert(hasUncoveredArg() && "no uncovered argument");
4711 return FirstUncoveredArg;
4714 void setAllCovered() {
4715 // A string has been found with all arguments covered, so clear out
4717 DiagnosticExprs.clear();
4718 FirstUncoveredArg = AllCovered;
4721 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4722 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4724 // Don't update if a previous string covers all arguments.
4725 if (FirstUncoveredArg == AllCovered)
4728 // UncoveredArgHandler tracks the highest uncovered argument index
4729 // and with it all the strings that match this index.
4730 if (NewFirstUncoveredArg == FirstUncoveredArg)
4731 DiagnosticExprs.push_back(StrExpr);
4732 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4733 DiagnosticExprs.clear();
4734 DiagnosticExprs.push_back(StrExpr);
4735 FirstUncoveredArg = NewFirstUncoveredArg;
4739 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4742 enum StringLiteralCheckType {
4744 SLCT_UncheckedLiteral,
4750 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4751 BinaryOperatorKind BinOpKind,
4752 bool AddendIsRight) {
4753 unsigned BitWidth = Offset.getBitWidth();
4754 unsigned AddendBitWidth = Addend.getBitWidth();
4755 // There might be negative interim results.
4756 if (Addend.isUnsigned()) {
4757 Addend = Addend.zext(++AddendBitWidth);
4758 Addend.setIsSigned(true);
4760 // Adjust the bit width of the APSInts.
4761 if (AddendBitWidth > BitWidth) {
4762 Offset = Offset.sext(AddendBitWidth);
4763 BitWidth = AddendBitWidth;
4764 } else if (BitWidth > AddendBitWidth) {
4765 Addend = Addend.sext(BitWidth);
4769 llvm::APSInt ResOffset = Offset;
4770 if (BinOpKind == BO_Add)
4771 ResOffset = Offset.sadd_ov(Addend, Ov);
4773 assert(AddendIsRight && BinOpKind == BO_Sub &&
4774 "operator must be add or sub with addend on the right");
4775 ResOffset = Offset.ssub_ov(Addend, Ov);
4778 // We add an offset to a pointer here so we should support an offset as big as
4781 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4782 "index (intermediate) result too big");
4783 Offset = Offset.sext(2 * BitWidth);
4784 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4793 // This is a wrapper class around StringLiteral to support offsetted string
4794 // literals as format strings. It takes the offset into account when returning
4795 // the string and its length or the source locations to display notes correctly.
4796 class FormatStringLiteral {
4797 const StringLiteral *FExpr;
4801 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4802 : FExpr(fexpr), Offset(Offset) {}
4804 StringRef getString() const {
4805 return FExpr->getString().drop_front(Offset);
4808 unsigned getByteLength() const {
4809 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4812 unsigned getLength() const { return FExpr->getLength() - Offset; }
4813 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4815 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4817 QualType getType() const { return FExpr->getType(); }
4819 bool isAscii() const { return FExpr->isAscii(); }
4820 bool isWide() const { return FExpr->isWide(); }
4821 bool isUTF8() const { return FExpr->isUTF8(); }
4822 bool isUTF16() const { return FExpr->isUTF16(); }
4823 bool isUTF32() const { return FExpr->isUTF32(); }
4824 bool isPascal() const { return FExpr->isPascal(); }
4826 SourceLocation getLocationOfByte(
4827 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4828 const TargetInfo &Target, unsigned *StartToken = nullptr,
4829 unsigned *StartTokenByteOffset = nullptr) const {
4830 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4831 StartToken, StartTokenByteOffset);
4834 SourceLocation getLocStart() const LLVM_READONLY {
4835 return FExpr->getLocStart().getLocWithOffset(Offset);
4838 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4843 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4844 const Expr *OrigFormatExpr,
4845 ArrayRef<const Expr *> Args,
4846 bool HasVAListArg, unsigned format_idx,
4847 unsigned firstDataArg,
4848 Sema::FormatStringType Type,
4849 bool inFunctionCall,
4850 Sema::VariadicCallType CallType,
4851 llvm::SmallBitVector &CheckedVarArgs,
4852 UncoveredArgHandler &UncoveredArg);
4854 // Determine if an expression is a string literal or constant string.
4855 // If this function returns false on the arguments to a function expecting a
4856 // format string, we will usually need to emit a warning.
4857 // True string literals are then checked by CheckFormatString.
4858 static StringLiteralCheckType
4859 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4860 bool HasVAListArg, unsigned format_idx,
4861 unsigned firstDataArg, Sema::FormatStringType Type,
4862 Sema::VariadicCallType CallType, bool InFunctionCall,
4863 llvm::SmallBitVector &CheckedVarArgs,
4864 UncoveredArgHandler &UncoveredArg,
4865 llvm::APSInt Offset) {
4867 assert(Offset.isSigned() && "invalid offset");
4869 if (E->isTypeDependent() || E->isValueDependent())
4870 return SLCT_NotALiteral;
4872 E = E->IgnoreParenCasts();
4874 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4875 // Technically -Wformat-nonliteral does not warn about this case.
4876 // The behavior of printf and friends in this case is implementation
4877 // dependent. Ideally if the format string cannot be null then
4878 // it should have a 'nonnull' attribute in the function prototype.
4879 return SLCT_UncheckedLiteral;
4881 switch (E->getStmtClass()) {
4882 case Stmt::BinaryConditionalOperatorClass:
4883 case Stmt::ConditionalOperatorClass: {
4884 // The expression is a literal if both sub-expressions were, and it was
4885 // completely checked only if both sub-expressions were checked.
4886 const AbstractConditionalOperator *C =
4887 cast<AbstractConditionalOperator>(E);
4889 // Determine whether it is necessary to check both sub-expressions, for
4890 // example, because the condition expression is a constant that can be
4891 // evaluated at compile time.
4892 bool CheckLeft = true, CheckRight = true;
4895 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4902 // We need to maintain the offsets for the right and the left hand side
4903 // separately to check if every possible indexed expression is a valid
4904 // string literal. They might have different offsets for different string
4905 // literals in the end.
4906 StringLiteralCheckType Left;
4908 Left = SLCT_UncheckedLiteral;
4910 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4911 HasVAListArg, format_idx, firstDataArg,
4912 Type, CallType, InFunctionCall,
4913 CheckedVarArgs, UncoveredArg, Offset);
4914 if (Left == SLCT_NotALiteral || !CheckRight) {
4919 StringLiteralCheckType Right =
4920 checkFormatStringExpr(S, C->getFalseExpr(), Args,
4921 HasVAListArg, format_idx, firstDataArg,
4922 Type, CallType, InFunctionCall, CheckedVarArgs,
4923 UncoveredArg, Offset);
4925 return (CheckLeft && Left < Right) ? Left : Right;
4928 case Stmt::ImplicitCastExprClass:
4929 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4932 case Stmt::OpaqueValueExprClass:
4933 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4937 return SLCT_NotALiteral;
4939 case Stmt::PredefinedExprClass:
4940 // While __func__, etc., are technically not string literals, they
4941 // cannot contain format specifiers and thus are not a security
4943 return SLCT_UncheckedLiteral;
4945 case Stmt::DeclRefExprClass: {
4946 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4948 // As an exception, do not flag errors for variables binding to
4949 // const string literals.
4950 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4951 bool isConstant = false;
4952 QualType T = DR->getType();
4954 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4955 isConstant = AT->getElementType().isConstant(S.Context);
4956 } else if (const PointerType *PT = T->getAs<PointerType>()) {
4957 isConstant = T.isConstant(S.Context) &&
4958 PT->getPointeeType().isConstant(S.Context);
4959 } else if (T->isObjCObjectPointerType()) {
4960 // In ObjC, there is usually no "const ObjectPointer" type,
4961 // so don't check if the pointee type is constant.
4962 isConstant = T.isConstant(S.Context);
4966 if (const Expr *Init = VD->getAnyInitializer()) {
4967 // Look through initializers like const char c[] = { "foo" }
4968 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4969 if (InitList->isStringLiteralInit())
4970 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4972 return checkFormatStringExpr(S, Init, Args,
4973 HasVAListArg, format_idx,
4974 firstDataArg, Type, CallType,
4975 /*InFunctionCall*/ false, CheckedVarArgs,
4976 UncoveredArg, Offset);
4980 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4981 // special check to see if the format string is a function parameter
4982 // of the function calling the printf function. If the function
4983 // has an attribute indicating it is a printf-like function, then we
4984 // should suppress warnings concerning non-literals being used in a call
4985 // to a vprintf function. For example:
4988 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4990 // va_start(ap, fmt);
4991 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4995 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4996 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4997 int PVIndex = PV->getFunctionScopeIndex() + 1;
4998 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4999 // adjust for implicit parameter
5000 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5001 if (MD->isInstance())
5003 // We also check if the formats are compatible.
5004 // We can't pass a 'scanf' string to a 'printf' function.
5005 if (PVIndex == PVFormat->getFormatIdx() &&
5006 Type == S.GetFormatStringType(PVFormat))
5007 return SLCT_UncheckedLiteral;
5014 return SLCT_NotALiteral;
5017 case Stmt::CallExprClass:
5018 case Stmt::CXXMemberCallExprClass: {
5019 const CallExpr *CE = cast<CallExpr>(E);
5020 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5021 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5022 unsigned ArgIndex = FA->getFormatIdx();
5023 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5024 if (MD->isInstance())
5026 const Expr *Arg = CE->getArg(ArgIndex - 1);
5028 return checkFormatStringExpr(S, Arg, Args,
5029 HasVAListArg, format_idx, firstDataArg,
5030 Type, CallType, InFunctionCall,
5031 CheckedVarArgs, UncoveredArg, Offset);
5032 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5033 unsigned BuiltinID = FD->getBuiltinID();
5034 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5035 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5036 const Expr *Arg = CE->getArg(0);
5037 return checkFormatStringExpr(S, Arg, Args,
5038 HasVAListArg, format_idx,
5039 firstDataArg, Type, CallType,
5040 InFunctionCall, CheckedVarArgs,
5041 UncoveredArg, Offset);
5046 return SLCT_NotALiteral;
5048 case Stmt::ObjCMessageExprClass: {
5049 const auto *ME = cast<ObjCMessageExpr>(E);
5050 if (const auto *ND = ME->getMethodDecl()) {
5051 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5052 unsigned ArgIndex = FA->getFormatIdx();
5053 const Expr *Arg = ME->getArg(ArgIndex - 1);
5054 return checkFormatStringExpr(
5055 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5056 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5060 return SLCT_NotALiteral;
5062 case Stmt::ObjCStringLiteralClass:
5063 case Stmt::StringLiteralClass: {
5064 const StringLiteral *StrE = nullptr;
5066 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5067 StrE = ObjCFExpr->getString();
5069 StrE = cast<StringLiteral>(E);
5072 if (Offset.isNegative() || Offset > StrE->getLength()) {
5073 // TODO: It would be better to have an explicit warning for out of
5075 return SLCT_NotALiteral;
5077 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5078 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5079 firstDataArg, Type, InFunctionCall, CallType,
5080 CheckedVarArgs, UncoveredArg);
5081 return SLCT_CheckedLiteral;
5084 return SLCT_NotALiteral;
5086 case Stmt::BinaryOperatorClass: {
5087 llvm::APSInt LResult;
5088 llvm::APSInt RResult;
5090 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5092 // A string literal + an int offset is still a string literal.
5093 if (BinOp->isAdditiveOp()) {
5094 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5095 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5097 if (LIsInt != RIsInt) {
5098 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5101 if (BinOpKind == BO_Add) {
5102 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5103 E = BinOp->getRHS();
5107 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5108 E = BinOp->getLHS();
5114 return SLCT_NotALiteral;
5116 case Stmt::UnaryOperatorClass: {
5117 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5118 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5119 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
5120 llvm::APSInt IndexResult;
5121 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5122 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5128 return SLCT_NotALiteral;
5132 return SLCT_NotALiteral;
5136 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5137 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5138 .Case("scanf", FST_Scanf)
5139 .Cases("printf", "printf0", FST_Printf)
5140 .Cases("NSString", "CFString", FST_NSString)
5141 .Case("strftime", FST_Strftime)
5142 .Case("strfmon", FST_Strfmon)
5143 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5144 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5145 .Case("os_trace", FST_OSLog)
5146 .Case("os_log", FST_OSLog)
5147 .Default(FST_Unknown);
5150 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5151 /// functions) for correct use of format strings.
5152 /// Returns true if a format string has been fully checked.
5153 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5154 ArrayRef<const Expr *> Args,
5156 VariadicCallType CallType,
5157 SourceLocation Loc, SourceRange Range,
5158 llvm::SmallBitVector &CheckedVarArgs) {
5159 FormatStringInfo FSI;
5160 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5161 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5162 FSI.FirstDataArg, GetFormatStringType(Format),
5163 CallType, Loc, Range, CheckedVarArgs);
5167 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5168 bool HasVAListArg, unsigned format_idx,
5169 unsigned firstDataArg, FormatStringType Type,
5170 VariadicCallType CallType,
5171 SourceLocation Loc, SourceRange Range,
5172 llvm::SmallBitVector &CheckedVarArgs) {
5173 // CHECK: printf/scanf-like function is called with no format string.
5174 if (format_idx >= Args.size()) {
5175 Diag(Loc, diag::warn_missing_format_string) << Range;
5179 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5181 // CHECK: format string is not a string literal.
5183 // Dynamically generated format strings are difficult to
5184 // automatically vet at compile time. Requiring that format strings
5185 // are string literals: (1) permits the checking of format strings by
5186 // the compiler and thereby (2) can practically remove the source of
5187 // many format string exploits.
5189 // Format string can be either ObjC string (e.g. @"%d") or
5190 // C string (e.g. "%d")
5191 // ObjC string uses the same format specifiers as C string, so we can use
5192 // the same format string checking logic for both ObjC and C strings.
5193 UncoveredArgHandler UncoveredArg;
5194 StringLiteralCheckType CT =
5195 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5196 format_idx, firstDataArg, Type, CallType,
5197 /*IsFunctionCall*/ true, CheckedVarArgs,
5199 /*no string offset*/ llvm::APSInt(64, false) = 0);
5201 // Generate a diagnostic where an uncovered argument is detected.
5202 if (UncoveredArg.hasUncoveredArg()) {
5203 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5204 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5205 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5208 if (CT != SLCT_NotALiteral)
5209 // Literal format string found, check done!
5210 return CT == SLCT_CheckedLiteral;
5212 // Strftime is particular as it always uses a single 'time' argument,
5213 // so it is safe to pass a non-literal string.
5214 if (Type == FST_Strftime)
5217 // Do not emit diag when the string param is a macro expansion and the
5218 // format is either NSString or CFString. This is a hack to prevent
5219 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5220 // which are usually used in place of NS and CF string literals.
5221 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5222 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5225 // If there are no arguments specified, warn with -Wformat-security, otherwise
5226 // warn only with -Wformat-nonliteral.
5227 if (Args.size() == firstDataArg) {
5228 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5229 << OrigFormatExpr->getSourceRange();
5234 case FST_FreeBSDKPrintf:
5236 Diag(FormatLoc, diag::note_format_security_fixit)
5237 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5240 Diag(FormatLoc, diag::note_format_security_fixit)
5241 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5245 Diag(FormatLoc, diag::warn_format_nonliteral)
5246 << OrigFormatExpr->getSourceRange();
5253 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5256 const FormatStringLiteral *FExpr;
5257 const Expr *OrigFormatExpr;
5258 const Sema::FormatStringType FSType;
5259 const unsigned FirstDataArg;
5260 const unsigned NumDataArgs;
5261 const char *Beg; // Start of format string.
5262 const bool HasVAListArg;
5263 ArrayRef<const Expr *> Args;
5265 llvm::SmallBitVector CoveredArgs;
5266 bool usesPositionalArgs = false;
5267 bool atFirstArg = true;
5268 bool inFunctionCall;
5269 Sema::VariadicCallType CallType;
5270 llvm::SmallBitVector &CheckedVarArgs;
5271 UncoveredArgHandler &UncoveredArg;
5274 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5275 const Expr *origFormatExpr,
5276 const Sema::FormatStringType type, unsigned firstDataArg,
5277 unsigned numDataArgs, const char *beg, bool hasVAListArg,
5278 ArrayRef<const Expr *> Args, unsigned formatIdx,
5279 bool inFunctionCall, Sema::VariadicCallType callType,
5280 llvm::SmallBitVector &CheckedVarArgs,
5281 UncoveredArgHandler &UncoveredArg)
5282 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5283 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5284 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5285 inFunctionCall(inFunctionCall), CallType(callType),
5286 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5287 CoveredArgs.resize(numDataArgs);
5288 CoveredArgs.reset();
5291 void DoneProcessing();
5293 void HandleIncompleteSpecifier(const char *startSpecifier,
5294 unsigned specifierLen) override;
5296 void HandleInvalidLengthModifier(
5297 const analyze_format_string::FormatSpecifier &FS,
5298 const analyze_format_string::ConversionSpecifier &CS,
5299 const char *startSpecifier, unsigned specifierLen,
5302 void HandleNonStandardLengthModifier(
5303 const analyze_format_string::FormatSpecifier &FS,
5304 const char *startSpecifier, unsigned specifierLen);
5306 void HandleNonStandardConversionSpecifier(
5307 const analyze_format_string::ConversionSpecifier &CS,
5308 const char *startSpecifier, unsigned specifierLen);
5310 void HandlePosition(const char *startPos, unsigned posLen) override;
5312 void HandleInvalidPosition(const char *startSpecifier,
5313 unsigned specifierLen,
5314 analyze_format_string::PositionContext p) override;
5316 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5318 void HandleNullChar(const char *nullCharacter) override;
5320 template <typename Range>
5322 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5323 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5324 bool IsStringLocation, Range StringRange,
5325 ArrayRef<FixItHint> Fixit = None);
5328 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5329 const char *startSpec,
5330 unsigned specifierLen,
5331 const char *csStart, unsigned csLen);
5333 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5334 const char *startSpec,
5335 unsigned specifierLen);
5337 SourceRange getFormatStringRange();
5338 CharSourceRange getSpecifierRange(const char *startSpecifier,
5339 unsigned specifierLen);
5340 SourceLocation getLocationOfByte(const char *x);
5342 const Expr *getDataArg(unsigned i) const;
5344 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5345 const analyze_format_string::ConversionSpecifier &CS,
5346 const char *startSpecifier, unsigned specifierLen,
5349 template <typename Range>
5350 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5351 bool IsStringLocation, Range StringRange,
5352 ArrayRef<FixItHint> Fixit = None);
5357 SourceRange CheckFormatHandler::getFormatStringRange() {
5358 return OrigFormatExpr->getSourceRange();
5361 CharSourceRange CheckFormatHandler::
5362 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5363 SourceLocation Start = getLocationOfByte(startSpecifier);
5364 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5366 // Advance the end SourceLocation by one due to half-open ranges.
5367 End = End.getLocWithOffset(1);
5369 return CharSourceRange::getCharRange(Start, End);
5372 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5373 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5374 S.getLangOpts(), S.Context.getTargetInfo());
5377 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5378 unsigned specifierLen){
5379 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5380 getLocationOfByte(startSpecifier),
5381 /*IsStringLocation*/true,
5382 getSpecifierRange(startSpecifier, specifierLen));
5385 void CheckFormatHandler::HandleInvalidLengthModifier(
5386 const analyze_format_string::FormatSpecifier &FS,
5387 const analyze_format_string::ConversionSpecifier &CS,
5388 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5389 using namespace analyze_format_string;
5391 const LengthModifier &LM = FS.getLengthModifier();
5392 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5394 // See if we know how to fix this length modifier.
5395 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5397 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5398 getLocationOfByte(LM.getStart()),
5399 /*IsStringLocation*/true,
5400 getSpecifierRange(startSpecifier, specifierLen));
5402 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5403 << FixedLM->toString()
5404 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5408 if (DiagID == diag::warn_format_nonsensical_length)
5409 Hint = FixItHint::CreateRemoval(LMRange);
5411 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5412 getLocationOfByte(LM.getStart()),
5413 /*IsStringLocation*/true,
5414 getSpecifierRange(startSpecifier, specifierLen),
5419 void CheckFormatHandler::HandleNonStandardLengthModifier(
5420 const analyze_format_string::FormatSpecifier &FS,
5421 const char *startSpecifier, unsigned specifierLen) {
5422 using namespace analyze_format_string;
5424 const LengthModifier &LM = FS.getLengthModifier();
5425 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5427 // See if we know how to fix this length modifier.
5428 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5430 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5431 << LM.toString() << 0,
5432 getLocationOfByte(LM.getStart()),
5433 /*IsStringLocation*/true,
5434 getSpecifierRange(startSpecifier, specifierLen));
5436 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5437 << FixedLM->toString()
5438 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5441 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5442 << LM.toString() << 0,
5443 getLocationOfByte(LM.getStart()),
5444 /*IsStringLocation*/true,
5445 getSpecifierRange(startSpecifier, specifierLen));
5449 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5450 const analyze_format_string::ConversionSpecifier &CS,
5451 const char *startSpecifier, unsigned specifierLen) {
5452 using namespace analyze_format_string;
5454 // See if we know how to fix this conversion specifier.
5455 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5457 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5458 << CS.toString() << /*conversion specifier*/1,
5459 getLocationOfByte(CS.getStart()),
5460 /*IsStringLocation*/true,
5461 getSpecifierRange(startSpecifier, specifierLen));
5463 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5464 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5465 << FixedCS->toString()
5466 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5468 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5469 << CS.toString() << /*conversion specifier*/1,
5470 getLocationOfByte(CS.getStart()),
5471 /*IsStringLocation*/true,
5472 getSpecifierRange(startSpecifier, specifierLen));
5476 void CheckFormatHandler::HandlePosition(const char *startPos,
5478 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5479 getLocationOfByte(startPos),
5480 /*IsStringLocation*/true,
5481 getSpecifierRange(startPos, posLen));
5485 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5486 analyze_format_string::PositionContext p) {
5487 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5489 getLocationOfByte(startPos), /*IsStringLocation*/true,
5490 getSpecifierRange(startPos, posLen));
5493 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5495 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5496 getLocationOfByte(startPos),
5497 /*IsStringLocation*/true,
5498 getSpecifierRange(startPos, posLen));
5501 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5502 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5503 // The presence of a null character is likely an error.
5504 EmitFormatDiagnostic(
5505 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5506 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5507 getFormatStringRange());
5511 // Note that this may return NULL if there was an error parsing or building
5512 // one of the argument expressions.
5513 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5514 return Args[FirstDataArg + i];
5517 void CheckFormatHandler::DoneProcessing() {
5518 // Does the number of data arguments exceed the number of
5519 // format conversions in the format string?
5520 if (!HasVAListArg) {
5521 // Find any arguments that weren't covered.
5523 signed notCoveredArg = CoveredArgs.find_first();
5524 if (notCoveredArg >= 0) {
5525 assert((unsigned)notCoveredArg < NumDataArgs);
5526 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5528 UncoveredArg.setAllCovered();
5533 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5534 const Expr *ArgExpr) {
5535 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5541 SourceLocation Loc = ArgExpr->getLocStart();
5543 if (S.getSourceManager().isInSystemMacro(Loc))
5546 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5547 for (auto E : DiagnosticExprs)
5548 PDiag << E->getSourceRange();
5550 CheckFormatHandler::EmitFormatDiagnostic(
5551 S, IsFunctionCall, DiagnosticExprs[0],
5552 PDiag, Loc, /*IsStringLocation*/false,
5553 DiagnosticExprs[0]->getSourceRange());
5557 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5559 const char *startSpec,
5560 unsigned specifierLen,
5561 const char *csStart,
5563 bool keepGoing = true;
5564 if (argIndex < NumDataArgs) {
5565 // Consider the argument coverered, even though the specifier doesn't
5567 CoveredArgs.set(argIndex);
5570 // If argIndex exceeds the number of data arguments we
5571 // don't issue a warning because that is just a cascade of warnings (and
5572 // they may have intended '%%' anyway). We don't want to continue processing
5573 // the format string after this point, however, as we will like just get
5574 // gibberish when trying to match arguments.
5578 StringRef Specifier(csStart, csLen);
5580 // If the specifier in non-printable, it could be the first byte of a UTF-8
5581 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5583 std::string CodePointStr;
5584 if (!llvm::sys::locale::isPrint(*csStart)) {
5585 llvm::UTF32 CodePoint;
5586 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5587 const llvm::UTF8 *E =
5588 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5589 llvm::ConversionResult Result =
5590 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5592 if (Result != llvm::conversionOK) {
5593 unsigned char FirstChar = *csStart;
5594 CodePoint = (llvm::UTF32)FirstChar;
5597 llvm::raw_string_ostream OS(CodePointStr);
5598 if (CodePoint < 256)
5599 OS << "\\x" << llvm::format("%02x", CodePoint);
5600 else if (CodePoint <= 0xFFFF)
5601 OS << "\\u" << llvm::format("%04x", CodePoint);
5603 OS << "\\U" << llvm::format("%08x", CodePoint);
5605 Specifier = CodePointStr;
5608 EmitFormatDiagnostic(
5609 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5610 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5616 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5617 const char *startSpec,
5618 unsigned specifierLen) {
5619 EmitFormatDiagnostic(
5620 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5621 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5625 CheckFormatHandler::CheckNumArgs(
5626 const analyze_format_string::FormatSpecifier &FS,
5627 const analyze_format_string::ConversionSpecifier &CS,
5628 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5630 if (argIndex >= NumDataArgs) {
5631 PartialDiagnostic PDiag = FS.usesPositionalArg()
5632 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5633 << (argIndex+1) << NumDataArgs)
5634 : S.PDiag(diag::warn_printf_insufficient_data_args);
5635 EmitFormatDiagnostic(
5636 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5637 getSpecifierRange(startSpecifier, specifierLen));
5639 // Since more arguments than conversion tokens are given, by extension
5640 // all arguments are covered, so mark this as so.
5641 UncoveredArg.setAllCovered();
5647 template<typename Range>
5648 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5650 bool IsStringLocation,
5652 ArrayRef<FixItHint> FixIt) {
5653 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5654 Loc, IsStringLocation, StringRange, FixIt);
5657 /// \brief If the format string is not within the funcion call, emit a note
5658 /// so that the function call and string are in diagnostic messages.
5660 /// \param InFunctionCall if true, the format string is within the function
5661 /// call and only one diagnostic message will be produced. Otherwise, an
5662 /// extra note will be emitted pointing to location of the format string.
5664 /// \param ArgumentExpr the expression that is passed as the format string
5665 /// argument in the function call. Used for getting locations when two
5666 /// diagnostics are emitted.
5668 /// \param PDiag the callee should already have provided any strings for the
5669 /// diagnostic message. This function only adds locations and fixits
5672 /// \param Loc primary location for diagnostic. If two diagnostics are
5673 /// required, one will be at Loc and a new SourceLocation will be created for
5676 /// \param IsStringLocation if true, Loc points to the format string should be
5677 /// used for the note. Otherwise, Loc points to the argument list and will
5678 /// be used with PDiag.
5680 /// \param StringRange some or all of the string to highlight. This is
5681 /// templated so it can accept either a CharSourceRange or a SourceRange.
5683 /// \param FixIt optional fix it hint for the format string.
5684 template <typename Range>
5685 void CheckFormatHandler::EmitFormatDiagnostic(
5686 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5687 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5688 Range StringRange, ArrayRef<FixItHint> FixIt) {
5689 if (InFunctionCall) {
5690 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5694 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5695 << ArgumentExpr->getSourceRange();
5697 const Sema::SemaDiagnosticBuilder &Note =
5698 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5699 diag::note_format_string_defined);
5701 Note << StringRange;
5706 //===--- CHECK: Printf format string checking ------------------------------===//
5710 class CheckPrintfHandler : public CheckFormatHandler {
5712 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5713 const Expr *origFormatExpr,
5714 const Sema::FormatStringType type, unsigned firstDataArg,
5715 unsigned numDataArgs, bool isObjC, const char *beg,
5716 bool hasVAListArg, ArrayRef<const Expr *> Args,
5717 unsigned formatIdx, bool inFunctionCall,
5718 Sema::VariadicCallType CallType,
5719 llvm::SmallBitVector &CheckedVarArgs,
5720 UncoveredArgHandler &UncoveredArg)
5721 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5722 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5723 inFunctionCall, CallType, CheckedVarArgs,
5726 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5728 /// Returns true if '%@' specifiers are allowed in the format string.
5729 bool allowsObjCArg() const {
5730 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5731 FSType == Sema::FST_OSTrace;
5734 bool HandleInvalidPrintfConversionSpecifier(
5735 const analyze_printf::PrintfSpecifier &FS,
5736 const char *startSpecifier,
5737 unsigned specifierLen) override;
5739 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5740 const char *startSpecifier,
5741 unsigned specifierLen) override;
5742 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5743 const char *StartSpecifier,
5744 unsigned SpecifierLen,
5747 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5748 const char *startSpecifier, unsigned specifierLen);
5749 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5750 const analyze_printf::OptionalAmount &Amt,
5752 const char *startSpecifier, unsigned specifierLen);
5753 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5754 const analyze_printf::OptionalFlag &flag,
5755 const char *startSpecifier, unsigned specifierLen);
5756 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5757 const analyze_printf::OptionalFlag &ignoredFlag,
5758 const analyze_printf::OptionalFlag &flag,
5759 const char *startSpecifier, unsigned specifierLen);
5760 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5763 void HandleEmptyObjCModifierFlag(const char *startFlag,
5764 unsigned flagLen) override;
5766 void HandleInvalidObjCModifierFlag(const char *startFlag,
5767 unsigned flagLen) override;
5769 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5770 const char *flagsEnd,
5771 const char *conversionPosition)
5777 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5778 const analyze_printf::PrintfSpecifier &FS,
5779 const char *startSpecifier,
5780 unsigned specifierLen) {
5781 const analyze_printf::PrintfConversionSpecifier &CS =
5782 FS.getConversionSpecifier();
5784 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5785 getLocationOfByte(CS.getStart()),
5786 startSpecifier, specifierLen,
5787 CS.getStart(), CS.getLength());
5790 bool CheckPrintfHandler::HandleAmount(
5791 const analyze_format_string::OptionalAmount &Amt,
5792 unsigned k, const char *startSpecifier,
5793 unsigned specifierLen) {
5794 if (Amt.hasDataArgument()) {
5795 if (!HasVAListArg) {
5796 unsigned argIndex = Amt.getArgIndex();
5797 if (argIndex >= NumDataArgs) {
5798 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5800 getLocationOfByte(Amt.getStart()),
5801 /*IsStringLocation*/true,
5802 getSpecifierRange(startSpecifier, specifierLen));
5803 // Don't do any more checking. We will just emit
5808 // Type check the data argument. It should be an 'int'.
5809 // Although not in conformance with C99, we also allow the argument to be
5810 // an 'unsigned int' as that is a reasonably safe case. GCC also
5811 // doesn't emit a warning for that case.
5812 CoveredArgs.set(argIndex);
5813 const Expr *Arg = getDataArg(argIndex);
5817 QualType T = Arg->getType();
5819 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5820 assert(AT.isValid());
5822 if (!AT.matchesType(S.Context, T)) {
5823 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5824 << k << AT.getRepresentativeTypeName(S.Context)
5825 << T << Arg->getSourceRange(),
5826 getLocationOfByte(Amt.getStart()),
5827 /*IsStringLocation*/true,
5828 getSpecifierRange(startSpecifier, specifierLen));
5829 // Don't do any more checking. We will just emit
5838 void CheckPrintfHandler::HandleInvalidAmount(
5839 const analyze_printf::PrintfSpecifier &FS,
5840 const analyze_printf::OptionalAmount &Amt,
5842 const char *startSpecifier,
5843 unsigned specifierLen) {
5844 const analyze_printf::PrintfConversionSpecifier &CS =
5845 FS.getConversionSpecifier();
5848 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5849 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5850 Amt.getConstantLength()))
5853 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5854 << type << CS.toString(),
5855 getLocationOfByte(Amt.getStart()),
5856 /*IsStringLocation*/true,
5857 getSpecifierRange(startSpecifier, specifierLen),
5861 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5862 const analyze_printf::OptionalFlag &flag,
5863 const char *startSpecifier,
5864 unsigned specifierLen) {
5865 // Warn about pointless flag with a fixit removal.
5866 const analyze_printf::PrintfConversionSpecifier &CS =
5867 FS.getConversionSpecifier();
5868 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5869 << flag.toString() << CS.toString(),
5870 getLocationOfByte(flag.getPosition()),
5871 /*IsStringLocation*/true,
5872 getSpecifierRange(startSpecifier, specifierLen),
5873 FixItHint::CreateRemoval(
5874 getSpecifierRange(flag.getPosition(), 1)));
5877 void CheckPrintfHandler::HandleIgnoredFlag(
5878 const analyze_printf::PrintfSpecifier &FS,
5879 const analyze_printf::OptionalFlag &ignoredFlag,
5880 const analyze_printf::OptionalFlag &flag,
5881 const char *startSpecifier,
5882 unsigned specifierLen) {
5883 // Warn about ignored flag with a fixit removal.
5884 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5885 << ignoredFlag.toString() << flag.toString(),
5886 getLocationOfByte(ignoredFlag.getPosition()),
5887 /*IsStringLocation*/true,
5888 getSpecifierRange(startSpecifier, specifierLen),
5889 FixItHint::CreateRemoval(
5890 getSpecifierRange(ignoredFlag.getPosition(), 1)));
5893 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5895 // Warn about an empty flag.
5896 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5897 getLocationOfByte(startFlag),
5898 /*IsStringLocation*/true,
5899 getSpecifierRange(startFlag, flagLen));
5902 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5904 // Warn about an invalid flag.
5905 auto Range = getSpecifierRange(startFlag, flagLen);
5906 StringRef flag(startFlag, flagLen);
5907 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5908 getLocationOfByte(startFlag),
5909 /*IsStringLocation*/true,
5910 Range, FixItHint::CreateRemoval(Range));
5913 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5914 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5915 // Warn about using '[...]' without a '@' conversion.
5916 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5917 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5918 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5919 getLocationOfByte(conversionPosition),
5920 /*IsStringLocation*/true,
5921 Range, FixItHint::CreateRemoval(Range));
5924 // Determines if the specified is a C++ class or struct containing
5925 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5927 template<typename MemberKind>
5928 static llvm::SmallPtrSet<MemberKind*, 1>
5929 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5930 const RecordType *RT = Ty->getAs<RecordType>();
5931 llvm::SmallPtrSet<MemberKind*, 1> Results;
5935 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5936 if (!RD || !RD->getDefinition())
5939 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5940 Sema::LookupMemberName);
5941 R.suppressDiagnostics();
5943 // We just need to include all members of the right kind turned up by the
5944 // filter, at this point.
5945 if (S.LookupQualifiedName(R, RT->getDecl()))
5946 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5947 NamedDecl *decl = (*I)->getUnderlyingDecl();
5948 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5954 /// Check if we could call '.c_str()' on an object.
5956 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5957 /// allow the call, or if it would be ambiguous).
5958 bool Sema::hasCStrMethod(const Expr *E) {
5959 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5962 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5963 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5965 if ((*MI)->getMinRequiredArguments() == 0)
5970 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5971 // better diagnostic if so. AT is assumed to be valid.
5972 // Returns true when a c_str() conversion method is found.
5973 bool CheckPrintfHandler::checkForCStrMembers(
5974 const analyze_printf::ArgType &AT, const Expr *E) {
5975 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5978 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5980 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5982 const CXXMethodDecl *Method = *MI;
5983 if (Method->getMinRequiredArguments() == 0 &&
5984 AT.matchesType(S.Context, Method->getReturnType())) {
5985 // FIXME: Suggest parens if the expression needs them.
5986 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5987 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5989 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5998 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
6000 const char *startSpecifier,
6001 unsigned specifierLen) {
6002 using namespace analyze_format_string;
6003 using namespace analyze_printf;
6005 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
6007 if (FS.consumesDataArgument()) {
6010 usesPositionalArgs = FS.usesPositionalArg();
6012 else if (usesPositionalArgs != FS.usesPositionalArg()) {
6013 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6014 startSpecifier, specifierLen);
6019 // First check if the field width, precision, and conversion specifier
6020 // have matching data arguments.
6021 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6022 startSpecifier, specifierLen)) {
6026 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6027 startSpecifier, specifierLen)) {
6031 if (!CS.consumesDataArgument()) {
6032 // FIXME: Technically specifying a precision or field width here
6033 // makes no sense. Worth issuing a warning at some point.
6037 // Consume the argument.
6038 unsigned argIndex = FS.getArgIndex();
6039 if (argIndex < NumDataArgs) {
6040 // The check to see if the argIndex is valid will come later.
6041 // We set the bit here because we may exit early from this
6042 // function if we encounter some other error.
6043 CoveredArgs.set(argIndex);
6046 // FreeBSD kernel extensions.
6047 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6048 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6049 // We need at least two arguments.
6050 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6053 // Claim the second argument.
6054 CoveredArgs.set(argIndex + 1);
6056 // Type check the first argument (int for %b, pointer for %D)
6057 const Expr *Ex = getDataArg(argIndex);
6058 const analyze_printf::ArgType &AT =
6059 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6060 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6061 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6062 EmitFormatDiagnostic(
6063 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6064 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6065 << false << Ex->getSourceRange(),
6066 Ex->getLocStart(), /*IsStringLocation*/false,
6067 getSpecifierRange(startSpecifier, specifierLen));
6069 // Type check the second argument (char * for both %b and %D)
6070 Ex = getDataArg(argIndex + 1);
6071 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6072 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6073 EmitFormatDiagnostic(
6074 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6075 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6076 << false << Ex->getSourceRange(),
6077 Ex->getLocStart(), /*IsStringLocation*/false,
6078 getSpecifierRange(startSpecifier, specifierLen));
6083 // Check for using an Objective-C specific conversion specifier
6084 // in a non-ObjC literal.
6085 if (!allowsObjCArg() && CS.isObjCArg()) {
6086 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6090 // %P can only be used with os_log.
6091 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6092 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6096 // %n is not allowed with os_log.
6097 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6098 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6099 getLocationOfByte(CS.getStart()),
6100 /*IsStringLocation*/ false,
6101 getSpecifierRange(startSpecifier, specifierLen));
6106 // Only scalars are allowed for os_trace.
6107 if (FSType == Sema::FST_OSTrace &&
6108 (CS.getKind() == ConversionSpecifier::PArg ||
6109 CS.getKind() == ConversionSpecifier::sArg ||
6110 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6111 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6115 // Check for use of public/private annotation outside of os_log().
6116 if (FSType != Sema::FST_OSLog) {
6117 if (FS.isPublic().isSet()) {
6118 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6120 getLocationOfByte(FS.isPublic().getPosition()),
6121 /*IsStringLocation*/ false,
6122 getSpecifierRange(startSpecifier, specifierLen));
6124 if (FS.isPrivate().isSet()) {
6125 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6127 getLocationOfByte(FS.isPrivate().getPosition()),
6128 /*IsStringLocation*/ false,
6129 getSpecifierRange(startSpecifier, specifierLen));
6133 // Check for invalid use of field width
6134 if (!FS.hasValidFieldWidth()) {
6135 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6136 startSpecifier, specifierLen);
6139 // Check for invalid use of precision
6140 if (!FS.hasValidPrecision()) {
6141 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6142 startSpecifier, specifierLen);
6145 // Precision is mandatory for %P specifier.
6146 if (CS.getKind() == ConversionSpecifier::PArg &&
6147 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6148 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6149 getLocationOfByte(startSpecifier),
6150 /*IsStringLocation*/ false,
6151 getSpecifierRange(startSpecifier, specifierLen));
6154 // Check each flag does not conflict with any other component.
6155 if (!FS.hasValidThousandsGroupingPrefix())
6156 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6157 if (!FS.hasValidLeadingZeros())
6158 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6159 if (!FS.hasValidPlusPrefix())
6160 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6161 if (!FS.hasValidSpacePrefix())
6162 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6163 if (!FS.hasValidAlternativeForm())
6164 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6165 if (!FS.hasValidLeftJustified())
6166 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6168 // Check that flags are not ignored by another flag
6169 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6170 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6171 startSpecifier, specifierLen);
6172 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6173 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6174 startSpecifier, specifierLen);
6176 // Check the length modifier is valid with the given conversion specifier.
6177 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6178 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6179 diag::warn_format_nonsensical_length);
6180 else if (!FS.hasStandardLengthModifier())
6181 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6182 else if (!FS.hasStandardLengthConversionCombination())
6183 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6184 diag::warn_format_non_standard_conversion_spec);
6186 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6187 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6189 // The remaining checks depend on the data arguments.
6193 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6196 const Expr *Arg = getDataArg(argIndex);
6200 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6203 static bool requiresParensToAddCast(const Expr *E) {
6204 // FIXME: We should have a general way to reason about operator
6205 // precedence and whether parens are actually needed here.
6206 // Take care of a few common cases where they aren't.
6207 const Expr *Inside = E->IgnoreImpCasts();
6208 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6209 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6211 switch (Inside->getStmtClass()) {
6212 case Stmt::ArraySubscriptExprClass:
6213 case Stmt::CallExprClass:
6214 case Stmt::CharacterLiteralClass:
6215 case Stmt::CXXBoolLiteralExprClass:
6216 case Stmt::DeclRefExprClass:
6217 case Stmt::FloatingLiteralClass:
6218 case Stmt::IntegerLiteralClass:
6219 case Stmt::MemberExprClass:
6220 case Stmt::ObjCArrayLiteralClass:
6221 case Stmt::ObjCBoolLiteralExprClass:
6222 case Stmt::ObjCBoxedExprClass:
6223 case Stmt::ObjCDictionaryLiteralClass:
6224 case Stmt::ObjCEncodeExprClass:
6225 case Stmt::ObjCIvarRefExprClass:
6226 case Stmt::ObjCMessageExprClass:
6227 case Stmt::ObjCPropertyRefExprClass:
6228 case Stmt::ObjCStringLiteralClass:
6229 case Stmt::ObjCSubscriptRefExprClass:
6230 case Stmt::ParenExprClass:
6231 case Stmt::StringLiteralClass:
6232 case Stmt::UnaryOperatorClass:
6239 static std::pair<QualType, StringRef>
6240 shouldNotPrintDirectly(const ASTContext &Context,
6241 QualType IntendedTy,
6243 // Use a 'while' to peel off layers of typedefs.
6244 QualType TyTy = IntendedTy;
6245 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6246 StringRef Name = UserTy->getDecl()->getName();
6247 QualType CastTy = llvm::StringSwitch<QualType>(Name)
6248 .Case("CFIndex", Context.getNSIntegerType())
6249 .Case("NSInteger", Context.getNSIntegerType())
6250 .Case("NSUInteger", Context.getNSUIntegerType())
6251 .Case("SInt32", Context.IntTy)
6252 .Case("UInt32", Context.UnsignedIntTy)
6253 .Default(QualType());
6255 if (!CastTy.isNull())
6256 return std::make_pair(CastTy, Name);
6258 TyTy = UserTy->desugar();
6261 // Strip parens if necessary.
6262 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6263 return shouldNotPrintDirectly(Context,
6264 PE->getSubExpr()->getType(),
6267 // If this is a conditional expression, then its result type is constructed
6268 // via usual arithmetic conversions and thus there might be no necessary
6269 // typedef sugar there. Recurse to operands to check for NSInteger &
6270 // Co. usage condition.
6271 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6272 QualType TrueTy, FalseTy;
6273 StringRef TrueName, FalseName;
6275 std::tie(TrueTy, TrueName) =
6276 shouldNotPrintDirectly(Context,
6277 CO->getTrueExpr()->getType(),
6279 std::tie(FalseTy, FalseName) =
6280 shouldNotPrintDirectly(Context,
6281 CO->getFalseExpr()->getType(),
6282 CO->getFalseExpr());
6284 if (TrueTy == FalseTy)
6285 return std::make_pair(TrueTy, TrueName);
6286 else if (TrueTy.isNull())
6287 return std::make_pair(FalseTy, FalseName);
6288 else if (FalseTy.isNull())
6289 return std::make_pair(TrueTy, TrueName);
6292 return std::make_pair(QualType(), StringRef());
6296 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6297 const char *StartSpecifier,
6298 unsigned SpecifierLen,
6300 using namespace analyze_format_string;
6301 using namespace analyze_printf;
6303 // Now type check the data expression that matches the
6304 // format specifier.
6305 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6309 QualType ExprTy = E->getType();
6310 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6311 ExprTy = TET->getUnderlyingExpr()->getType();
6314 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6316 if (match == analyze_printf::ArgType::Match) {
6320 // Look through argument promotions for our error message's reported type.
6321 // This includes the integral and floating promotions, but excludes array
6322 // and function pointer decay; seeing that an argument intended to be a
6323 // string has type 'char [6]' is probably more confusing than 'char *'.
6324 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6325 if (ICE->getCastKind() == CK_IntegralCast ||
6326 ICE->getCastKind() == CK_FloatingCast) {
6327 E = ICE->getSubExpr();
6328 ExprTy = E->getType();
6330 // Check if we didn't match because of an implicit cast from a 'char'
6331 // or 'short' to an 'int'. This is done because printf is a varargs
6333 if (ICE->getType() == S.Context.IntTy ||
6334 ICE->getType() == S.Context.UnsignedIntTy) {
6335 // All further checking is done on the subexpression.
6336 if (AT.matchesType(S.Context, ExprTy))
6340 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6341 // Special case for 'a', which has type 'int' in C.
6342 // Note, however, that we do /not/ want to treat multibyte constants like
6343 // 'MooV' as characters! This form is deprecated but still exists.
6344 if (ExprTy == S.Context.IntTy)
6345 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6346 ExprTy = S.Context.CharTy;
6349 // Look through enums to their underlying type.
6350 bool IsEnum = false;
6351 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6352 ExprTy = EnumTy->getDecl()->getIntegerType();
6356 // %C in an Objective-C context prints a unichar, not a wchar_t.
6357 // If the argument is an integer of some kind, believe the %C and suggest
6358 // a cast instead of changing the conversion specifier.
6359 QualType IntendedTy = ExprTy;
6360 if (isObjCContext() &&
6361 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6362 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6363 !ExprTy->isCharType()) {
6364 // 'unichar' is defined as a typedef of unsigned short, but we should
6365 // prefer using the typedef if it is visible.
6366 IntendedTy = S.Context.UnsignedShortTy;
6368 // While we are here, check if the value is an IntegerLiteral that happens
6369 // to be within the valid range.
6370 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6371 const llvm::APInt &V = IL->getValue();
6372 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6376 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6377 Sema::LookupOrdinaryName);
6378 if (S.LookupName(Result, S.getCurScope())) {
6379 NamedDecl *ND = Result.getFoundDecl();
6380 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6381 if (TD->getUnderlyingType() == IntendedTy)
6382 IntendedTy = S.Context.getTypedefType(TD);
6387 // Special-case some of Darwin's platform-independence types by suggesting
6388 // casts to primitive types that are known to be large enough.
6389 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6390 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6392 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6393 if (!CastTy.isNull()) {
6394 IntendedTy = CastTy;
6395 ShouldNotPrintDirectly = true;
6399 // We may be able to offer a FixItHint if it is a supported type.
6400 PrintfSpecifier fixedFS = FS;
6402 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6405 // Get the fix string from the fixed format specifier
6406 SmallString<16> buf;
6407 llvm::raw_svector_ostream os(buf);
6408 fixedFS.toString(os);
6410 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6412 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6413 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6414 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6415 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6417 // In this case, the specifier is wrong and should be changed to match
6419 EmitFormatDiagnostic(S.PDiag(diag)
6420 << AT.getRepresentativeTypeName(S.Context)
6421 << IntendedTy << IsEnum << E->getSourceRange(),
6423 /*IsStringLocation*/ false, SpecRange,
6424 FixItHint::CreateReplacement(SpecRange, os.str()));
6426 // The canonical type for formatting this value is different from the
6427 // actual type of the expression. (This occurs, for example, with Darwin's
6428 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6429 // should be printed as 'long' for 64-bit compatibility.)
6430 // Rather than emitting a normal format/argument mismatch, we want to
6431 // add a cast to the recommended type (and correct the format string
6433 SmallString<16> CastBuf;
6434 llvm::raw_svector_ostream CastFix(CastBuf);
6436 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6439 SmallVector<FixItHint,4> Hints;
6440 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6441 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6443 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6444 // If there's already a cast present, just replace it.
6445 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6446 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6448 } else if (!requiresParensToAddCast(E)) {
6449 // If the expression has high enough precedence,
6450 // just write the C-style cast.
6451 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6454 // Otherwise, add parens around the expression as well as the cast.
6456 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6459 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6460 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6463 if (ShouldNotPrintDirectly) {
6464 // The expression has a type that should not be printed directly.
6465 // We extract the name from the typedef because we don't want to show
6466 // the underlying type in the diagnostic.
6468 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6469 Name = TypedefTy->getDecl()->getName();
6472 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6473 << Name << IntendedTy << IsEnum
6474 << E->getSourceRange(),
6475 E->getLocStart(), /*IsStringLocation=*/false,
6478 // In this case, the expression could be printed using a different
6479 // specifier, but we've decided that the specifier is probably correct
6480 // and we should cast instead. Just use the normal warning message.
6481 EmitFormatDiagnostic(
6482 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6483 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6484 << E->getSourceRange(),
6485 E->getLocStart(), /*IsStringLocation*/false,
6490 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6492 // Since the warning for passing non-POD types to variadic functions
6493 // was deferred until now, we emit a warning for non-POD
6495 switch (S.isValidVarArgType(ExprTy)) {
6496 case Sema::VAK_Valid:
6497 case Sema::VAK_ValidInCXX11: {
6498 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6499 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6500 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6503 EmitFormatDiagnostic(
6504 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6505 << IsEnum << CSR << E->getSourceRange(),
6506 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6509 case Sema::VAK_Undefined:
6510 case Sema::VAK_MSVCUndefined:
6511 EmitFormatDiagnostic(
6512 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6513 << S.getLangOpts().CPlusPlus11
6516 << AT.getRepresentativeTypeName(S.Context)
6518 << E->getSourceRange(),
6519 E->getLocStart(), /*IsStringLocation*/false, CSR);
6520 checkForCStrMembers(AT, E);
6523 case Sema::VAK_Invalid:
6524 if (ExprTy->isObjCObjectType())
6525 EmitFormatDiagnostic(
6526 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6527 << S.getLangOpts().CPlusPlus11
6530 << AT.getRepresentativeTypeName(S.Context)
6532 << E->getSourceRange(),
6533 E->getLocStart(), /*IsStringLocation*/false, CSR);
6535 // FIXME: If this is an initializer list, suggest removing the braces
6536 // or inserting a cast to the target type.
6537 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6538 << isa<InitListExpr>(E) << ExprTy << CallType
6539 << AT.getRepresentativeTypeName(S.Context)
6540 << E->getSourceRange();
6544 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6545 "format string specifier index out of range");
6546 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6552 //===--- CHECK: Scanf format string checking ------------------------------===//
6556 class CheckScanfHandler : public CheckFormatHandler {
6558 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6559 const Expr *origFormatExpr, Sema::FormatStringType type,
6560 unsigned firstDataArg, unsigned numDataArgs,
6561 const char *beg, bool hasVAListArg,
6562 ArrayRef<const Expr *> Args, unsigned formatIdx,
6563 bool inFunctionCall, Sema::VariadicCallType CallType,
6564 llvm::SmallBitVector &CheckedVarArgs,
6565 UncoveredArgHandler &UncoveredArg)
6566 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6567 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6568 inFunctionCall, CallType, CheckedVarArgs,
6571 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6572 const char *startSpecifier,
6573 unsigned specifierLen) override;
6575 bool HandleInvalidScanfConversionSpecifier(
6576 const analyze_scanf::ScanfSpecifier &FS,
6577 const char *startSpecifier,
6578 unsigned specifierLen) override;
6580 void HandleIncompleteScanList(const char *start, const char *end) override;
6585 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6587 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6588 getLocationOfByte(end), /*IsStringLocation*/true,
6589 getSpecifierRange(start, end - start));
6592 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6593 const analyze_scanf::ScanfSpecifier &FS,
6594 const char *startSpecifier,
6595 unsigned specifierLen) {
6596 const analyze_scanf::ScanfConversionSpecifier &CS =
6597 FS.getConversionSpecifier();
6599 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6600 getLocationOfByte(CS.getStart()),
6601 startSpecifier, specifierLen,
6602 CS.getStart(), CS.getLength());
6605 bool CheckScanfHandler::HandleScanfSpecifier(
6606 const analyze_scanf::ScanfSpecifier &FS,
6607 const char *startSpecifier,
6608 unsigned specifierLen) {
6609 using namespace analyze_scanf;
6610 using namespace analyze_format_string;
6612 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6614 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6615 // be used to decide if we are using positional arguments consistently.
6616 if (FS.consumesDataArgument()) {
6619 usesPositionalArgs = FS.usesPositionalArg();
6621 else if (usesPositionalArgs != FS.usesPositionalArg()) {
6622 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6623 startSpecifier, specifierLen);
6628 // Check if the field with is non-zero.
6629 const OptionalAmount &Amt = FS.getFieldWidth();
6630 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6631 if (Amt.getConstantAmount() == 0) {
6632 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6633 Amt.getConstantLength());
6634 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6635 getLocationOfByte(Amt.getStart()),
6636 /*IsStringLocation*/true, R,
6637 FixItHint::CreateRemoval(R));
6641 if (!FS.consumesDataArgument()) {
6642 // FIXME: Technically specifying a precision or field width here
6643 // makes no sense. Worth issuing a warning at some point.
6647 // Consume the argument.
6648 unsigned argIndex = FS.getArgIndex();
6649 if (argIndex < NumDataArgs) {
6650 // The check to see if the argIndex is valid will come later.
6651 // We set the bit here because we may exit early from this
6652 // function if we encounter some other error.
6653 CoveredArgs.set(argIndex);
6656 // Check the length modifier is valid with the given conversion specifier.
6657 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6658 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6659 diag::warn_format_nonsensical_length);
6660 else if (!FS.hasStandardLengthModifier())
6661 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6662 else if (!FS.hasStandardLengthConversionCombination())
6663 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6664 diag::warn_format_non_standard_conversion_spec);
6666 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6667 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6669 // The remaining checks depend on the data arguments.
6673 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6676 // Check that the argument type matches the format specifier.
6677 const Expr *Ex = getDataArg(argIndex);
6681 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6683 if (!AT.isValid()) {
6687 analyze_format_string::ArgType::MatchKind match =
6688 AT.matchesType(S.Context, Ex->getType());
6689 if (match == analyze_format_string::ArgType::Match) {
6693 ScanfSpecifier fixedFS = FS;
6694 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6695 S.getLangOpts(), S.Context);
6697 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6698 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6699 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6703 // Get the fix string from the fixed format specifier.
6704 SmallString<128> buf;
6705 llvm::raw_svector_ostream os(buf);
6706 fixedFS.toString(os);
6708 EmitFormatDiagnostic(
6709 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6710 << Ex->getType() << false << Ex->getSourceRange(),
6712 /*IsStringLocation*/ false,
6713 getSpecifierRange(startSpecifier, specifierLen),
6714 FixItHint::CreateReplacement(
6715 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6717 EmitFormatDiagnostic(S.PDiag(diag)
6718 << AT.getRepresentativeTypeName(S.Context)
6719 << Ex->getType() << false << Ex->getSourceRange(),
6721 /*IsStringLocation*/ false,
6722 getSpecifierRange(startSpecifier, specifierLen));
6728 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6729 const Expr *OrigFormatExpr,
6730 ArrayRef<const Expr *> Args,
6731 bool HasVAListArg, unsigned format_idx,
6732 unsigned firstDataArg,
6733 Sema::FormatStringType Type,
6734 bool inFunctionCall,
6735 Sema::VariadicCallType CallType,
6736 llvm::SmallBitVector &CheckedVarArgs,
6737 UncoveredArgHandler &UncoveredArg) {
6738 // CHECK: is the format string a wide literal?
6739 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6740 CheckFormatHandler::EmitFormatDiagnostic(
6741 S, inFunctionCall, Args[format_idx],
6742 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6743 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6747 // Str - The format string. NOTE: this is NOT null-terminated!
6748 StringRef StrRef = FExpr->getString();
6749 const char *Str = StrRef.data();
6750 // Account for cases where the string literal is truncated in a declaration.
6751 const ConstantArrayType *T =
6752 S.Context.getAsConstantArrayType(FExpr->getType());
6753 assert(T && "String literal not of constant array type!");
6754 size_t TypeSize = T->getSize().getZExtValue();
6755 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6756 const unsigned numDataArgs = Args.size() - firstDataArg;
6758 // Emit a warning if the string literal is truncated and does not contain an
6759 // embedded null character.
6760 if (TypeSize <= StrRef.size() &&
6761 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6762 CheckFormatHandler::EmitFormatDiagnostic(
6763 S, inFunctionCall, Args[format_idx],
6764 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6765 FExpr->getLocStart(),
6766 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6770 // CHECK: empty format string?
6771 if (StrLen == 0 && numDataArgs > 0) {
6772 CheckFormatHandler::EmitFormatDiagnostic(
6773 S, inFunctionCall, Args[format_idx],
6774 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6775 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6779 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6780 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6781 Type == Sema::FST_OSTrace) {
6782 CheckPrintfHandler H(
6783 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6784 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6785 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6786 CheckedVarArgs, UncoveredArg);
6788 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6790 S.Context.getTargetInfo(),
6791 Type == Sema::FST_FreeBSDKPrintf))
6793 } else if (Type == Sema::FST_Scanf) {
6794 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6795 numDataArgs, Str, HasVAListArg, Args, format_idx,
6796 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6798 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6800 S.Context.getTargetInfo()))
6802 } // TODO: handle other formats
6805 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6806 // Str - The format string. NOTE: this is NOT null-terminated!
6807 StringRef StrRef = FExpr->getString();
6808 const char *Str = StrRef.data();
6809 // Account for cases where the string literal is truncated in a declaration.
6810 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6811 assert(T && "String literal not of constant array type!");
6812 size_t TypeSize = T->getSize().getZExtValue();
6813 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6814 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6816 Context.getTargetInfo());
6819 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6821 // Returns the related absolute value function that is larger, of 0 if one
6823 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6824 switch (AbsFunction) {
6828 case Builtin::BI__builtin_abs:
6829 return Builtin::BI__builtin_labs;
6830 case Builtin::BI__builtin_labs:
6831 return Builtin::BI__builtin_llabs;
6832 case Builtin::BI__builtin_llabs:
6835 case Builtin::BI__builtin_fabsf:
6836 return Builtin::BI__builtin_fabs;
6837 case Builtin::BI__builtin_fabs:
6838 return Builtin::BI__builtin_fabsl;
6839 case Builtin::BI__builtin_fabsl:
6842 case Builtin::BI__builtin_cabsf:
6843 return Builtin::BI__builtin_cabs;
6844 case Builtin::BI__builtin_cabs:
6845 return Builtin::BI__builtin_cabsl;
6846 case Builtin::BI__builtin_cabsl:
6849 case Builtin::BIabs:
6850 return Builtin::BIlabs;
6851 case Builtin::BIlabs:
6852 return Builtin::BIllabs;
6853 case Builtin::BIllabs:
6856 case Builtin::BIfabsf:
6857 return Builtin::BIfabs;
6858 case Builtin::BIfabs:
6859 return Builtin::BIfabsl;
6860 case Builtin::BIfabsl:
6863 case Builtin::BIcabsf:
6864 return Builtin::BIcabs;
6865 case Builtin::BIcabs:
6866 return Builtin::BIcabsl;
6867 case Builtin::BIcabsl:
6872 // Returns the argument type of the absolute value function.
6873 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6878 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6879 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6880 if (Error != ASTContext::GE_None)
6883 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6887 if (FT->getNumParams() != 1)
6890 return FT->getParamType(0);
6893 // Returns the best absolute value function, or zero, based on type and
6894 // current absolute value function.
6895 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6896 unsigned AbsFunctionKind) {
6897 unsigned BestKind = 0;
6898 uint64_t ArgSize = Context.getTypeSize(ArgType);
6899 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6900 Kind = getLargerAbsoluteValueFunction(Kind)) {
6901 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6902 if (Context.getTypeSize(ParamType) >= ArgSize) {
6905 else if (Context.hasSameType(ParamType, ArgType)) {
6914 enum AbsoluteValueKind {
6920 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6921 if (T->isIntegralOrEnumerationType())
6923 if (T->isRealFloatingType())
6924 return AVK_Floating;
6925 if (T->isAnyComplexType())
6928 llvm_unreachable("Type not integer, floating, or complex");
6931 // Changes the absolute value function to a different type. Preserves whether
6932 // the function is a builtin.
6933 static unsigned changeAbsFunction(unsigned AbsKind,
6934 AbsoluteValueKind ValueKind) {
6935 switch (ValueKind) {
6940 case Builtin::BI__builtin_fabsf:
6941 case Builtin::BI__builtin_fabs:
6942 case Builtin::BI__builtin_fabsl:
6943 case Builtin::BI__builtin_cabsf:
6944 case Builtin::BI__builtin_cabs:
6945 case Builtin::BI__builtin_cabsl:
6946 return Builtin::BI__builtin_abs;
6947 case Builtin::BIfabsf:
6948 case Builtin::BIfabs:
6949 case Builtin::BIfabsl:
6950 case Builtin::BIcabsf:
6951 case Builtin::BIcabs:
6952 case Builtin::BIcabsl:
6953 return Builtin::BIabs;
6959 case Builtin::BI__builtin_abs:
6960 case Builtin::BI__builtin_labs:
6961 case Builtin::BI__builtin_llabs:
6962 case Builtin::BI__builtin_cabsf:
6963 case Builtin::BI__builtin_cabs:
6964 case Builtin::BI__builtin_cabsl:
6965 return Builtin::BI__builtin_fabsf;
6966 case Builtin::BIabs:
6967 case Builtin::BIlabs:
6968 case Builtin::BIllabs:
6969 case Builtin::BIcabsf:
6970 case Builtin::BIcabs:
6971 case Builtin::BIcabsl:
6972 return Builtin::BIfabsf;
6978 case Builtin::BI__builtin_abs:
6979 case Builtin::BI__builtin_labs:
6980 case Builtin::BI__builtin_llabs:
6981 case Builtin::BI__builtin_fabsf:
6982 case Builtin::BI__builtin_fabs:
6983 case Builtin::BI__builtin_fabsl:
6984 return Builtin::BI__builtin_cabsf;
6985 case Builtin::BIabs:
6986 case Builtin::BIlabs:
6987 case Builtin::BIllabs:
6988 case Builtin::BIfabsf:
6989 case Builtin::BIfabs:
6990 case Builtin::BIfabsl:
6991 return Builtin::BIcabsf;
6994 llvm_unreachable("Unable to convert function");
6997 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6998 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7002 switch (FDecl->getBuiltinID()) {
7005 case Builtin::BI__builtin_abs:
7006 case Builtin::BI__builtin_fabs:
7007 case Builtin::BI__builtin_fabsf:
7008 case Builtin::BI__builtin_fabsl:
7009 case Builtin::BI__builtin_labs:
7010 case Builtin::BI__builtin_llabs:
7011 case Builtin::BI__builtin_cabs:
7012 case Builtin::BI__builtin_cabsf:
7013 case Builtin::BI__builtin_cabsl:
7014 case Builtin::BIabs:
7015 case Builtin::BIlabs:
7016 case Builtin::BIllabs:
7017 case Builtin::BIfabs:
7018 case Builtin::BIfabsf:
7019 case Builtin::BIfabsl:
7020 case Builtin::BIcabs:
7021 case Builtin::BIcabsf:
7022 case Builtin::BIcabsl:
7023 return FDecl->getBuiltinID();
7025 llvm_unreachable("Unknown Builtin type");
7028 // If the replacement is valid, emit a note with replacement function.
7029 // Additionally, suggest including the proper header if not already included.
7030 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
7031 unsigned AbsKind, QualType ArgType) {
7032 bool EmitHeaderHint = true;
7033 const char *HeaderName = nullptr;
7034 const char *FunctionName = nullptr;
7035 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7036 FunctionName = "std::abs";
7037 if (ArgType->isIntegralOrEnumerationType()) {
7038 HeaderName = "cstdlib";
7039 } else if (ArgType->isRealFloatingType()) {
7040 HeaderName = "cmath";
7042 llvm_unreachable("Invalid Type");
7045 // Lookup all std::abs
7046 if (NamespaceDecl *Std = S.getStdNamespace()) {
7047 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
7048 R.suppressDiagnostics();
7049 S.LookupQualifiedName(R, Std);
7051 for (const auto *I : R) {
7052 const FunctionDecl *FDecl = nullptr;
7053 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7054 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7056 FDecl = dyn_cast<FunctionDecl>(I);
7061 // Found std::abs(), check that they are the right ones.
7062 if (FDecl->getNumParams() != 1)
7065 // Check that the parameter type can handle the argument.
7066 QualType ParamType = FDecl->getParamDecl(0)->getType();
7067 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7068 S.Context.getTypeSize(ArgType) <=
7069 S.Context.getTypeSize(ParamType)) {
7070 // Found a function, don't need the header hint.
7071 EmitHeaderHint = false;
7077 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7078 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7081 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7082 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7083 R.suppressDiagnostics();
7084 S.LookupName(R, S.getCurScope());
7086 if (R.isSingleResult()) {
7087 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7088 if (FD && FD->getBuiltinID() == AbsKind) {
7089 EmitHeaderHint = false;
7093 } else if (!R.empty()) {
7099 S.Diag(Loc, diag::note_replace_abs_function)
7100 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7105 if (!EmitHeaderHint)
7108 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7112 template <std::size_t StrLen>
7113 static bool IsStdFunction(const FunctionDecl *FDecl,
7114 const char (&Str)[StrLen]) {
7117 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7119 if (!FDecl->isInStdNamespace())
7125 // Warn when using the wrong abs() function.
7126 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7127 const FunctionDecl *FDecl) {
7128 if (Call->getNumArgs() != 1)
7131 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7132 bool IsStdAbs = IsStdFunction(FDecl, "abs");
7133 if (AbsKind == 0 && !IsStdAbs)
7136 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7137 QualType ParamType = Call->getArg(0)->getType();
7139 // Unsigned types cannot be negative. Suggest removing the absolute value
7141 if (ArgType->isUnsignedIntegerType()) {
7142 const char *FunctionName =
7143 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7144 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7145 Diag(Call->getExprLoc(), diag::note_remove_abs)
7147 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7151 // Taking the absolute value of a pointer is very suspicious, they probably
7152 // wanted to index into an array, dereference a pointer, call a function, etc.
7153 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7154 unsigned DiagType = 0;
7155 if (ArgType->isFunctionType())
7157 else if (ArgType->isArrayType())
7160 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7164 // std::abs has overloads which prevent most of the absolute value problems
7169 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7170 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7172 // The argument and parameter are the same kind. Check if they are the right
7174 if (ArgValueKind == ParamValueKind) {
7175 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7178 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7179 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7180 << FDecl << ArgType << ParamType;
7182 if (NewAbsKind == 0)
7185 emitReplacement(*this, Call->getExprLoc(),
7186 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7190 // ArgValueKind != ParamValueKind
7191 // The wrong type of absolute value function was used. Attempt to find the
7193 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7194 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7195 if (NewAbsKind == 0)
7198 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7199 << FDecl << ParamValueKind << ArgValueKind;
7201 emitReplacement(*this, Call->getExprLoc(),
7202 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7205 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7206 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7207 const FunctionDecl *FDecl) {
7208 if (!Call || !FDecl) return;
7210 // Ignore template specializations and macros.
7211 if (inTemplateInstantiation()) return;
7212 if (Call->getExprLoc().isMacroID()) return;
7214 // Only care about the one template argument, two function parameter std::max
7215 if (Call->getNumArgs() != 2) return;
7216 if (!IsStdFunction(FDecl, "max")) return;
7217 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7218 if (!ArgList) return;
7219 if (ArgList->size() != 1) return;
7221 // Check that template type argument is unsigned integer.
7222 const auto& TA = ArgList->get(0);
7223 if (TA.getKind() != TemplateArgument::Type) return;
7224 QualType ArgType = TA.getAsType();
7225 if (!ArgType->isUnsignedIntegerType()) return;
7227 // See if either argument is a literal zero.
7228 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7229 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7230 if (!MTE) return false;
7231 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7232 if (!Num) return false;
7233 if (Num->getValue() != 0) return false;
7237 const Expr *FirstArg = Call->getArg(0);
7238 const Expr *SecondArg = Call->getArg(1);
7239 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7240 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7242 // Only warn when exactly one argument is zero.
7243 if (IsFirstArgZero == IsSecondArgZero) return;
7245 SourceRange FirstRange = FirstArg->getSourceRange();
7246 SourceRange SecondRange = SecondArg->getSourceRange();
7248 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7250 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7251 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7253 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7254 SourceRange RemovalRange;
7255 if (IsFirstArgZero) {
7256 RemovalRange = SourceRange(FirstRange.getBegin(),
7257 SecondRange.getBegin().getLocWithOffset(-1));
7259 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7260 SecondRange.getEnd());
7263 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7264 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7265 << FixItHint::CreateRemoval(RemovalRange);
7268 //===--- CHECK: Standard memory functions ---------------------------------===//
7270 /// \brief Takes the expression passed to the size_t parameter of functions
7271 /// such as memcmp, strncat, etc and warns if it's a comparison.
7273 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7274 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7275 IdentifierInfo *FnName,
7276 SourceLocation FnLoc,
7277 SourceLocation RParenLoc) {
7278 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7282 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7283 if (!Size->isComparisonOp() && !Size->isLogicalOp())
7286 SourceRange SizeRange = Size->getSourceRange();
7287 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7288 << SizeRange << FnName;
7289 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7290 << FnName << FixItHint::CreateInsertion(
7291 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7292 << FixItHint::CreateRemoval(RParenLoc);
7293 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7294 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7295 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7301 /// \brief Determine whether the given type is or contains a dynamic class type
7302 /// (e.g., whether it has a vtable).
7303 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7304 bool &IsContained) {
7305 // Look through array types while ignoring qualifiers.
7306 const Type *Ty = T->getBaseElementTypeUnsafe();
7307 IsContained = false;
7309 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7310 RD = RD ? RD->getDefinition() : nullptr;
7311 if (!RD || RD->isInvalidDecl())
7314 if (RD->isDynamicClass())
7317 // Check all the fields. If any bases were dynamic, the class is dynamic.
7318 // It's impossible for a class to transitively contain itself by value, so
7319 // infinite recursion is impossible.
7320 for (auto *FD : RD->fields()) {
7322 if (const CXXRecordDecl *ContainedRD =
7323 getContainedDynamicClass(FD->getType(), SubContained)) {
7332 /// \brief If E is a sizeof expression, returns its argument expression,
7333 /// otherwise returns NULL.
7334 static const Expr *getSizeOfExprArg(const Expr *E) {
7335 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7336 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7337 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
7338 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7343 /// \brief If E is a sizeof expression, returns its argument type.
7344 static QualType getSizeOfArgType(const Expr *E) {
7345 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7346 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7347 if (SizeOf->getKind() == UETT_SizeOf)
7348 return SizeOf->getTypeOfArgument();
7353 /// \brief Check for dangerous or invalid arguments to memset().
7355 /// This issues warnings on known problematic, dangerous or unspecified
7356 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7359 /// \param Call The call expression to diagnose.
7360 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7362 IdentifierInfo *FnName) {
7365 // It is possible to have a non-standard definition of memset. Validate
7366 // we have enough arguments, and if not, abort further checking.
7367 unsigned ExpectedNumArgs =
7368 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7369 if (Call->getNumArgs() < ExpectedNumArgs)
7372 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7373 BId == Builtin::BIstrndup ? 1 : 2);
7375 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7376 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7378 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7379 Call->getLocStart(), Call->getRParenLoc()))
7382 // We have special checking when the length is a sizeof expression.
7383 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7384 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7385 llvm::FoldingSetNodeID SizeOfArgID;
7387 // Although widely used, 'bzero' is not a standard function. Be more strict
7388 // with the argument types before allowing diagnostics and only allow the
7389 // form bzero(ptr, sizeof(...)).
7390 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7391 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7394 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7395 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7396 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7398 QualType DestTy = Dest->getType();
7400 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7401 PointeeTy = DestPtrTy->getPointeeType();
7403 // Never warn about void type pointers. This can be used to suppress
7405 if (PointeeTy->isVoidType())
7408 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7409 // actually comparing the expressions for equality. Because computing the
7410 // expression IDs can be expensive, we only do this if the diagnostic is
7413 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7414 SizeOfArg->getExprLoc())) {
7415 // We only compute IDs for expressions if the warning is enabled, and
7416 // cache the sizeof arg's ID.
7417 if (SizeOfArgID == llvm::FoldingSetNodeID())
7418 SizeOfArg->Profile(SizeOfArgID, Context, true);
7419 llvm::FoldingSetNodeID DestID;
7420 Dest->Profile(DestID, Context, true);
7421 if (DestID == SizeOfArgID) {
7422 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7423 // over sizeof(src) as well.
7424 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7425 StringRef ReadableName = FnName->getName();
7427 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7428 if (UnaryOp->getOpcode() == UO_AddrOf)
7429 ActionIdx = 1; // If its an address-of operator, just remove it.
7430 if (!PointeeTy->isIncompleteType() &&
7431 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7432 ActionIdx = 2; // If the pointee's size is sizeof(char),
7433 // suggest an explicit length.
7435 // If the function is defined as a builtin macro, do not show macro
7437 SourceLocation SL = SizeOfArg->getExprLoc();
7438 SourceRange DSR = Dest->getSourceRange();
7439 SourceRange SSR = SizeOfArg->getSourceRange();
7440 SourceManager &SM = getSourceManager();
7442 if (SM.isMacroArgExpansion(SL)) {
7443 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7444 SL = SM.getSpellingLoc(SL);
7445 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7446 SM.getSpellingLoc(DSR.getEnd()));
7447 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7448 SM.getSpellingLoc(SSR.getEnd()));
7451 DiagRuntimeBehavior(SL, SizeOfArg,
7452 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7458 DiagRuntimeBehavior(SL, SizeOfArg,
7459 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7467 // Also check for cases where the sizeof argument is the exact same
7468 // type as the memory argument, and where it points to a user-defined
7470 if (SizeOfArgTy != QualType()) {
7471 if (PointeeTy->isRecordType() &&
7472 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7473 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7474 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7475 << FnName << SizeOfArgTy << ArgIdx
7476 << PointeeTy << Dest->getSourceRange()
7477 << LenExpr->getSourceRange());
7481 } else if (DestTy->isArrayType()) {
7485 if (PointeeTy == QualType())
7488 // Always complain about dynamic classes.
7490 if (const CXXRecordDecl *ContainedRD =
7491 getContainedDynamicClass(PointeeTy, IsContained)) {
7493 unsigned OperationType = 0;
7494 // "overwritten" if we're warning about the destination for any call
7495 // but memcmp; otherwise a verb appropriate to the call.
7496 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7497 if (BId == Builtin::BImemcpy)
7499 else if(BId == Builtin::BImemmove)
7501 else if (BId == Builtin::BImemcmp)
7505 DiagRuntimeBehavior(
7506 Dest->getExprLoc(), Dest,
7507 PDiag(diag::warn_dyn_class_memaccess)
7508 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7509 << FnName << IsContained << ContainedRD << OperationType
7510 << Call->getCallee()->getSourceRange());
7511 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7512 BId != Builtin::BImemset)
7513 DiagRuntimeBehavior(
7514 Dest->getExprLoc(), Dest,
7515 PDiag(diag::warn_arc_object_memaccess)
7516 << ArgIdx << FnName << PointeeTy
7517 << Call->getCallee()->getSourceRange());
7521 DiagRuntimeBehavior(
7522 Dest->getExprLoc(), Dest,
7523 PDiag(diag::note_bad_memaccess_silence)
7524 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7529 // A little helper routine: ignore addition and subtraction of integer literals.
7530 // This intentionally does not ignore all integer constant expressions because
7531 // we don't want to remove sizeof().
7532 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7533 Ex = Ex->IgnoreParenCasts();
7536 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7537 if (!BO || !BO->isAdditiveOp())
7540 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7541 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7543 if (isa<IntegerLiteral>(RHS))
7545 else if (isa<IntegerLiteral>(LHS))
7554 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7555 ASTContext &Context) {
7556 // Only handle constant-sized or VLAs, but not flexible members.
7557 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7558 // Only issue the FIXIT for arrays of size > 1.
7559 if (CAT->getSize().getSExtValue() <= 1)
7561 } else if (!Ty->isVariableArrayType()) {
7567 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7568 // be the size of the source, instead of the destination.
7569 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7570 IdentifierInfo *FnName) {
7572 // Don't crash if the user has the wrong number of arguments
7573 unsigned NumArgs = Call->getNumArgs();
7574 if ((NumArgs != 3) && (NumArgs != 4))
7577 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7578 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7579 const Expr *CompareWithSrc = nullptr;
7581 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7582 Call->getLocStart(), Call->getRParenLoc()))
7585 // Look for 'strlcpy(dst, x, sizeof(x))'
7586 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7587 CompareWithSrc = Ex;
7589 // Look for 'strlcpy(dst, x, strlen(x))'
7590 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7591 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7592 SizeCall->getNumArgs() == 1)
7593 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7597 if (!CompareWithSrc)
7600 // Determine if the argument to sizeof/strlen is equal to the source
7601 // argument. In principle there's all kinds of things you could do
7602 // here, for instance creating an == expression and evaluating it with
7603 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7604 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7608 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7609 if (!CompareWithSrcDRE ||
7610 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7613 const Expr *OriginalSizeArg = Call->getArg(2);
7614 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7615 << OriginalSizeArg->getSourceRange() << FnName;
7617 // Output a FIXIT hint if the destination is an array (rather than a
7618 // pointer to an array). This could be enhanced to handle some
7619 // pointers if we know the actual size, like if DstArg is 'array+2'
7620 // we could say 'sizeof(array)-2'.
7621 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7622 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7625 SmallString<128> sizeString;
7626 llvm::raw_svector_ostream OS(sizeString);
7628 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7631 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7632 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7636 /// Check if two expressions refer to the same declaration.
7637 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7638 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7639 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7640 return D1->getDecl() == D2->getDecl();
7644 static const Expr *getStrlenExprArg(const Expr *E) {
7645 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7646 const FunctionDecl *FD = CE->getDirectCallee();
7647 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7649 return CE->getArg(0)->IgnoreParenCasts();
7654 // Warn on anti-patterns as the 'size' argument to strncat.
7655 // The correct size argument should look like following:
7656 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7657 void Sema::CheckStrncatArguments(const CallExpr *CE,
7658 IdentifierInfo *FnName) {
7659 // Don't crash if the user has the wrong number of arguments.
7660 if (CE->getNumArgs() < 3)
7662 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7663 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7664 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7666 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7667 CE->getRParenLoc()))
7670 // Identify common expressions, which are wrongly used as the size argument
7671 // to strncat and may lead to buffer overflows.
7672 unsigned PatternType = 0;
7673 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7675 if (referToTheSameDecl(SizeOfArg, DstArg))
7678 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7680 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7681 if (BE->getOpcode() == BO_Sub) {
7682 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7683 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7684 // - sizeof(dst) - strlen(dst)
7685 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7686 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7688 // - sizeof(src) - (anything)
7689 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7694 if (PatternType == 0)
7697 // Generate the diagnostic.
7698 SourceLocation SL = LenArg->getLocStart();
7699 SourceRange SR = LenArg->getSourceRange();
7700 SourceManager &SM = getSourceManager();
7702 // If the function is defined as a builtin macro, do not show macro expansion.
7703 if (SM.isMacroArgExpansion(SL)) {
7704 SL = SM.getSpellingLoc(SL);
7705 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7706 SM.getSpellingLoc(SR.getEnd()));
7709 // Check if the destination is an array (rather than a pointer to an array).
7710 QualType DstTy = DstArg->getType();
7711 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7713 if (!isKnownSizeArray) {
7714 if (PatternType == 1)
7715 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7717 Diag(SL, diag::warn_strncat_src_size) << SR;
7721 if (PatternType == 1)
7722 Diag(SL, diag::warn_strncat_large_size) << SR;
7724 Diag(SL, diag::warn_strncat_src_size) << SR;
7726 SmallString<128> sizeString;
7727 llvm::raw_svector_ostream OS(sizeString);
7729 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7732 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7735 Diag(SL, diag::note_strncat_wrong_size)
7736 << FixItHint::CreateReplacement(SR, OS.str());
7739 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7741 static const Expr *EvalVal(const Expr *E,
7742 SmallVectorImpl<const DeclRefExpr *> &refVars,
7743 const Decl *ParentDecl);
7744 static const Expr *EvalAddr(const Expr *E,
7745 SmallVectorImpl<const DeclRefExpr *> &refVars,
7746 const Decl *ParentDecl);
7748 /// CheckReturnStackAddr - Check if a return statement returns the address
7749 /// of a stack variable.
7751 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7752 SourceLocation ReturnLoc) {
7753 const Expr *stackE = nullptr;
7754 SmallVector<const DeclRefExpr *, 8> refVars;
7756 // Perform checking for returned stack addresses, local blocks,
7757 // label addresses or references to temporaries.
7758 if (lhsType->isPointerType() ||
7759 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7760 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7761 } else if (lhsType->isReferenceType()) {
7762 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7766 return; // Nothing suspicious was found.
7768 // Parameters are initialized in the calling scope, so taking the address
7769 // of a parameter reference doesn't need a warning.
7770 for (auto *DRE : refVars)
7771 if (isa<ParmVarDecl>(DRE->getDecl()))
7774 SourceLocation diagLoc;
7775 SourceRange diagRange;
7776 if (refVars.empty()) {
7777 diagLoc = stackE->getLocStart();
7778 diagRange = stackE->getSourceRange();
7780 // We followed through a reference variable. 'stackE' contains the
7781 // problematic expression but we will warn at the return statement pointing
7782 // at the reference variable. We will later display the "trail" of
7783 // reference variables using notes.
7784 diagLoc = refVars[0]->getLocStart();
7785 diagRange = refVars[0]->getSourceRange();
7788 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7789 // address of local var
7790 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7791 << DR->getDecl()->getDeclName() << diagRange;
7792 } else if (isa<BlockExpr>(stackE)) { // local block.
7793 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7794 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7795 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7796 } else { // local temporary.
7797 // If there is an LValue->RValue conversion, then the value of the
7798 // reference type is used, not the reference.
7799 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7800 if (ICE->getCastKind() == CK_LValueToRValue) {
7804 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7805 << lhsType->isReferenceType() << diagRange;
7808 // Display the "trail" of reference variables that we followed until we
7809 // found the problematic expression using notes.
7810 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7811 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7812 // If this var binds to another reference var, show the range of the next
7813 // var, otherwise the var binds to the problematic expression, in which case
7814 // show the range of the expression.
7815 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7816 : stackE->getSourceRange();
7817 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7818 << VD->getDeclName() << range;
7822 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7823 /// check if the expression in a return statement evaluates to an address
7824 /// to a location on the stack, a local block, an address of a label, or a
7825 /// reference to local temporary. The recursion is used to traverse the
7826 /// AST of the return expression, with recursion backtracking when we
7827 /// encounter a subexpression that (1) clearly does not lead to one of the
7828 /// above problematic expressions (2) is something we cannot determine leads to
7829 /// a problematic expression based on such local checking.
7831 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
7832 /// the expression that they point to. Such variables are added to the
7833 /// 'refVars' vector so that we know what the reference variable "trail" was.
7835 /// EvalAddr processes expressions that are pointers that are used as
7836 /// references (and not L-values). EvalVal handles all other values.
7837 /// At the base case of the recursion is a check for the above problematic
7840 /// This implementation handles:
7842 /// * pointer-to-pointer casts
7843 /// * implicit conversions from array references to pointers
7844 /// * taking the address of fields
7845 /// * arbitrary interplay between "&" and "*" operators
7846 /// * pointer arithmetic from an address of a stack variable
7847 /// * taking the address of an array element where the array is on the stack
7848 static const Expr *EvalAddr(const Expr *E,
7849 SmallVectorImpl<const DeclRefExpr *> &refVars,
7850 const Decl *ParentDecl) {
7851 if (E->isTypeDependent())
7854 // We should only be called for evaluating pointer expressions.
7855 assert((E->getType()->isAnyPointerType() ||
7856 E->getType()->isBlockPointerType() ||
7857 E->getType()->isObjCQualifiedIdType()) &&
7858 "EvalAddr only works on pointers");
7860 E = E->IgnoreParens();
7862 // Our "symbolic interpreter" is just a dispatch off the currently
7863 // viewed AST node. We then recursively traverse the AST by calling
7864 // EvalAddr and EvalVal appropriately.
7865 switch (E->getStmtClass()) {
7866 case Stmt::DeclRefExprClass: {
7867 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7869 // If we leave the immediate function, the lifetime isn't about to end.
7870 if (DR->refersToEnclosingVariableOrCapture())
7873 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7874 // If this is a reference variable, follow through to the expression that
7876 if (V->hasLocalStorage() &&
7877 V->getType()->isReferenceType() && V->hasInit()) {
7878 // Add the reference variable to the "trail".
7879 refVars.push_back(DR);
7880 return EvalAddr(V->getInit(), refVars, ParentDecl);
7886 case Stmt::UnaryOperatorClass: {
7887 // The only unary operator that make sense to handle here
7888 // is AddrOf. All others don't make sense as pointers.
7889 const UnaryOperator *U = cast<UnaryOperator>(E);
7891 if (U->getOpcode() == UO_AddrOf)
7892 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7896 case Stmt::BinaryOperatorClass: {
7897 // Handle pointer arithmetic. All other binary operators are not valid
7899 const BinaryOperator *B = cast<BinaryOperator>(E);
7900 BinaryOperatorKind op = B->getOpcode();
7902 if (op != BO_Add && op != BO_Sub)
7905 const Expr *Base = B->getLHS();
7907 // Determine which argument is the real pointer base. It could be
7908 // the RHS argument instead of the LHS.
7909 if (!Base->getType()->isPointerType())
7912 assert(Base->getType()->isPointerType());
7913 return EvalAddr(Base, refVars, ParentDecl);
7916 // For conditional operators we need to see if either the LHS or RHS are
7917 // valid DeclRefExpr*s. If one of them is valid, we return it.
7918 case Stmt::ConditionalOperatorClass: {
7919 const ConditionalOperator *C = cast<ConditionalOperator>(E);
7921 // Handle the GNU extension for missing LHS.
7922 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7923 if (const Expr *LHSExpr = C->getLHS()) {
7924 // In C++, we can have a throw-expression, which has 'void' type.
7925 if (!LHSExpr->getType()->isVoidType())
7926 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7930 // In C++, we can have a throw-expression, which has 'void' type.
7931 if (C->getRHS()->getType()->isVoidType())
7934 return EvalAddr(C->getRHS(), refVars, ParentDecl);
7937 case Stmt::BlockExprClass:
7938 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7939 return E; // local block.
7942 case Stmt::AddrLabelExprClass:
7943 return E; // address of label.
7945 case Stmt::ExprWithCleanupsClass:
7946 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7949 // For casts, we need to handle conversions from arrays to
7950 // pointer values, and pointer-to-pointer conversions.
7951 case Stmt::ImplicitCastExprClass:
7952 case Stmt::CStyleCastExprClass:
7953 case Stmt::CXXFunctionalCastExprClass:
7954 case Stmt::ObjCBridgedCastExprClass:
7955 case Stmt::CXXStaticCastExprClass:
7956 case Stmt::CXXDynamicCastExprClass:
7957 case Stmt::CXXConstCastExprClass:
7958 case Stmt::CXXReinterpretCastExprClass: {
7959 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7960 switch (cast<CastExpr>(E)->getCastKind()) {
7961 case CK_LValueToRValue:
7963 case CK_BaseToDerived:
7964 case CK_DerivedToBase:
7965 case CK_UncheckedDerivedToBase:
7967 case CK_CPointerToObjCPointerCast:
7968 case CK_BlockPointerToObjCPointerCast:
7969 case CK_AnyPointerToBlockPointerCast:
7970 return EvalAddr(SubExpr, refVars, ParentDecl);
7972 case CK_ArrayToPointerDecay:
7973 return EvalVal(SubExpr, refVars, ParentDecl);
7976 if (SubExpr->getType()->isAnyPointerType() ||
7977 SubExpr->getType()->isBlockPointerType() ||
7978 SubExpr->getType()->isObjCQualifiedIdType())
7979 return EvalAddr(SubExpr, refVars, ParentDecl);
7988 case Stmt::MaterializeTemporaryExprClass:
7989 if (const Expr *Result =
7990 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7991 refVars, ParentDecl))
7995 // Everything else: we simply don't reason about them.
8001 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
8002 /// See the comments for EvalAddr for more details.
8003 static const Expr *EvalVal(const Expr *E,
8004 SmallVectorImpl<const DeclRefExpr *> &refVars,
8005 const Decl *ParentDecl) {
8007 // We should only be called for evaluating non-pointer expressions, or
8008 // expressions with a pointer type that are not used as references but
8010 // are l-values (e.g., DeclRefExpr with a pointer type).
8012 // Our "symbolic interpreter" is just a dispatch off the currently
8013 // viewed AST node. We then recursively traverse the AST by calling
8014 // EvalAddr and EvalVal appropriately.
8016 E = E->IgnoreParens();
8017 switch (E->getStmtClass()) {
8018 case Stmt::ImplicitCastExprClass: {
8019 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8020 if (IE->getValueKind() == VK_LValue) {
8021 E = IE->getSubExpr();
8027 case Stmt::ExprWithCleanupsClass:
8028 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8031 case Stmt::DeclRefExprClass: {
8032 // When we hit a DeclRefExpr we are looking at code that refers to a
8033 // variable's name. If it's not a reference variable we check if it has
8034 // local storage within the function, and if so, return the expression.
8035 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8037 // If we leave the immediate function, the lifetime isn't about to end.
8038 if (DR->refersToEnclosingVariableOrCapture())
8041 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8042 // Check if it refers to itself, e.g. "int& i = i;".
8043 if (V == ParentDecl)
8046 if (V->hasLocalStorage()) {
8047 if (!V->getType()->isReferenceType())
8050 // Reference variable, follow through to the expression that
8053 // Add the reference variable to the "trail".
8054 refVars.push_back(DR);
8055 return EvalVal(V->getInit(), refVars, V);
8063 case Stmt::UnaryOperatorClass: {
8064 // The only unary operator that make sense to handle here
8065 // is Deref. All others don't resolve to a "name." This includes
8066 // handling all sorts of rvalues passed to a unary operator.
8067 const UnaryOperator *U = cast<UnaryOperator>(E);
8069 if (U->getOpcode() == UO_Deref)
8070 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
8075 case Stmt::ArraySubscriptExprClass: {
8076 // Array subscripts are potential references to data on the stack. We
8077 // retrieve the DeclRefExpr* for the array variable if it indeed
8078 // has local storage.
8079 const auto *ASE = cast<ArraySubscriptExpr>(E);
8080 if (ASE->isTypeDependent())
8082 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8085 case Stmt::OMPArraySectionExprClass: {
8086 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8090 case Stmt::ConditionalOperatorClass: {
8091 // For conditional operators we need to see if either the LHS or RHS are
8092 // non-NULL Expr's. If one is non-NULL, we return it.
8093 const ConditionalOperator *C = cast<ConditionalOperator>(E);
8095 // Handle the GNU extension for missing LHS.
8096 if (const Expr *LHSExpr = C->getLHS()) {
8097 // In C++, we can have a throw-expression, which has 'void' type.
8098 if (!LHSExpr->getType()->isVoidType())
8099 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8103 // In C++, we can have a throw-expression, which has 'void' type.
8104 if (C->getRHS()->getType()->isVoidType())
8107 return EvalVal(C->getRHS(), refVars, ParentDecl);
8110 // Accesses to members are potential references to data on the stack.
8111 case Stmt::MemberExprClass: {
8112 const MemberExpr *M = cast<MemberExpr>(E);
8114 // Check for indirect access. We only want direct field accesses.
8118 // Check whether the member type is itself a reference, in which case
8119 // we're not going to refer to the member, but to what the member refers
8121 if (M->getMemberDecl()->getType()->isReferenceType())
8124 return EvalVal(M->getBase(), refVars, ParentDecl);
8127 case Stmt::MaterializeTemporaryExprClass:
8128 if (const Expr *Result =
8129 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8130 refVars, ParentDecl))
8135 // Check that we don't return or take the address of a reference to a
8136 // temporary. This is only useful in C++.
8137 if (!E->isTypeDependent() && E->isRValue())
8140 // Everything else: we simply don't reason about them.
8147 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8148 SourceLocation ReturnLoc,
8150 const AttrVec *Attrs,
8151 const FunctionDecl *FD) {
8152 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8154 // Check if the return value is null but should not be.
8155 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8156 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8157 CheckNonNullExpr(*this, RetValExp))
8158 Diag(ReturnLoc, diag::warn_null_ret)
8159 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8161 // C++11 [basic.stc.dynamic.allocation]p4:
8162 // If an allocation function declared with a non-throwing
8163 // exception-specification fails to allocate storage, it shall return
8164 // a null pointer. Any other allocation function that fails to allocate
8165 // storage shall indicate failure only by throwing an exception [...]
8167 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8168 if (Op == OO_New || Op == OO_Array_New) {
8169 const FunctionProtoType *Proto
8170 = FD->getType()->castAs<FunctionProtoType>();
8171 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8172 CheckNonNullExpr(*this, RetValExp))
8173 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8174 << FD << getLangOpts().CPlusPlus11;
8179 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8181 /// Check for comparisons of floating point operands using != and ==.
8182 /// Issue a warning if these are no self-comparisons, as they are not likely
8183 /// to do what the programmer intended.
8184 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8185 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8186 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8188 // Special case: check for x == x (which is OK).
8189 // Do not emit warnings for such cases.
8190 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8191 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8192 if (DRL->getDecl() == DRR->getDecl())
8195 // Special case: check for comparisons against literals that can be exactly
8196 // represented by APFloat. In such cases, do not emit a warning. This
8197 // is a heuristic: often comparison against such literals are used to
8198 // detect if a value in a variable has not changed. This clearly can
8199 // lead to false negatives.
8200 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8204 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8208 // Check for comparisons with builtin types.
8209 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8210 if (CL->getBuiltinCallee())
8213 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8214 if (CR->getBuiltinCallee())
8217 // Emit the diagnostic.
8218 Diag(Loc, diag::warn_floatingpoint_eq)
8219 << LHS->getSourceRange() << RHS->getSourceRange();
8222 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8223 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8227 /// Structure recording the 'active' range of an integer-valued
8230 /// The number of bits active in the int.
8233 /// True if the int is known not to have negative values.
8236 IntRange(unsigned Width, bool NonNegative)
8237 : Width(Width), NonNegative(NonNegative) {}
8239 /// Returns the range of the bool type.
8240 static IntRange forBoolType() {
8241 return IntRange(1, true);
8244 /// Returns the range of an opaque value of the given integral type.
8245 static IntRange forValueOfType(ASTContext &C, QualType T) {
8246 return forValueOfCanonicalType(C,
8247 T->getCanonicalTypeInternal().getTypePtr());
8250 /// Returns the range of an opaque value of a canonical integral type.
8251 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8252 assert(T->isCanonicalUnqualified());
8254 if (const VectorType *VT = dyn_cast<VectorType>(T))
8255 T = VT->getElementType().getTypePtr();
8256 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8257 T = CT->getElementType().getTypePtr();
8258 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8259 T = AT->getValueType().getTypePtr();
8261 if (!C.getLangOpts().CPlusPlus) {
8262 // For enum types in C code, use the underlying datatype.
8263 if (const EnumType *ET = dyn_cast<EnumType>(T))
8264 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8265 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8266 // For enum types in C++, use the known bit width of the enumerators.
8267 EnumDecl *Enum = ET->getDecl();
8268 // In C++11, enums can have a fixed underlying type. Use this type to
8269 // compute the range.
8270 if (Enum->isFixed()) {
8271 return IntRange(C.getIntWidth(QualType(T, 0)),
8272 !ET->isSignedIntegerOrEnumerationType());
8275 unsigned NumPositive = Enum->getNumPositiveBits();
8276 unsigned NumNegative = Enum->getNumNegativeBits();
8278 if (NumNegative == 0)
8279 return IntRange(NumPositive, true/*NonNegative*/);
8281 return IntRange(std::max(NumPositive + 1, NumNegative),
8282 false/*NonNegative*/);
8285 const BuiltinType *BT = cast<BuiltinType>(T);
8286 assert(BT->isInteger());
8288 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8291 /// Returns the "target" range of a canonical integral type, i.e.
8292 /// the range of values expressible in the type.
8294 /// This matches forValueOfCanonicalType except that enums have the
8295 /// full range of their type, not the range of their enumerators.
8296 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8297 assert(T->isCanonicalUnqualified());
8299 if (const VectorType *VT = dyn_cast<VectorType>(T))
8300 T = VT->getElementType().getTypePtr();
8301 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8302 T = CT->getElementType().getTypePtr();
8303 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8304 T = AT->getValueType().getTypePtr();
8305 if (const EnumType *ET = dyn_cast<EnumType>(T))
8306 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8308 const BuiltinType *BT = cast<BuiltinType>(T);
8309 assert(BT->isInteger());
8311 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8314 /// Returns the supremum of two ranges: i.e. their conservative merge.
8315 static IntRange join(IntRange L, IntRange R) {
8316 return IntRange(std::max(L.Width, R.Width),
8317 L.NonNegative && R.NonNegative);
8320 /// Returns the infinum of two ranges: i.e. their aggressive merge.
8321 static IntRange meet(IntRange L, IntRange R) {
8322 return IntRange(std::min(L.Width, R.Width),
8323 L.NonNegative || R.NonNegative);
8329 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8330 unsigned MaxWidth) {
8331 if (value.isSigned() && value.isNegative())
8332 return IntRange(value.getMinSignedBits(), false);
8334 if (value.getBitWidth() > MaxWidth)
8335 value = value.trunc(MaxWidth);
8337 // isNonNegative() just checks the sign bit without considering
8339 return IntRange(value.getActiveBits(), true);
8342 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8343 unsigned MaxWidth) {
8345 return GetValueRange(C, result.getInt(), MaxWidth);
8347 if (result.isVector()) {
8348 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8349 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8350 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8351 R = IntRange::join(R, El);
8356 if (result.isComplexInt()) {
8357 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8358 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8359 return IntRange::join(R, I);
8362 // This can happen with lossless casts to intptr_t of "based" lvalues.
8363 // Assume it might use arbitrary bits.
8364 // FIXME: The only reason we need to pass the type in here is to get
8365 // the sign right on this one case. It would be nice if APValue
8367 assert(result.isLValue() || result.isAddrLabelDiff());
8368 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8371 static QualType GetExprType(const Expr *E) {
8372 QualType Ty = E->getType();
8373 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8374 Ty = AtomicRHS->getValueType();
8378 /// Pseudo-evaluate the given integer expression, estimating the
8379 /// range of values it might take.
8381 /// \param MaxWidth - the width to which the value will be truncated
8382 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8383 E = E->IgnoreParens();
8385 // Try a full evaluation first.
8386 Expr::EvalResult result;
8387 if (E->EvaluateAsRValue(result, C))
8388 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8390 // I think we only want to look through implicit casts here; if the
8391 // user has an explicit widening cast, we should treat the value as
8392 // being of the new, wider type.
8393 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8394 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8395 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8397 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8399 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8400 CE->getCastKind() == CK_BooleanToSignedIntegral;
8402 // Assume that non-integer casts can span the full range of the type.
8404 return OutputTypeRange;
8407 = GetExprRange(C, CE->getSubExpr(),
8408 std::min(MaxWidth, OutputTypeRange.Width));
8410 // Bail out if the subexpr's range is as wide as the cast type.
8411 if (SubRange.Width >= OutputTypeRange.Width)
8412 return OutputTypeRange;
8414 // Otherwise, we take the smaller width, and we're non-negative if
8415 // either the output type or the subexpr is.
8416 return IntRange(SubRange.Width,
8417 SubRange.NonNegative || OutputTypeRange.NonNegative);
8420 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8421 // If we can fold the condition, just take that operand.
8423 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8424 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8425 : CO->getFalseExpr(),
8428 // Otherwise, conservatively merge.
8429 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8430 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8431 return IntRange::join(L, R);
8434 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8435 switch (BO->getOpcode()) {
8437 llvm_unreachable("builtin <=> should have class type");
8439 // Boolean-valued operations are single-bit and positive.
8448 return IntRange::forBoolType();
8450 // The type of the assignments is the type of the LHS, so the RHS
8451 // is not necessarily the same type.
8460 return IntRange::forValueOfType(C, GetExprType(E));
8462 // Simple assignments just pass through the RHS, which will have
8463 // been coerced to the LHS type.
8466 return GetExprRange(C, BO->getRHS(), MaxWidth);
8468 // Operations with opaque sources are black-listed.
8471 return IntRange::forValueOfType(C, GetExprType(E));
8473 // Bitwise-and uses the *infinum* of the two source ranges.
8476 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8477 GetExprRange(C, BO->getRHS(), MaxWidth));
8479 // Left shift gets black-listed based on a judgement call.
8481 // ...except that we want to treat '1 << (blah)' as logically
8482 // positive. It's an important idiom.
8483 if (IntegerLiteral *I
8484 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8485 if (I->getValue() == 1) {
8486 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8487 return IntRange(R.Width, /*NonNegative*/ true);
8493 return IntRange::forValueOfType(C, GetExprType(E));
8495 // Right shift by a constant can narrow its left argument.
8497 case BO_ShrAssign: {
8498 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8500 // If the shift amount is a positive constant, drop the width by
8503 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8504 shift.isNonNegative()) {
8505 unsigned zext = shift.getZExtValue();
8506 if (zext >= L.Width)
8507 L.Width = (L.NonNegative ? 0 : 1);
8515 // Comma acts as its right operand.
8517 return GetExprRange(C, BO->getRHS(), MaxWidth);
8519 // Black-list pointer subtractions.
8521 if (BO->getLHS()->getType()->isPointerType())
8522 return IntRange::forValueOfType(C, GetExprType(E));
8525 // The width of a division result is mostly determined by the size
8528 // Don't 'pre-truncate' the operands.
8529 unsigned opWidth = C.getIntWidth(GetExprType(E));
8530 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8532 // If the divisor is constant, use that.
8533 llvm::APSInt divisor;
8534 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8535 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8536 if (log2 >= L.Width)
8537 L.Width = (L.NonNegative ? 0 : 1);
8539 L.Width = std::min(L.Width - log2, MaxWidth);
8543 // Otherwise, just use the LHS's width.
8544 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8545 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8548 // The result of a remainder can't be larger than the result of
8551 // Don't 'pre-truncate' the operands.
8552 unsigned opWidth = C.getIntWidth(GetExprType(E));
8553 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8554 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8556 IntRange meet = IntRange::meet(L, R);
8557 meet.Width = std::min(meet.Width, MaxWidth);
8561 // The default behavior is okay for these.
8569 // The default case is to treat the operation as if it were closed
8570 // on the narrowest type that encompasses both operands.
8571 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8572 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8573 return IntRange::join(L, R);
8576 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8577 switch (UO->getOpcode()) {
8578 // Boolean-valued operations are white-listed.
8580 return IntRange::forBoolType();
8582 // Operations with opaque sources are black-listed.
8584 case UO_AddrOf: // should be impossible
8585 return IntRange::forValueOfType(C, GetExprType(E));
8588 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8592 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8593 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8595 if (const auto *BitField = E->getSourceBitField())
8596 return IntRange(BitField->getBitWidthValue(C),
8597 BitField->getType()->isUnsignedIntegerOrEnumerationType());
8599 return IntRange::forValueOfType(C, GetExprType(E));
8602 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
8603 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8606 /// Checks whether the given value, which currently has the given
8607 /// source semantics, has the same value when coerced through the
8608 /// target semantics.
8609 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8610 const llvm::fltSemantics &Src,
8611 const llvm::fltSemantics &Tgt) {
8612 llvm::APFloat truncated = value;
8615 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8616 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8618 return truncated.bitwiseIsEqual(value);
8621 /// Checks whether the given value, which currently has the given
8622 /// source semantics, has the same value when coerced through the
8623 /// target semantics.
8625 /// The value might be a vector of floats (or a complex number).
8626 static bool IsSameFloatAfterCast(const APValue &value,
8627 const llvm::fltSemantics &Src,
8628 const llvm::fltSemantics &Tgt) {
8629 if (value.isFloat())
8630 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8632 if (value.isVector()) {
8633 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8634 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8639 assert(value.isComplexFloat());
8640 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8641 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8644 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8646 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
8647 // Suppress cases where we are comparing against an enum constant.
8648 if (const DeclRefExpr *DR =
8649 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8650 if (isa<EnumConstantDecl>(DR->getDecl()))
8653 // Suppress cases where the '0' value is expanded from a macro.
8654 if (E->getLocStart().isMacroID())
8660 static bool isKnownToHaveUnsignedValue(Expr *E) {
8661 return E->getType()->isIntegerType() &&
8662 (!E->getType()->isSignedIntegerType() ||
8663 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8667 /// The promoted range of values of a type. In general this has the
8668 /// following structure:
8670 /// |-----------| . . . |-----------|
8672 /// Min HoleMin HoleMax Max
8674 /// ... where there is only a hole if a signed type is promoted to unsigned
8675 /// (in which case Min and Max are the smallest and largest representable
8677 struct PromotedRange {
8678 // Min, or HoleMax if there is a hole.
8679 llvm::APSInt PromotedMin;
8680 // Max, or HoleMin if there is a hole.
8681 llvm::APSInt PromotedMax;
8683 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8685 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8686 else if (R.Width >= BitWidth && !Unsigned) {
8687 // Promotion made the type *narrower*. This happens when promoting
8688 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8689 // Treat all values of 'signed int' as being in range for now.
8690 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8691 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8693 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8694 .extOrTrunc(BitWidth);
8695 PromotedMin.setIsUnsigned(Unsigned);
8697 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8698 .extOrTrunc(BitWidth);
8699 PromotedMax.setIsUnsigned(Unsigned);
8703 // Determine whether this range is contiguous (has no hole).
8704 bool isContiguous() const { return PromotedMin <= PromotedMax; }
8706 // Where a constant value is within the range.
8707 enum ComparisonResult {
8716 Less = LE | LT | NE,
8717 Min = LE | InRangeFlag,
8718 InRange = InRangeFlag,
8719 Max = GE | InRangeFlag,
8720 Greater = GE | GT | NE,
8722 OnlyValue = LE | GE | EQ | InRangeFlag,
8726 ComparisonResult compare(const llvm::APSInt &Value) const {
8727 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8728 Value.isUnsigned() == PromotedMin.isUnsigned());
8729 if (!isContiguous()) {
8730 assert(Value.isUnsigned() && "discontiguous range for signed compare");
8731 if (Value.isMinValue()) return Min;
8732 if (Value.isMaxValue()) return Max;
8733 if (Value >= PromotedMin) return InRange;
8734 if (Value <= PromotedMax) return InRange;
8738 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8739 case -1: return Less;
8740 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8742 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8743 case -1: return InRange;
8745 case 1: return Greater;
8749 llvm_unreachable("impossible compare result");
8752 static llvm::Optional<StringRef>
8753 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
8755 ComparisonResult LTFlag = LT, GTFlag = GT;
8756 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8758 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
8759 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
8760 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
8764 ComparisonResult TrueFlag, FalseFlag;
8768 } else if (Op == BO_NE) {
8772 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8779 if (Op == BO_GE || Op == BO_LE)
8780 std::swap(TrueFlag, FalseFlag);
8783 return StringRef("true");
8785 return StringRef("false");
8791 static bool HasEnumType(Expr *E) {
8792 // Strip off implicit integral promotions.
8793 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8794 if (ICE->getCastKind() != CK_IntegralCast &&
8795 ICE->getCastKind() != CK_NoOp)
8797 E = ICE->getSubExpr();
8800 return E->getType()->isEnumeralType();
8803 static int classifyConstantValue(Expr *Constant) {
8804 // The values of this enumeration are used in the diagnostics
8805 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8806 enum ConstantValueKind {
8811 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8812 return BL->getValue() ? ConstantValueKind::LiteralTrue
8813 : ConstantValueKind::LiteralFalse;
8814 return ConstantValueKind::Miscellaneous;
8817 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8818 Expr *Constant, Expr *Other,
8819 const llvm::APSInt &Value,
8821 if (S.inTemplateInstantiation())
8824 Expr *OriginalOther = Other;
8826 Constant = Constant->IgnoreParenImpCasts();
8827 Other = Other->IgnoreParenImpCasts();
8829 // Suppress warnings on tautological comparisons between values of the same
8830 // enumeration type. There are only two ways we could warn on this:
8831 // - If the constant is outside the range of representable values of
8832 // the enumeration. In such a case, we should warn about the cast
8833 // to enumeration type, not about the comparison.
8834 // - If the constant is the maximum / minimum in-range value. For an
8835 // enumeratin type, such comparisons can be meaningful and useful.
8836 if (Constant->getType()->isEnumeralType() &&
8837 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8840 // TODO: Investigate using GetExprRange() to get tighter bounds
8841 // on the bit ranges.
8842 QualType OtherT = Other->getType();
8843 if (const auto *AT = OtherT->getAs<AtomicType>())
8844 OtherT = AT->getValueType();
8845 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8847 // Whether we're treating Other as being a bool because of the form of
8848 // expression despite it having another type (typically 'int' in C).
8849 bool OtherIsBooleanDespiteType =
8850 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
8851 if (OtherIsBooleanDespiteType)
8852 OtherRange = IntRange::forBoolType();
8854 // Determine the promoted range of the other type and see if a comparison of
8855 // the constant against that range is tautological.
8856 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
8857 Value.isUnsigned());
8858 auto Cmp = OtherPromotedRange.compare(Value);
8859 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
8863 // Suppress the diagnostic for an in-range comparison if the constant comes
8864 // from a macro or enumerator. We don't want to diagnose
8866 // some_long_value <= INT_MAX
8868 // when sizeof(int) == sizeof(long).
8869 bool InRange = Cmp & PromotedRange::InRangeFlag;
8870 if (InRange && IsEnumConstOrFromMacro(S, Constant))
8873 // If this is a comparison to an enum constant, include that
8874 // constant in the diagnostic.
8875 const EnumConstantDecl *ED = nullptr;
8876 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8877 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8879 // Should be enough for uint128 (39 decimal digits)
8880 SmallString<64> PrettySourceValue;
8881 llvm::raw_svector_ostream OS(PrettySourceValue);
8883 OS << '\'' << *ED << "' (" << Value << ")";
8887 // FIXME: We use a somewhat different formatting for the in-range cases and
8888 // cases involving boolean values for historical reasons. We should pick a
8889 // consistent way of presenting these diagnostics.
8890 if (!InRange || Other->isKnownToHaveBooleanValue()) {
8891 S.DiagRuntimeBehavior(
8892 E->getOperatorLoc(), E,
8893 S.PDiag(!InRange ? diag::warn_out_of_range_compare
8894 : diag::warn_tautological_bool_compare)
8895 << OS.str() << classifyConstantValue(Constant)
8896 << OtherT << OtherIsBooleanDespiteType << *Result
8897 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8899 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
8900 ? (HasEnumType(OriginalOther)
8901 ? diag::warn_unsigned_enum_always_true_comparison
8902 : diag::warn_unsigned_always_true_comparison)
8903 : diag::warn_tautological_constant_compare;
8905 S.Diag(E->getOperatorLoc(), Diag)
8906 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
8907 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8913 /// Analyze the operands of the given comparison. Implements the
8914 /// fallback case from AnalyzeComparison.
8915 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8916 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8917 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8920 /// \brief Implements -Wsign-compare.
8922 /// \param E the binary operator to check for warnings
8923 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8924 // The type the comparison is being performed in.
8925 QualType T = E->getLHS()->getType();
8927 // Only analyze comparison operators where both sides have been converted to
8929 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8930 return AnalyzeImpConvsInComparison(S, E);
8932 // Don't analyze value-dependent comparisons directly.
8933 if (E->isValueDependent())
8934 return AnalyzeImpConvsInComparison(S, E);
8936 Expr *LHS = E->getLHS();
8937 Expr *RHS = E->getRHS();
8939 if (T->isIntegralType(S.Context)) {
8940 llvm::APSInt RHSValue;
8941 llvm::APSInt LHSValue;
8943 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8944 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
8946 // We don't care about expressions whose result is a constant.
8947 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8948 return AnalyzeImpConvsInComparison(S, E);
8950 // We only care about expressions where just one side is literal
8951 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8952 // Is the constant on the RHS or LHS?
8953 const bool RhsConstant = IsRHSIntegralLiteral;
8954 Expr *Const = RhsConstant ? RHS : LHS;
8955 Expr *Other = RhsConstant ? LHS : RHS;
8956 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8958 // Check whether an integer constant comparison results in a value
8959 // of 'true' or 'false'.
8960 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8961 return AnalyzeImpConvsInComparison(S, E);
8965 if (!T->hasUnsignedIntegerRepresentation()) {
8966 // We don't do anything special if this isn't an unsigned integral
8967 // comparison: we're only interested in integral comparisons, and
8968 // signed comparisons only happen in cases we don't care to warn about.
8969 return AnalyzeImpConvsInComparison(S, E);
8972 LHS = LHS->IgnoreParenImpCasts();
8973 RHS = RHS->IgnoreParenImpCasts();
8975 if (!S.getLangOpts().CPlusPlus) {
8976 // Avoid warning about comparison of integers with different signs when
8977 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
8979 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
8980 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
8981 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
8982 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
8985 // Check to see if one of the (unmodified) operands is of different
8987 Expr *signedOperand, *unsignedOperand;
8988 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8989 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8990 "unsigned comparison between two signed integer expressions?");
8991 signedOperand = LHS;
8992 unsignedOperand = RHS;
8993 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8994 signedOperand = RHS;
8995 unsignedOperand = LHS;
8997 return AnalyzeImpConvsInComparison(S, E);
9000 // Otherwise, calculate the effective range of the signed operand.
9001 IntRange signedRange = GetExprRange(S.Context, signedOperand);
9003 // Go ahead and analyze implicit conversions in the operands. Note
9004 // that we skip the implicit conversions on both sides.
9005 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9006 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
9008 // If the signed range is non-negative, -Wsign-compare won't fire.
9009 if (signedRange.NonNegative)
9012 // For (in)equality comparisons, if the unsigned operand is a
9013 // constant which cannot collide with a overflowed signed operand,
9014 // then reinterpreting the signed operand as unsigned will not
9015 // change the result of the comparison.
9016 if (E->isEqualityOp()) {
9017 unsigned comparisonWidth = S.Context.getIntWidth(T);
9018 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
9020 // We should never be unable to prove that the unsigned operand is
9022 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9024 if (unsignedRange.Width < comparisonWidth)
9028 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9029 S.PDiag(diag::warn_mixed_sign_comparison)
9030 << LHS->getType() << RHS->getType()
9031 << LHS->getSourceRange() << RHS->getSourceRange());
9034 /// Analyzes an attempt to assign the given value to a bitfield.
9036 /// Returns true if there was something fishy about the attempt.
9037 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9038 SourceLocation InitLoc) {
9039 assert(Bitfield->isBitField());
9040 if (Bitfield->isInvalidDecl())
9043 // White-list bool bitfields.
9044 QualType BitfieldType = Bitfield->getType();
9045 if (BitfieldType->isBooleanType())
9048 if (BitfieldType->isEnumeralType()) {
9049 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9050 // If the underlying enum type was not explicitly specified as an unsigned
9051 // type and the enum contain only positive values, MSVC++ will cause an
9052 // inconsistency by storing this as a signed type.
9053 if (S.getLangOpts().CPlusPlus11 &&
9054 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9055 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9056 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9057 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9058 << BitfieldEnumDecl->getNameAsString();
9062 if (Bitfield->getType()->isBooleanType())
9065 // Ignore value- or type-dependent expressions.
9066 if (Bitfield->getBitWidth()->isValueDependent() ||
9067 Bitfield->getBitWidth()->isTypeDependent() ||
9068 Init->isValueDependent() ||
9069 Init->isTypeDependent())
9072 Expr *OriginalInit = Init->IgnoreParenImpCasts();
9073 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9076 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9077 Expr::SE_AllowSideEffects)) {
9078 // The RHS is not constant. If the RHS has an enum type, make sure the
9079 // bitfield is wide enough to hold all the values of the enum without
9081 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9082 EnumDecl *ED = EnumTy->getDecl();
9083 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9085 // Enum types are implicitly signed on Windows, so check if there are any
9086 // negative enumerators to see if the enum was intended to be signed or
9088 bool SignedEnum = ED->getNumNegativeBits() > 0;
9090 // Check for surprising sign changes when assigning enum values to a
9091 // bitfield of different signedness. If the bitfield is signed and we
9092 // have exactly the right number of bits to store this unsigned enum,
9093 // suggest changing the enum to an unsigned type. This typically happens
9094 // on Windows where unfixed enums always use an underlying type of 'int'.
9095 unsigned DiagID = 0;
9096 if (SignedEnum && !SignedBitfield) {
9097 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9098 } else if (SignedBitfield && !SignedEnum &&
9099 ED->getNumPositiveBits() == FieldWidth) {
9100 DiagID = diag::warn_signed_bitfield_enum_conversion;
9104 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9105 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9106 SourceRange TypeRange =
9107 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9108 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9109 << SignedEnum << TypeRange;
9112 // Compute the required bitwidth. If the enum has negative values, we need
9113 // one more bit than the normal number of positive bits to represent the
9115 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9116 ED->getNumNegativeBits())
9117 : ED->getNumPositiveBits();
9119 // Check the bitwidth.
9120 if (BitsNeeded > FieldWidth) {
9121 Expr *WidthExpr = Bitfield->getBitWidth();
9122 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9124 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9125 << BitsNeeded << ED << WidthExpr->getSourceRange();
9132 unsigned OriginalWidth = Value.getBitWidth();
9134 if (!Value.isSigned() || Value.isNegative())
9135 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9136 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9137 OriginalWidth = Value.getMinSignedBits();
9139 if (OriginalWidth <= FieldWidth)
9142 // Compute the value which the bitfield will contain.
9143 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9144 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9146 // Check whether the stored value is equal to the original value.
9147 TruncatedValue = TruncatedValue.extend(OriginalWidth);
9148 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9151 // Special-case bitfields of width 1: booleans are naturally 0/1, and
9152 // therefore don't strictly fit into a signed bitfield of width 1.
9153 if (FieldWidth == 1 && Value == 1)
9156 std::string PrettyValue = Value.toString(10);
9157 std::string PrettyTrunc = TruncatedValue.toString(10);
9159 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9160 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9161 << Init->getSourceRange();
9166 /// Analyze the given simple or compound assignment for warning-worthy
9168 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9169 // Just recurse on the LHS.
9170 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9172 // We want to recurse on the RHS as normal unless we're assigning to
9174 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9175 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9176 E->getOperatorLoc())) {
9177 // Recurse, ignoring any implicit conversions on the RHS.
9178 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9179 E->getOperatorLoc());
9183 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9186 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
9187 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9188 SourceLocation CContext, unsigned diag,
9189 bool pruneControlFlow = false) {
9190 if (pruneControlFlow) {
9191 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9193 << SourceType << T << E->getSourceRange()
9194 << SourceRange(CContext));
9197 S.Diag(E->getExprLoc(), diag)
9198 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9201 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
9202 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9203 SourceLocation CContext,
9204 unsigned diag, bool pruneControlFlow = false) {
9205 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9209 /// Diagnose an implicit cast from a floating point value to an integer value.
9210 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9211 SourceLocation CContext) {
9212 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9213 const bool PruneWarnings = S.inTemplateInstantiation();
9215 Expr *InnerE = E->IgnoreParenImpCasts();
9216 // We also want to warn on, e.g., "int i = -1.234"
9217 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9218 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9219 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9221 const bool IsLiteral =
9222 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9224 llvm::APFloat Value(0.0);
9226 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9228 return DiagnoseImpCast(S, E, T, CContext,
9229 diag::warn_impcast_float_integer, PruneWarnings);
9232 bool isExact = false;
9234 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9235 T->hasUnsignedIntegerRepresentation());
9236 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9237 &isExact) == llvm::APFloat::opOK &&
9239 if (IsLiteral) return;
9240 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9244 unsigned DiagID = 0;
9246 // Warn on floating point literal to integer.
9247 DiagID = diag::warn_impcast_literal_float_to_integer;
9248 } else if (IntegerValue == 0) {
9249 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9250 return DiagnoseImpCast(S, E, T, CContext,
9251 diag::warn_impcast_float_integer, PruneWarnings);
9253 // Warn on non-zero to zero conversion.
9254 DiagID = diag::warn_impcast_float_to_integer_zero;
9256 if (IntegerValue.isUnsigned()) {
9257 if (!IntegerValue.isMaxValue()) {
9258 return DiagnoseImpCast(S, E, T, CContext,
9259 diag::warn_impcast_float_integer, PruneWarnings);
9261 } else { // IntegerValue.isSigned()
9262 if (!IntegerValue.isMaxSignedValue() &&
9263 !IntegerValue.isMinSignedValue()) {
9264 return DiagnoseImpCast(S, E, T, CContext,
9265 diag::warn_impcast_float_integer, PruneWarnings);
9268 // Warn on evaluatable floating point expression to integer conversion.
9269 DiagID = diag::warn_impcast_float_to_integer;
9272 // FIXME: Force the precision of the source value down so we don't print
9273 // digits which are usually useless (we don't really care here if we
9274 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9275 // would automatically print the shortest representation, but it's a bit
9276 // tricky to implement.
9277 SmallString<16> PrettySourceValue;
9278 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9279 precision = (precision * 59 + 195) / 196;
9280 Value.toString(PrettySourceValue, precision);
9282 SmallString<16> PrettyTargetValue;
9284 PrettyTargetValue = Value.isZero() ? "false" : "true";
9286 IntegerValue.toString(PrettyTargetValue);
9288 if (PruneWarnings) {
9289 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9291 << E->getType() << T.getUnqualifiedType()
9292 << PrettySourceValue << PrettyTargetValue
9293 << E->getSourceRange() << SourceRange(CContext));
9295 S.Diag(E->getExprLoc(), DiagID)
9296 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9297 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9301 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9303 if (!Range.Width) return "0";
9305 llvm::APSInt ValueInRange = Value;
9306 ValueInRange.setIsSigned(!Range.NonNegative);
9307 ValueInRange = ValueInRange.trunc(Range.Width);
9308 return ValueInRange.toString(10);
9311 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9312 if (!isa<ImplicitCastExpr>(Ex))
9315 Expr *InnerE = Ex->IgnoreParenImpCasts();
9316 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9317 const Type *Source =
9318 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9319 if (Target->isDependentType())
9322 const BuiltinType *FloatCandidateBT =
9323 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9324 const Type *BoolCandidateType = ToBool ? Target : Source;
9326 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9327 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9330 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9331 SourceLocation CC) {
9332 unsigned NumArgs = TheCall->getNumArgs();
9333 for (unsigned i = 0; i < NumArgs; ++i) {
9334 Expr *CurrA = TheCall->getArg(i);
9335 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9338 bool IsSwapped = ((i > 0) &&
9339 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9340 IsSwapped |= ((i < (NumArgs - 1)) &&
9341 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9343 // Warn on this floating-point to bool conversion.
9344 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9345 CurrA->getType(), CC,
9346 diag::warn_impcast_floating_point_to_bool);
9351 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9352 SourceLocation CC) {
9353 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9357 // Don't warn on functions which have return type nullptr_t.
9358 if (isa<CallExpr>(E))
9361 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9362 const Expr::NullPointerConstantKind NullKind =
9363 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9364 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9367 // Return if target type is a safe conversion.
9368 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9369 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9372 SourceLocation Loc = E->getSourceRange().getBegin();
9374 // Venture through the macro stacks to get to the source of macro arguments.
9375 // The new location is a better location than the complete location that was
9377 while (S.SourceMgr.isMacroArgExpansion(Loc))
9378 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9380 while (S.SourceMgr.isMacroArgExpansion(CC))
9381 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9383 // __null is usually wrapped in a macro. Go up a macro if that is the case.
9384 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9385 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9386 Loc, S.SourceMgr, S.getLangOpts());
9387 if (MacroName == "NULL")
9388 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9391 // Only warn if the null and context location are in the same macro expansion.
9392 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9395 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9396 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
9397 << FixItHint::CreateReplacement(Loc,
9398 S.getFixItZeroLiteralForType(T, Loc));
9401 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9402 ObjCArrayLiteral *ArrayLiteral);
9405 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9406 ObjCDictionaryLiteral *DictionaryLiteral);
9408 /// Check a single element within a collection literal against the
9409 /// target element type.
9410 static void checkObjCCollectionLiteralElement(Sema &S,
9411 QualType TargetElementType,
9413 unsigned ElementKind) {
9414 // Skip a bitcast to 'id' or qualified 'id'.
9415 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9416 if (ICE->getCastKind() == CK_BitCast &&
9417 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9418 Element = ICE->getSubExpr();
9421 QualType ElementType = Element->getType();
9422 ExprResult ElementResult(Element);
9423 if (ElementType->getAs<ObjCObjectPointerType>() &&
9424 S.CheckSingleAssignmentConstraints(TargetElementType,
9427 != Sema::Compatible) {
9428 S.Diag(Element->getLocStart(),
9429 diag::warn_objc_collection_literal_element)
9430 << ElementType << ElementKind << TargetElementType
9431 << Element->getSourceRange();
9434 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9435 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9436 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9437 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9440 /// Check an Objective-C array literal being converted to the given
9442 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9443 ObjCArrayLiteral *ArrayLiteral) {
9447 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9451 if (TargetObjCPtr->isUnspecialized() ||
9452 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9453 != S.NSArrayDecl->getCanonicalDecl())
9456 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9457 if (TypeArgs.size() != 1)
9460 QualType TargetElementType = TypeArgs[0];
9461 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9462 checkObjCCollectionLiteralElement(S, TargetElementType,
9463 ArrayLiteral->getElement(I),
9468 /// Check an Objective-C dictionary literal being converted to the given
9471 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9472 ObjCDictionaryLiteral *DictionaryLiteral) {
9473 if (!S.NSDictionaryDecl)
9476 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9480 if (TargetObjCPtr->isUnspecialized() ||
9481 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9482 != S.NSDictionaryDecl->getCanonicalDecl())
9485 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9486 if (TypeArgs.size() != 2)
9489 QualType TargetKeyType = TypeArgs[0];
9490 QualType TargetObjectType = TypeArgs[1];
9491 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9492 auto Element = DictionaryLiteral->getKeyValueElement(I);
9493 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9494 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9498 // Helper function to filter out cases for constant width constant conversion.
9499 // Don't warn on char array initialization or for non-decimal values.
9500 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9501 SourceLocation CC) {
9502 // If initializing from a constant, and the constant starts with '0',
9503 // then it is a binary, octal, or hexadecimal. Allow these constants
9504 // to fill all the bits, even if there is a sign change.
9505 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9506 const char FirstLiteralCharacter =
9507 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9508 if (FirstLiteralCharacter == '0')
9512 // If the CC location points to a '{', and the type is char, then assume
9513 // assume it is an array initialization.
9514 if (CC.isValid() && T->isCharType()) {
9515 const char FirstContextCharacter =
9516 S.getSourceManager().getCharacterData(CC)[0];
9517 if (FirstContextCharacter == '{')
9525 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9526 bool *ICContext = nullptr) {
9527 if (E->isTypeDependent() || E->isValueDependent()) return;
9529 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9530 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9531 if (Source == Target) return;
9532 if (Target->isDependentType()) return;
9534 // If the conversion context location is invalid don't complain. We also
9535 // don't want to emit a warning if the issue occurs from the expansion of
9536 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9537 // delay this check as long as possible. Once we detect we are in that
9538 // scenario, we just return.
9542 // Diagnose implicit casts to bool.
9543 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9544 if (isa<StringLiteral>(E))
9545 // Warn on string literal to bool. Checks for string literals in logical
9546 // and expressions, for instance, assert(0 && "error here"), are
9547 // prevented by a check in AnalyzeImplicitConversions().
9548 return DiagnoseImpCast(S, E, T, CC,
9549 diag::warn_impcast_string_literal_to_bool);
9550 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9551 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9552 // This covers the literal expressions that evaluate to Objective-C
9554 return DiagnoseImpCast(S, E, T, CC,
9555 diag::warn_impcast_objective_c_literal_to_bool);
9557 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9558 // Warn on pointer to bool conversion that is always true.
9559 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9564 // Check implicit casts from Objective-C collection literals to specialized
9565 // collection types, e.g., NSArray<NSString *> *.
9566 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9567 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9568 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9569 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9571 // Strip vector types.
9572 if (isa<VectorType>(Source)) {
9573 if (!isa<VectorType>(Target)) {
9574 if (S.SourceMgr.isInSystemMacro(CC))
9576 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9579 // If the vector cast is cast between two vectors of the same size, it is
9580 // a bitcast, not a conversion.
9581 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9584 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9585 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9587 if (auto VecTy = dyn_cast<VectorType>(Target))
9588 Target = VecTy->getElementType().getTypePtr();
9590 // Strip complex types.
9591 if (isa<ComplexType>(Source)) {
9592 if (!isa<ComplexType>(Target)) {
9593 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
9596 return DiagnoseImpCast(S, E, T, CC,
9597 S.getLangOpts().CPlusPlus
9598 ? diag::err_impcast_complex_scalar
9599 : diag::warn_impcast_complex_scalar);
9602 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9603 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9606 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9607 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9609 // If the source is floating point...
9610 if (SourceBT && SourceBT->isFloatingPoint()) {
9611 // ...and the target is floating point...
9612 if (TargetBT && TargetBT->isFloatingPoint()) {
9613 // ...then warn if we're dropping FP rank.
9615 // Builtin FP kinds are ordered by increasing FP rank.
9616 if (SourceBT->getKind() > TargetBT->getKind()) {
9617 // Don't warn about float constants that are precisely
9618 // representable in the target type.
9619 Expr::EvalResult result;
9620 if (E->EvaluateAsRValue(result, S.Context)) {
9621 // Value might be a float, a float vector, or a float complex.
9622 if (IsSameFloatAfterCast(result.Val,
9623 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9624 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9628 if (S.SourceMgr.isInSystemMacro(CC))
9631 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9633 // ... or possibly if we're increasing rank, too
9634 else if (TargetBT->getKind() > SourceBT->getKind()) {
9635 if (S.SourceMgr.isInSystemMacro(CC))
9638 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9643 // If the target is integral, always warn.
9644 if (TargetBT && TargetBT->isInteger()) {
9645 if (S.SourceMgr.isInSystemMacro(CC))
9648 DiagnoseFloatingImpCast(S, E, T, CC);
9651 // Detect the case where a call result is converted from floating-point to
9652 // to bool, and the final argument to the call is converted from bool, to
9653 // discover this typo:
9655 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9657 // FIXME: This is an incredibly special case; is there some more general
9658 // way to detect this class of misplaced-parentheses bug?
9659 if (Target->isBooleanType() && isa<CallExpr>(E)) {
9660 // Check last argument of function call to see if it is an
9661 // implicit cast from a type matching the type the result
9662 // is being cast to.
9663 CallExpr *CEx = cast<CallExpr>(E);
9664 if (unsigned NumArgs = CEx->getNumArgs()) {
9665 Expr *LastA = CEx->getArg(NumArgs - 1);
9666 Expr *InnerE = LastA->IgnoreParenImpCasts();
9667 if (isa<ImplicitCastExpr>(LastA) &&
9668 InnerE->getType()->isBooleanType()) {
9669 // Warn on this floating-point to bool conversion
9670 DiagnoseImpCast(S, E, T, CC,
9671 diag::warn_impcast_floating_point_to_bool);
9678 DiagnoseNullConversion(S, E, T, CC);
9680 S.DiscardMisalignedMemberAddress(Target, E);
9682 if (!Source->isIntegerType() || !Target->isIntegerType())
9685 // TODO: remove this early return once the false positives for constant->bool
9686 // in templates, macros, etc, are reduced or removed.
9687 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9690 IntRange SourceRange = GetExprRange(S.Context, E);
9691 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9693 if (SourceRange.Width > TargetRange.Width) {
9694 // If the source is a constant, use a default-on diagnostic.
9695 // TODO: this should happen for bitfield stores, too.
9696 llvm::APSInt Value(32);
9697 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9698 if (S.SourceMgr.isInSystemMacro(CC))
9701 std::string PrettySourceValue = Value.toString(10);
9702 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9704 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9705 S.PDiag(diag::warn_impcast_integer_precision_constant)
9706 << PrettySourceValue << PrettyTargetValue
9707 << E->getType() << T << E->getSourceRange()
9708 << clang::SourceRange(CC));
9712 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9713 if (S.SourceMgr.isInSystemMacro(CC))
9716 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9717 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9718 /* pruneControlFlow */ true);
9719 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9722 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9723 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9724 // Warn when doing a signed to signed conversion, warn if the positive
9725 // source value is exactly the width of the target type, which will
9726 // cause a negative value to be stored.
9729 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9730 !S.SourceMgr.isInSystemMacro(CC)) {
9731 if (isSameWidthConstantConversion(S, E, T, CC)) {
9732 std::string PrettySourceValue = Value.toString(10);
9733 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9735 S.DiagRuntimeBehavior(
9737 S.PDiag(diag::warn_impcast_integer_precision_constant)
9738 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9739 << E->getSourceRange() << clang::SourceRange(CC));
9744 // Fall through for non-constants to give a sign conversion warning.
9747 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9748 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9749 SourceRange.Width == TargetRange.Width)) {
9750 if (S.SourceMgr.isInSystemMacro(CC))
9753 unsigned DiagID = diag::warn_impcast_integer_sign;
9755 // Traditionally, gcc has warned about this under -Wsign-compare.
9756 // We also want to warn about it in -Wconversion.
9757 // So if -Wconversion is off, use a completely identical diagnostic
9758 // in the sign-compare group.
9759 // The conditional-checking code will
9761 DiagID = diag::warn_impcast_integer_sign_conditional;
9765 return DiagnoseImpCast(S, E, T, CC, DiagID);
9768 // Diagnose conversions between different enumeration types.
9769 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9770 // type, to give us better diagnostics.
9771 QualType SourceType = E->getType();
9772 if (!S.getLangOpts().CPlusPlus) {
9773 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9774 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9775 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9776 SourceType = S.Context.getTypeDeclType(Enum);
9777 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9781 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9782 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9783 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9784 TargetEnum->getDecl()->hasNameForLinkage() &&
9785 SourceEnum != TargetEnum) {
9786 if (S.SourceMgr.isInSystemMacro(CC))
9789 return DiagnoseImpCast(S, E, SourceType, T, CC,
9790 diag::warn_impcast_different_enum_types);
9794 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9795 SourceLocation CC, QualType T);
9797 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9798 SourceLocation CC, bool &ICContext) {
9799 E = E->IgnoreParenImpCasts();
9801 if (isa<ConditionalOperator>(E))
9802 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9804 AnalyzeImplicitConversions(S, E, CC);
9805 if (E->getType() != T)
9806 return CheckImplicitConversion(S, E, T, CC, &ICContext);
9809 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9810 SourceLocation CC, QualType T) {
9811 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9813 bool Suspicious = false;
9814 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9815 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9817 // If -Wconversion would have warned about either of the candidates
9818 // for a signedness conversion to the context type...
9819 if (!Suspicious) return;
9821 // ...but it's currently ignored...
9822 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9825 // ...then check whether it would have warned about either of the
9826 // candidates for a signedness conversion to the condition type.
9827 if (E->getType() == T) return;
9830 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9831 E->getType(), CC, &Suspicious);
9833 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9834 E->getType(), CC, &Suspicious);
9837 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9838 /// Input argument E is a logical expression.
9839 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9840 if (S.getLangOpts().Bool)
9842 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9845 /// AnalyzeImplicitConversions - Find and report any interesting
9846 /// implicit conversions in the given expression. There are a couple
9847 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9848 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
9849 SourceLocation CC) {
9850 QualType T = OrigE->getType();
9851 Expr *E = OrigE->IgnoreParenImpCasts();
9853 if (E->isTypeDependent() || E->isValueDependent())
9856 // For conditional operators, we analyze the arguments as if they
9857 // were being fed directly into the output.
9858 if (isa<ConditionalOperator>(E)) {
9859 ConditionalOperator *CO = cast<ConditionalOperator>(E);
9860 CheckConditionalOperator(S, CO, CC, T);
9864 // Check implicit argument conversions for function calls.
9865 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9866 CheckImplicitArgumentConversions(S, Call, CC);
9868 // Go ahead and check any implicit conversions we might have skipped.
9869 // The non-canonical typecheck is just an optimization;
9870 // CheckImplicitConversion will filter out dead implicit conversions.
9871 if (E->getType() != T)
9872 CheckImplicitConversion(S, E, T, CC);
9874 // Now continue drilling into this expression.
9876 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9877 // The bound subexpressions in a PseudoObjectExpr are not reachable
9878 // as transitive children.
9879 // FIXME: Use a more uniform representation for this.
9880 for (auto *SE : POE->semantics())
9881 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9882 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9885 // Skip past explicit casts.
9886 if (isa<ExplicitCastExpr>(E)) {
9887 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9888 return AnalyzeImplicitConversions(S, E, CC);
9891 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9892 // Do a somewhat different check with comparison operators.
9893 if (BO->isComparisonOp())
9894 return AnalyzeComparison(S, BO);
9896 // And with simple assignments.
9897 if (BO->getOpcode() == BO_Assign)
9898 return AnalyzeAssignment(S, BO);
9901 // These break the otherwise-useful invariant below. Fortunately,
9902 // we don't really need to recurse into them, because any internal
9903 // expressions should have been analyzed already when they were
9904 // built into statements.
9905 if (isa<StmtExpr>(E)) return;
9907 // Don't descend into unevaluated contexts.
9908 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9910 // Now just recurse over the expression's children.
9911 CC = E->getExprLoc();
9912 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9913 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9914 for (Stmt *SubStmt : E->children()) {
9915 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9919 if (IsLogicalAndOperator &&
9920 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9921 // Ignore checking string literals that are in logical and operators.
9922 // This is a common pattern for asserts.
9924 AnalyzeImplicitConversions(S, ChildExpr, CC);
9927 if (BO && BO->isLogicalOp()) {
9928 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9929 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9930 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9932 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9933 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9934 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9937 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9938 if (U->getOpcode() == UO_LNot)
9939 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9942 /// Diagnose integer type and any valid implicit convertion to it.
9943 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9944 // Taking into account implicit conversions,
9945 // allow any integer.
9946 if (!E->getType()->isIntegerType()) {
9947 S.Diag(E->getLocStart(),
9948 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9951 // Potentially emit standard warnings for implicit conversions if enabled
9952 // using -Wconversion.
9953 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9957 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9958 // Returns true when emitting a warning about taking the address of a reference.
9959 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9960 const PartialDiagnostic &PD) {
9961 E = E->IgnoreParenImpCasts();
9963 const FunctionDecl *FD = nullptr;
9965 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9966 if (!DRE->getDecl()->getType()->isReferenceType())
9968 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9969 if (!M->getMemberDecl()->getType()->isReferenceType())
9971 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9972 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9974 FD = Call->getDirectCallee();
9979 SemaRef.Diag(E->getExprLoc(), PD);
9981 // If possible, point to location of function.
9983 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9989 // Returns true if the SourceLocation is expanded from any macro body.
9990 // Returns false if the SourceLocation is invalid, is from not in a macro
9991 // expansion, or is from expanded from a top-level macro argument.
9992 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9993 if (Loc.isInvalid())
9996 while (Loc.isMacroID()) {
9997 if (SM.isMacroBodyExpansion(Loc))
9999 Loc = SM.getImmediateMacroCallerLoc(Loc);
10005 /// \brief Diagnose pointers that are always non-null.
10006 /// \param E the expression containing the pointer
10007 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10008 /// compared to a null pointer
10009 /// \param IsEqual True when the comparison is equal to a null pointer
10010 /// \param Range Extra SourceRange to highlight in the diagnostic
10011 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10012 Expr::NullPointerConstantKind NullKind,
10013 bool IsEqual, SourceRange Range) {
10017 // Don't warn inside macros.
10018 if (E->getExprLoc().isMacroID()) {
10019 const SourceManager &SM = getSourceManager();
10020 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10021 IsInAnyMacroBody(SM, Range.getBegin()))
10024 E = E->IgnoreImpCasts();
10026 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10028 if (isa<CXXThisExpr>(E)) {
10029 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10030 : diag::warn_this_bool_conversion;
10031 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10035 bool IsAddressOf = false;
10037 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10038 if (UO->getOpcode() != UO_AddrOf)
10040 IsAddressOf = true;
10041 E = UO->getSubExpr();
10045 unsigned DiagID = IsCompare
10046 ? diag::warn_address_of_reference_null_compare
10047 : diag::warn_address_of_reference_bool_conversion;
10048 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10050 if (CheckForReference(*this, E, PD)) {
10055 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10056 bool IsParam = isa<NonNullAttr>(NonnullAttr);
10058 llvm::raw_string_ostream S(Str);
10059 E->printPretty(S, nullptr, getPrintingPolicy());
10060 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10061 : diag::warn_cast_nonnull_to_bool;
10062 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10063 << E->getSourceRange() << Range << IsEqual;
10064 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10067 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10068 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10069 if (auto *Callee = Call->getDirectCallee()) {
10070 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10071 ComplainAboutNonnullParamOrCall(A);
10077 // Expect to find a single Decl. Skip anything more complicated.
10078 ValueDecl *D = nullptr;
10079 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10081 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10082 D = M->getMemberDecl();
10085 // Weak Decls can be null.
10086 if (!D || D->isWeak())
10089 // Check for parameter decl with nonnull attribute
10090 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10091 if (getCurFunction() &&
10092 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10093 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10094 ComplainAboutNonnullParamOrCall(A);
10098 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10099 auto ParamIter = llvm::find(FD->parameters(), PV);
10100 assert(ParamIter != FD->param_end());
10101 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10103 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10104 if (!NonNull->args_size()) {
10105 ComplainAboutNonnullParamOrCall(NonNull);
10109 for (unsigned ArgNo : NonNull->args()) {
10110 if (ArgNo == ParamNo) {
10111 ComplainAboutNonnullParamOrCall(NonNull);
10120 QualType T = D->getType();
10121 const bool IsArray = T->isArrayType();
10122 const bool IsFunction = T->isFunctionType();
10124 // Address of function is used to silence the function warning.
10125 if (IsAddressOf && IsFunction) {
10130 if (!IsAddressOf && !IsFunction && !IsArray)
10133 // Pretty print the expression for the diagnostic.
10135 llvm::raw_string_ostream S(Str);
10136 E->printPretty(S, nullptr, getPrintingPolicy());
10138 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10139 : diag::warn_impcast_pointer_to_bool;
10146 DiagType = AddressOf;
10147 else if (IsFunction)
10148 DiagType = FunctionPointer;
10150 DiagType = ArrayPointer;
10152 llvm_unreachable("Could not determine diagnostic.");
10153 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10154 << Range << IsEqual;
10159 // Suggest '&' to silence the function warning.
10160 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10161 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10163 // Check to see if '()' fixit should be emitted.
10164 QualType ReturnType;
10165 UnresolvedSet<4> NonTemplateOverloads;
10166 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10167 if (ReturnType.isNull())
10171 // There are two cases here. If there is null constant, the only suggest
10172 // for a pointer return type. If the null is 0, then suggest if the return
10173 // type is a pointer or an integer type.
10174 if (!ReturnType->isPointerType()) {
10175 if (NullKind == Expr::NPCK_ZeroExpression ||
10176 NullKind == Expr::NPCK_ZeroLiteral) {
10177 if (!ReturnType->isIntegerType())
10183 } else { // !IsCompare
10184 // For function to bool, only suggest if the function pointer has bool
10186 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10189 Diag(E->getExprLoc(), diag::note_function_to_function_call)
10190 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10193 /// Diagnoses "dangerous" implicit conversions within the given
10194 /// expression (which is a full expression). Implements -Wconversion
10195 /// and -Wsign-compare.
10197 /// \param CC the "context" location of the implicit conversion, i.e.
10198 /// the most location of the syntactic entity requiring the implicit
10200 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10201 // Don't diagnose in unevaluated contexts.
10202 if (isUnevaluatedContext())
10205 // Don't diagnose for value- or type-dependent expressions.
10206 if (E->isTypeDependent() || E->isValueDependent())
10209 // Check for array bounds violations in cases where the check isn't triggered
10210 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10211 // ArraySubscriptExpr is on the RHS of a variable initialization.
10212 CheckArrayAccess(E);
10214 // This is not the right CC for (e.g.) a variable initialization.
10215 AnalyzeImplicitConversions(*this, E, CC);
10218 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10219 /// Input argument E is a logical expression.
10220 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10221 ::CheckBoolLikeConversion(*this, E, CC);
10224 /// Diagnose when expression is an integer constant expression and its evaluation
10225 /// results in integer overflow
10226 void Sema::CheckForIntOverflow (Expr *E) {
10227 // Use a work list to deal with nested struct initializers.
10228 SmallVector<Expr *, 2> Exprs(1, E);
10231 Expr *E = Exprs.pop_back_val();
10233 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10234 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10238 if (auto InitList = dyn_cast<InitListExpr>(E))
10239 Exprs.append(InitList->inits().begin(), InitList->inits().end());
10241 if (isa<ObjCBoxedExpr>(E))
10242 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10243 } while (!Exprs.empty());
10248 /// \brief Visitor for expressions which looks for unsequenced operations on the
10250 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10251 using Base = EvaluatedExprVisitor<SequenceChecker>;
10253 /// \brief A tree of sequenced regions within an expression. Two regions are
10254 /// unsequenced if one is an ancestor or a descendent of the other. When we
10255 /// finish processing an expression with sequencing, such as a comma
10256 /// expression, we fold its tree nodes into its parent, since they are
10257 /// unsequenced with respect to nodes we will visit later.
10258 class SequenceTree {
10260 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10261 unsigned Parent : 31;
10262 unsigned Merged : 1;
10264 SmallVector<Value, 8> Values;
10267 /// \brief A region within an expression which may be sequenced with respect
10268 /// to some other region.
10270 friend class SequenceTree;
10272 unsigned Index = 0;
10274 explicit Seq(unsigned N) : Index(N) {}
10280 SequenceTree() { Values.push_back(Value(0)); }
10281 Seq root() const { return Seq(0); }
10283 /// \brief Create a new sequence of operations, which is an unsequenced
10284 /// subset of \p Parent. This sequence of operations is sequenced with
10285 /// respect to other children of \p Parent.
10286 Seq allocate(Seq Parent) {
10287 Values.push_back(Value(Parent.Index));
10288 return Seq(Values.size() - 1);
10291 /// \brief Merge a sequence of operations into its parent.
10292 void merge(Seq S) {
10293 Values[S.Index].Merged = true;
10296 /// \brief Determine whether two operations are unsequenced. This operation
10297 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10298 /// should have been merged into its parent as appropriate.
10299 bool isUnsequenced(Seq Cur, Seq Old) {
10300 unsigned C = representative(Cur.Index);
10301 unsigned Target = representative(Old.Index);
10302 while (C >= Target) {
10305 C = Values[C].Parent;
10311 /// \brief Pick a representative for a sequence.
10312 unsigned representative(unsigned K) {
10313 if (Values[K].Merged)
10314 // Perform path compression as we go.
10315 return Values[K].Parent = representative(Values[K].Parent);
10320 /// An object for which we can track unsequenced uses.
10321 using Object = NamedDecl *;
10323 /// Different flavors of object usage which we track. We only track the
10324 /// least-sequenced usage of each kind.
10326 /// A read of an object. Multiple unsequenced reads are OK.
10329 /// A modification of an object which is sequenced before the value
10330 /// computation of the expression, such as ++n in C++.
10333 /// A modification of an object which is not sequenced before the value
10334 /// computation of the expression, such as n++.
10335 UK_ModAsSideEffect,
10337 UK_Count = UK_ModAsSideEffect + 1
10341 Expr *Use = nullptr;
10342 SequenceTree::Seq Seq;
10348 Usage Uses[UK_Count];
10350 /// Have we issued a diagnostic for this variable already?
10351 bool Diagnosed = false;
10353 UsageInfo() = default;
10355 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
10359 /// Sequenced regions within the expression.
10362 /// Declaration modifications and references which we have seen.
10363 UsageInfoMap UsageMap;
10365 /// The region we are currently within.
10366 SequenceTree::Seq Region;
10368 /// Filled in with declarations which were modified as a side-effect
10369 /// (that is, post-increment operations).
10370 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10372 /// Expressions to check later. We defer checking these to reduce
10374 SmallVectorImpl<Expr *> &WorkList;
10376 /// RAII object wrapping the visitation of a sequenced subexpression of an
10377 /// expression. At the end of this process, the side-effects of the evaluation
10378 /// become sequenced with respect to the value computation of the result, so
10379 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10381 struct SequencedSubexpression {
10382 SequencedSubexpression(SequenceChecker &Self)
10383 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10384 Self.ModAsSideEffect = &ModAsSideEffect;
10387 ~SequencedSubexpression() {
10388 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10389 UsageInfo &U = Self.UsageMap[M.first];
10390 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10391 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10392 SideEffectUsage = M.second;
10394 Self.ModAsSideEffect = OldModAsSideEffect;
10397 SequenceChecker &Self;
10398 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10399 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
10402 /// RAII object wrapping the visitation of a subexpression which we might
10403 /// choose to evaluate as a constant. If any subexpression is evaluated and
10404 /// found to be non-constant, this allows us to suppress the evaluation of
10405 /// the outer expression.
10406 class EvaluationTracker {
10408 EvaluationTracker(SequenceChecker &Self)
10409 : Self(Self), Prev(Self.EvalTracker) {
10410 Self.EvalTracker = this;
10413 ~EvaluationTracker() {
10414 Self.EvalTracker = Prev;
10416 Prev->EvalOK &= EvalOK;
10419 bool evaluate(const Expr *E, bool &Result) {
10420 if (!EvalOK || E->isValueDependent())
10422 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10427 SequenceChecker &Self;
10428 EvaluationTracker *Prev;
10429 bool EvalOK = true;
10430 } *EvalTracker = nullptr;
10432 /// \brief Find the object which is produced by the specified expression,
10434 Object getObject(Expr *E, bool Mod) const {
10435 E = E->IgnoreParenCasts();
10436 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10437 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10438 return getObject(UO->getSubExpr(), Mod);
10439 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10440 if (BO->getOpcode() == BO_Comma)
10441 return getObject(BO->getRHS(), Mod);
10442 if (Mod && BO->isAssignmentOp())
10443 return getObject(BO->getLHS(), Mod);
10444 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10445 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10446 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10447 return ME->getMemberDecl();
10448 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10449 // FIXME: If this is a reference, map through to its value.
10450 return DRE->getDecl();
10454 /// \brief Note that an object was modified or used by an expression.
10455 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10456 Usage &U = UI.Uses[UK];
10457 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10458 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10459 ModAsSideEffect->push_back(std::make_pair(O, U));
10465 /// \brief Check whether a modification or use conflicts with a prior usage.
10466 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10471 const Usage &U = UI.Uses[OtherKind];
10472 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10476 Expr *ModOrUse = Ref;
10477 if (OtherKind == UK_Use)
10478 std::swap(Mod, ModOrUse);
10480 SemaRef.Diag(Mod->getExprLoc(),
10481 IsModMod ? diag::warn_unsequenced_mod_mod
10482 : diag::warn_unsequenced_mod_use)
10483 << O << SourceRange(ModOrUse->getExprLoc());
10484 UI.Diagnosed = true;
10487 void notePreUse(Object O, Expr *Use) {
10488 UsageInfo &U = UsageMap[O];
10489 // Uses conflict with other modifications.
10490 checkUsage(O, U, Use, UK_ModAsValue, false);
10493 void notePostUse(Object O, Expr *Use) {
10494 UsageInfo &U = UsageMap[O];
10495 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10496 addUsage(U, O, Use, UK_Use);
10499 void notePreMod(Object O, Expr *Mod) {
10500 UsageInfo &U = UsageMap[O];
10501 // Modifications conflict with other modifications and with uses.
10502 checkUsage(O, U, Mod, UK_ModAsValue, true);
10503 checkUsage(O, U, Mod, UK_Use, false);
10506 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10507 UsageInfo &U = UsageMap[O];
10508 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10509 addUsage(U, O, Use, UK);
10513 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10514 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
10518 void VisitStmt(Stmt *S) {
10519 // Skip all statements which aren't expressions for now.
10522 void VisitExpr(Expr *E) {
10523 // By default, just recurse to evaluated subexpressions.
10524 Base::VisitStmt(E);
10527 void VisitCastExpr(CastExpr *E) {
10528 Object O = Object();
10529 if (E->getCastKind() == CK_LValueToRValue)
10530 O = getObject(E->getSubExpr(), false);
10539 void VisitBinComma(BinaryOperator *BO) {
10540 // C++11 [expr.comma]p1:
10541 // Every value computation and side effect associated with the left
10542 // expression is sequenced before every value computation and side
10543 // effect associated with the right expression.
10544 SequenceTree::Seq LHS = Tree.allocate(Region);
10545 SequenceTree::Seq RHS = Tree.allocate(Region);
10546 SequenceTree::Seq OldRegion = Region;
10549 SequencedSubexpression SeqLHS(*this);
10551 Visit(BO->getLHS());
10555 Visit(BO->getRHS());
10557 Region = OldRegion;
10559 // Forget that LHS and RHS are sequenced. They are both unsequenced
10560 // with respect to other stuff.
10565 void VisitBinAssign(BinaryOperator *BO) {
10566 // The modification is sequenced after the value computation of the LHS
10567 // and RHS, so check it before inspecting the operands and update the
10569 Object O = getObject(BO->getLHS(), true);
10571 return VisitExpr(BO);
10575 // C++11 [expr.ass]p7:
10576 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10579 // Therefore, for a compound assignment operator, O is considered used
10580 // everywhere except within the evaluation of E1 itself.
10581 if (isa<CompoundAssignOperator>(BO))
10584 Visit(BO->getLHS());
10586 if (isa<CompoundAssignOperator>(BO))
10587 notePostUse(O, BO);
10589 Visit(BO->getRHS());
10591 // C++11 [expr.ass]p1:
10592 // the assignment is sequenced [...] before the value computation of the
10593 // assignment expression.
10594 // C11 6.5.16/3 has no such rule.
10595 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10596 : UK_ModAsSideEffect);
10599 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10600 VisitBinAssign(CAO);
10603 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10604 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10605 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10606 Object O = getObject(UO->getSubExpr(), true);
10608 return VisitExpr(UO);
10611 Visit(UO->getSubExpr());
10612 // C++11 [expr.pre.incr]p1:
10613 // the expression ++x is equivalent to x+=1
10614 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10615 : UK_ModAsSideEffect);
10618 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10619 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10620 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10621 Object O = getObject(UO->getSubExpr(), true);
10623 return VisitExpr(UO);
10626 Visit(UO->getSubExpr());
10627 notePostMod(O, UO, UK_ModAsSideEffect);
10630 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10631 void VisitBinLOr(BinaryOperator *BO) {
10632 // The side-effects of the LHS of an '&&' are sequenced before the
10633 // value computation of the RHS, and hence before the value computation
10634 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10635 // as if they were unconditionally sequenced.
10636 EvaluationTracker Eval(*this);
10638 SequencedSubexpression Sequenced(*this);
10639 Visit(BO->getLHS());
10643 if (Eval.evaluate(BO->getLHS(), Result)) {
10645 Visit(BO->getRHS());
10647 // Check for unsequenced operations in the RHS, treating it as an
10648 // entirely separate evaluation.
10650 // FIXME: If there are operations in the RHS which are unsequenced
10651 // with respect to operations outside the RHS, and those operations
10652 // are unconditionally evaluated, diagnose them.
10653 WorkList.push_back(BO->getRHS());
10656 void VisitBinLAnd(BinaryOperator *BO) {
10657 EvaluationTracker Eval(*this);
10659 SequencedSubexpression Sequenced(*this);
10660 Visit(BO->getLHS());
10664 if (Eval.evaluate(BO->getLHS(), Result)) {
10666 Visit(BO->getRHS());
10668 WorkList.push_back(BO->getRHS());
10672 // Only visit the condition, unless we can be sure which subexpression will
10674 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10675 EvaluationTracker Eval(*this);
10677 SequencedSubexpression Sequenced(*this);
10678 Visit(CO->getCond());
10682 if (Eval.evaluate(CO->getCond(), Result))
10683 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10685 WorkList.push_back(CO->getTrueExpr());
10686 WorkList.push_back(CO->getFalseExpr());
10690 void VisitCallExpr(CallExpr *CE) {
10691 // C++11 [intro.execution]p15:
10692 // When calling a function [...], every value computation and side effect
10693 // associated with any argument expression, or with the postfix expression
10694 // designating the called function, is sequenced before execution of every
10695 // expression or statement in the body of the function [and thus before
10696 // the value computation of its result].
10697 SequencedSubexpression Sequenced(*this);
10698 Base::VisitCallExpr(CE);
10700 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10703 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10704 // This is a call, so all subexpressions are sequenced before the result.
10705 SequencedSubexpression Sequenced(*this);
10707 if (!CCE->isListInitialization())
10708 return VisitExpr(CCE);
10710 // In C++11, list initializations are sequenced.
10711 SmallVector<SequenceTree::Seq, 32> Elts;
10712 SequenceTree::Seq Parent = Region;
10713 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10714 E = CCE->arg_end();
10716 Region = Tree.allocate(Parent);
10717 Elts.push_back(Region);
10721 // Forget that the initializers are sequenced.
10723 for (unsigned I = 0; I < Elts.size(); ++I)
10724 Tree.merge(Elts[I]);
10727 void VisitInitListExpr(InitListExpr *ILE) {
10728 if (!SemaRef.getLangOpts().CPlusPlus11)
10729 return VisitExpr(ILE);
10731 // In C++11, list initializations are sequenced.
10732 SmallVector<SequenceTree::Seq, 32> Elts;
10733 SequenceTree::Seq Parent = Region;
10734 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10735 Expr *E = ILE->getInit(I);
10737 Region = Tree.allocate(Parent);
10738 Elts.push_back(Region);
10742 // Forget that the initializers are sequenced.
10744 for (unsigned I = 0; I < Elts.size(); ++I)
10745 Tree.merge(Elts[I]);
10751 void Sema::CheckUnsequencedOperations(Expr *E) {
10752 SmallVector<Expr *, 8> WorkList;
10753 WorkList.push_back(E);
10754 while (!WorkList.empty()) {
10755 Expr *Item = WorkList.pop_back_val();
10756 SequenceChecker(*this, Item, WorkList);
10760 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10761 bool IsConstexpr) {
10762 CheckImplicitConversions(E, CheckLoc);
10763 if (!E->isInstantiationDependent())
10764 CheckUnsequencedOperations(E);
10765 if (!IsConstexpr && !E->isValueDependent())
10766 CheckForIntOverflow(E);
10767 DiagnoseMisalignedMembers();
10770 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10771 FieldDecl *BitField,
10773 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10776 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10777 SourceLocation Loc) {
10778 if (!PType->isVariablyModifiedType())
10780 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10781 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10784 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10785 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10788 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10789 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10793 const ArrayType *AT = S.Context.getAsArrayType(PType);
10797 if (AT->getSizeModifier() != ArrayType::Star) {
10798 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10802 S.Diag(Loc, diag::err_array_star_in_function_definition);
10805 /// CheckParmsForFunctionDef - Check that the parameters of the given
10806 /// function are appropriate for the definition of a function. This
10807 /// takes care of any checks that cannot be performed on the
10808 /// declaration itself, e.g., that the types of each of the function
10809 /// parameters are complete.
10810 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10811 bool CheckParameterNames) {
10812 bool HasInvalidParm = false;
10813 for (ParmVarDecl *Param : Parameters) {
10814 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10815 // function declarator that is part of a function definition of
10816 // that function shall not have incomplete type.
10818 // This is also C++ [dcl.fct]p6.
10819 if (!Param->isInvalidDecl() &&
10820 RequireCompleteType(Param->getLocation(), Param->getType(),
10821 diag::err_typecheck_decl_incomplete_type)) {
10822 Param->setInvalidDecl();
10823 HasInvalidParm = true;
10826 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10827 // declaration of each parameter shall include an identifier.
10828 if (CheckParameterNames &&
10829 Param->getIdentifier() == nullptr &&
10830 !Param->isImplicit() &&
10831 !getLangOpts().CPlusPlus)
10832 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10835 // If the function declarator is not part of a definition of that
10836 // function, parameters may have incomplete type and may use the [*]
10837 // notation in their sequences of declarator specifiers to specify
10838 // variable length array types.
10839 QualType PType = Param->getOriginalType();
10840 // FIXME: This diagnostic should point the '[*]' if source-location
10841 // information is added for it.
10842 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10844 // MSVC destroys objects passed by value in the callee. Therefore a
10845 // function definition which takes such a parameter must be able to call the
10846 // object's destructor. However, we don't perform any direct access check
10848 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10850 .areArgsDestroyedLeftToRightInCallee()) {
10851 if (!Param->isInvalidDecl()) {
10852 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10853 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10854 if (!ClassDecl->isInvalidDecl() &&
10855 !ClassDecl->hasIrrelevantDestructor() &&
10856 !ClassDecl->isDependentContext()) {
10857 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10858 MarkFunctionReferenced(Param->getLocation(), Destructor);
10859 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10865 // Parameters with the pass_object_size attribute only need to be marked
10866 // constant at function definitions. Because we lack information about
10867 // whether we're on a declaration or definition when we're instantiating the
10868 // attribute, we need to check for constness here.
10869 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10870 if (!Param->getType().isConstQualified())
10871 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10872 << Attr->getSpelling() << 1;
10875 return HasInvalidParm;
10878 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10880 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10881 ASTContext &Context) {
10882 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10883 return Context.getDeclAlign(DRE->getDecl());
10885 if (const auto *ME = dyn_cast<MemberExpr>(E))
10886 return Context.getDeclAlign(ME->getMemberDecl());
10891 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10892 /// pointer cast increases the alignment requirements.
10893 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10894 // This is actually a lot of work to potentially be doing on every
10895 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10896 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10899 // Ignore dependent types.
10900 if (T->isDependentType() || Op->getType()->isDependentType())
10903 // Require that the destination be a pointer type.
10904 const PointerType *DestPtr = T->getAs<PointerType>();
10905 if (!DestPtr) return;
10907 // If the destination has alignment 1, we're done.
10908 QualType DestPointee = DestPtr->getPointeeType();
10909 if (DestPointee->isIncompleteType()) return;
10910 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10911 if (DestAlign.isOne()) return;
10913 // Require that the source be a pointer type.
10914 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10915 if (!SrcPtr) return;
10916 QualType SrcPointee = SrcPtr->getPointeeType();
10918 // Whitelist casts from cv void*. We already implicitly
10919 // whitelisted casts to cv void*, since they have alignment 1.
10920 // Also whitelist casts involving incomplete types, which implicitly
10921 // includes 'void'.
10922 if (SrcPointee->isIncompleteType()) return;
10924 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10926 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10927 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10928 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10929 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10930 if (UO->getOpcode() == UO_AddrOf)
10931 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10934 if (SrcAlign >= DestAlign) return;
10936 Diag(TRange.getBegin(), diag::warn_cast_align)
10937 << Op->getType() << T
10938 << static_cast<unsigned>(SrcAlign.getQuantity())
10939 << static_cast<unsigned>(DestAlign.getQuantity())
10940 << TRange << Op->getSourceRange();
10943 /// \brief Check whether this array fits the idiom of a size-one tail padded
10944 /// array member of a struct.
10946 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10947 /// commonly used to emulate flexible arrays in C89 code.
10948 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10949 const NamedDecl *ND) {
10950 if (Size != 1 || !ND) return false;
10952 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10953 if (!FD) return false;
10955 // Don't consider sizes resulting from macro expansions or template argument
10956 // substitution to form C89 tail-padded arrays.
10958 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10960 TypeLoc TL = TInfo->getTypeLoc();
10961 // Look through typedefs.
10962 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10963 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10964 TInfo = TDL->getTypeSourceInfo();
10967 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10968 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10969 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10975 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10976 if (!RD) return false;
10977 if (RD->isUnion()) return false;
10978 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10979 if (!CRD->isStandardLayout()) return false;
10982 // See if this is the last field decl in the record.
10983 const Decl *D = FD;
10984 while ((D = D->getNextDeclInContext()))
10985 if (isa<FieldDecl>(D))
10990 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10991 const ArraySubscriptExpr *ASE,
10992 bool AllowOnePastEnd, bool IndexNegated) {
10993 IndexExpr = IndexExpr->IgnoreParenImpCasts();
10994 if (IndexExpr->isValueDependent())
10997 const Type *EffectiveType =
10998 BaseExpr->getType()->getPointeeOrArrayElementType();
10999 BaseExpr = BaseExpr->IgnoreParenCasts();
11000 const ConstantArrayType *ArrayTy =
11001 Context.getAsConstantArrayType(BaseExpr->getType());
11005 llvm::APSInt index;
11006 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
11011 const NamedDecl *ND = nullptr;
11012 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11013 ND = dyn_cast<NamedDecl>(DRE->getDecl());
11014 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11015 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11017 if (index.isUnsigned() || !index.isNegative()) {
11018 llvm::APInt size = ArrayTy->getSize();
11019 if (!size.isStrictlyPositive())
11022 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
11023 if (BaseType != EffectiveType) {
11024 // Make sure we're comparing apples to apples when comparing index to size
11025 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11026 uint64_t array_typesize = Context.getTypeSize(BaseType);
11027 // Handle ptrarith_typesize being zero, such as when casting to void*
11028 if (!ptrarith_typesize) ptrarith_typesize = 1;
11029 if (ptrarith_typesize != array_typesize) {
11030 // There's a cast to a different size type involved
11031 uint64_t ratio = array_typesize / ptrarith_typesize;
11032 // TODO: Be smarter about handling cases where array_typesize is not a
11033 // multiple of ptrarith_typesize
11034 if (ptrarith_typesize * ratio == array_typesize)
11035 size *= llvm::APInt(size.getBitWidth(), ratio);
11039 if (size.getBitWidth() > index.getBitWidth())
11040 index = index.zext(size.getBitWidth());
11041 else if (size.getBitWidth() < index.getBitWidth())
11042 size = size.zext(index.getBitWidth());
11044 // For array subscripting the index must be less than size, but for pointer
11045 // arithmetic also allow the index (offset) to be equal to size since
11046 // computing the next address after the end of the array is legal and
11047 // commonly done e.g. in C++ iterators and range-based for loops.
11048 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11051 // Also don't warn for arrays of size 1 which are members of some
11052 // structure. These are often used to approximate flexible arrays in C89
11054 if (IsTailPaddedMemberArray(*this, size, ND))
11057 // Suppress the warning if the subscript expression (as identified by the
11058 // ']' location) and the index expression are both from macro expansions
11059 // within a system header.
11061 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11062 ASE->getRBracketLoc());
11063 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11064 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11065 IndexExpr->getLocStart());
11066 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11071 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11073 DiagID = diag::warn_array_index_exceeds_bounds;
11075 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11076 PDiag(DiagID) << index.toString(10, true)
11077 << size.toString(10, true)
11078 << (unsigned)size.getLimitedValue(~0U)
11079 << IndexExpr->getSourceRange());
11081 unsigned DiagID = diag::warn_array_index_precedes_bounds;
11083 DiagID = diag::warn_ptr_arith_precedes_bounds;
11084 if (index.isNegative()) index = -index;
11087 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11088 PDiag(DiagID) << index.toString(10, true)
11089 << IndexExpr->getSourceRange());
11093 // Try harder to find a NamedDecl to point at in the note.
11094 while (const ArraySubscriptExpr *ASE =
11095 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11096 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11097 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11098 ND = dyn_cast<NamedDecl>(DRE->getDecl());
11099 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11100 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11104 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11105 PDiag(diag::note_array_index_out_of_bounds)
11106 << ND->getDeclName());
11109 void Sema::CheckArrayAccess(const Expr *expr) {
11110 int AllowOnePastEnd = 0;
11112 expr = expr->IgnoreParenImpCasts();
11113 switch (expr->getStmtClass()) {
11114 case Stmt::ArraySubscriptExprClass: {
11115 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11116 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11117 AllowOnePastEnd > 0);
11120 case Stmt::OMPArraySectionExprClass: {
11121 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11122 if (ASE->getLowerBound())
11123 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11124 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11127 case Stmt::UnaryOperatorClass: {
11128 // Only unwrap the * and & unary operators
11129 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11130 expr = UO->getSubExpr();
11131 switch (UO->getOpcode()) {
11143 case Stmt::ConditionalOperatorClass: {
11144 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11145 if (const Expr *lhs = cond->getLHS())
11146 CheckArrayAccess(lhs);
11147 if (const Expr *rhs = cond->getRHS())
11148 CheckArrayAccess(rhs);
11151 case Stmt::CXXOperatorCallExprClass: {
11152 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11153 for (const auto *Arg : OCE->arguments())
11154 CheckArrayAccess(Arg);
11163 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11167 struct RetainCycleOwner {
11168 VarDecl *Variable = nullptr;
11170 SourceLocation Loc;
11171 bool Indirect = false;
11173 RetainCycleOwner() = default;
11175 void setLocsFrom(Expr *e) {
11176 Loc = e->getExprLoc();
11177 Range = e->getSourceRange();
11183 /// Consider whether capturing the given variable can possibly lead to
11184 /// a retain cycle.
11185 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11186 // In ARC, it's captured strongly iff the variable has __strong
11187 // lifetime. In MRR, it's captured strongly if the variable is
11188 // __block and has an appropriate type.
11189 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11192 owner.Variable = var;
11194 owner.setLocsFrom(ref);
11198 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11200 e = e->IgnoreParens();
11201 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11202 switch (cast->getCastKind()) {
11204 case CK_LValueBitCast:
11205 case CK_LValueToRValue:
11206 case CK_ARCReclaimReturnedObject:
11207 e = cast->getSubExpr();
11215 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11216 ObjCIvarDecl *ivar = ref->getDecl();
11217 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11220 // Try to find a retain cycle in the base.
11221 if (!findRetainCycleOwner(S, ref->getBase(), owner))
11224 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11225 owner.Indirect = true;
11229 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11230 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11231 if (!var) return false;
11232 return considerVariable(var, ref, owner);
11235 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11236 if (member->isArrow()) return false;
11238 // Don't count this as an indirect ownership.
11239 e = member->getBase();
11243 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11244 // Only pay attention to pseudo-objects on property references.
11245 ObjCPropertyRefExpr *pre
11246 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11248 if (!pre) return false;
11249 if (pre->isImplicitProperty()) return false;
11250 ObjCPropertyDecl *property = pre->getExplicitProperty();
11251 if (!property->isRetaining() &&
11252 !(property->getPropertyIvarDecl() &&
11253 property->getPropertyIvarDecl()->getType()
11254 .getObjCLifetime() == Qualifiers::OCL_Strong))
11257 owner.Indirect = true;
11258 if (pre->isSuperReceiver()) {
11259 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11260 if (!owner.Variable)
11262 owner.Loc = pre->getLocation();
11263 owner.Range = pre->getSourceRange();
11266 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11267 ->getSourceExpr());
11279 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11280 ASTContext &Context;
11282 Expr *Capturer = nullptr;
11283 bool VarWillBeReased = false;
11285 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11286 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11287 Context(Context), Variable(variable) {}
11289 void VisitDeclRefExpr(DeclRefExpr *ref) {
11290 if (ref->getDecl() == Variable && !Capturer)
11294 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11295 if (Capturer) return;
11296 Visit(ref->getBase());
11297 if (Capturer && ref->isFreeIvar())
11301 void VisitBlockExpr(BlockExpr *block) {
11302 // Look inside nested blocks
11303 if (block->getBlockDecl()->capturesVariable(Variable))
11304 Visit(block->getBlockDecl()->getBody());
11307 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11308 if (Capturer) return;
11309 if (OVE->getSourceExpr())
11310 Visit(OVE->getSourceExpr());
11313 void VisitBinaryOperator(BinaryOperator *BinOp) {
11314 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11316 Expr *LHS = BinOp->getLHS();
11317 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11318 if (DRE->getDecl() != Variable)
11320 if (Expr *RHS = BinOp->getRHS()) {
11321 RHS = RHS->IgnoreParenCasts();
11322 llvm::APSInt Value;
11324 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11332 /// Check whether the given argument is a block which captures a
11334 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11335 assert(owner.Variable && owner.Loc.isValid());
11337 e = e->IgnoreParenCasts();
11339 // Look through [^{...} copy] and Block_copy(^{...}).
11340 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11341 Selector Cmd = ME->getSelector();
11342 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11343 e = ME->getInstanceReceiver();
11346 e = e->IgnoreParenCasts();
11348 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11349 if (CE->getNumArgs() == 1) {
11350 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11352 const IdentifierInfo *FnI = Fn->getIdentifier();
11353 if (FnI && FnI->isStr("_Block_copy")) {
11354 e = CE->getArg(0)->IgnoreParenCasts();
11360 BlockExpr *block = dyn_cast<BlockExpr>(e);
11361 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11364 FindCaptureVisitor visitor(S.Context, owner.Variable);
11365 visitor.Visit(block->getBlockDecl()->getBody());
11366 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11369 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11370 RetainCycleOwner &owner) {
11372 assert(owner.Variable && owner.Loc.isValid());
11374 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11375 << owner.Variable << capturer->getSourceRange();
11376 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11377 << owner.Indirect << owner.Range;
11380 /// Check for a keyword selector that starts with the word 'add' or
11382 static bool isSetterLikeSelector(Selector sel) {
11383 if (sel.isUnarySelector()) return false;
11385 StringRef str = sel.getNameForSlot(0);
11386 while (!str.empty() && str.front() == '_') str = str.substr(1);
11387 if (str.startswith("set"))
11388 str = str.substr(3);
11389 else if (str.startswith("add")) {
11390 // Specially whitelist 'addOperationWithBlock:'.
11391 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11393 str = str.substr(3);
11398 if (str.empty()) return true;
11399 return !isLowercase(str.front());
11402 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11403 ObjCMessageExpr *Message) {
11404 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11405 Message->getReceiverInterface(),
11406 NSAPI::ClassId_NSMutableArray);
11407 if (!IsMutableArray) {
11411 Selector Sel = Message->getSelector();
11413 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11414 S.NSAPIObj->getNSArrayMethodKind(Sel);
11419 NSAPI::NSArrayMethodKind MK = *MKOpt;
11422 case NSAPI::NSMutableArr_addObject:
11423 case NSAPI::NSMutableArr_insertObjectAtIndex:
11424 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11426 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11437 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11438 ObjCMessageExpr *Message) {
11439 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11440 Message->getReceiverInterface(),
11441 NSAPI::ClassId_NSMutableDictionary);
11442 if (!IsMutableDictionary) {
11446 Selector Sel = Message->getSelector();
11448 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11449 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11454 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11457 case NSAPI::NSMutableDict_setObjectForKey:
11458 case NSAPI::NSMutableDict_setValueForKey:
11459 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11469 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11470 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11471 Message->getReceiverInterface(),
11472 NSAPI::ClassId_NSMutableSet);
11474 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11475 Message->getReceiverInterface(),
11476 NSAPI::ClassId_NSMutableOrderedSet);
11477 if (!IsMutableSet && !IsMutableOrderedSet) {
11481 Selector Sel = Message->getSelector();
11483 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11488 NSAPI::NSSetMethodKind MK = *MKOpt;
11491 case NSAPI::NSMutableSet_addObject:
11492 case NSAPI::NSOrderedSet_setObjectAtIndex:
11493 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11494 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11496 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11503 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11504 if (!Message->isInstanceMessage()) {
11508 Optional<int> ArgOpt;
11510 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11511 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11512 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11516 int ArgIndex = *ArgOpt;
11518 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11519 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11520 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11523 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11524 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11525 if (ArgRE->isObjCSelfExpr()) {
11526 Diag(Message->getSourceRange().getBegin(),
11527 diag::warn_objc_circular_container)
11528 << ArgRE->getDecl()->getName() << StringRef("super");
11532 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11534 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11535 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11538 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11539 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11540 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11541 ValueDecl *Decl = ReceiverRE->getDecl();
11542 Diag(Message->getSourceRange().getBegin(),
11543 diag::warn_objc_circular_container)
11544 << Decl->getName() << Decl->getName();
11545 if (!ArgRE->isObjCSelfExpr()) {
11546 Diag(Decl->getLocation(),
11547 diag::note_objc_circular_container_declared_here)
11548 << Decl->getName();
11552 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11553 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11554 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11555 ObjCIvarDecl *Decl = IvarRE->getDecl();
11556 Diag(Message->getSourceRange().getBegin(),
11557 diag::warn_objc_circular_container)
11558 << Decl->getName() << Decl->getName();
11559 Diag(Decl->getLocation(),
11560 diag::note_objc_circular_container_declared_here)
11561 << Decl->getName();
11568 /// Check a message send to see if it's likely to cause a retain cycle.
11569 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11570 // Only check instance methods whose selector looks like a setter.
11571 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11574 // Try to find a variable that the receiver is strongly owned by.
11575 RetainCycleOwner owner;
11576 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11577 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11580 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11581 owner.Variable = getCurMethodDecl()->getSelfDecl();
11582 owner.Loc = msg->getSuperLoc();
11583 owner.Range = msg->getSuperLoc();
11586 // Check whether the receiver is captured by any of the arguments.
11587 const ObjCMethodDecl *MD = msg->getMethodDecl();
11588 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11589 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11590 // noescape blocks should not be retained by the method.
11591 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11593 return diagnoseRetainCycle(*this, capturer, owner);
11598 /// Check a property assign to see if it's likely to cause a retain cycle.
11599 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11600 RetainCycleOwner owner;
11601 if (!findRetainCycleOwner(*this, receiver, owner))
11604 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11605 diagnoseRetainCycle(*this, capturer, owner);
11608 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11609 RetainCycleOwner Owner;
11610 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11613 // Because we don't have an expression for the variable, we have to set the
11614 // location explicitly here.
11615 Owner.Loc = Var->getLocation();
11616 Owner.Range = Var->getSourceRange();
11618 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11619 diagnoseRetainCycle(*this, Capturer, Owner);
11622 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11623 Expr *RHS, bool isProperty) {
11624 // Check if RHS is an Objective-C object literal, which also can get
11625 // immediately zapped in a weak reference. Note that we explicitly
11626 // allow ObjCStringLiterals, since those are designed to never really die.
11627 RHS = RHS->IgnoreParenImpCasts();
11629 // This enum needs to match with the 'select' in
11630 // warn_objc_arc_literal_assign (off-by-1).
11631 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11632 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11635 S.Diag(Loc, diag::warn_arc_literal_assign)
11637 << (isProperty ? 0 : 1)
11638 << RHS->getSourceRange();
11643 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11644 Qualifiers::ObjCLifetime LT,
11645 Expr *RHS, bool isProperty) {
11646 // Strip off any implicit cast added to get to the one ARC-specific.
11647 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11648 if (cast->getCastKind() == CK_ARCConsumeObject) {
11649 S.Diag(Loc, diag::warn_arc_retained_assign)
11650 << (LT == Qualifiers::OCL_ExplicitNone)
11651 << (isProperty ? 0 : 1)
11652 << RHS->getSourceRange();
11655 RHS = cast->getSubExpr();
11658 if (LT == Qualifiers::OCL_Weak &&
11659 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11665 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11666 QualType LHS, Expr *RHS) {
11667 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11669 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11672 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11678 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11679 Expr *LHS, Expr *RHS) {
11681 // PropertyRef on LHS type need be directly obtained from
11682 // its declaration as it has a PseudoType.
11683 ObjCPropertyRefExpr *PRE
11684 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11685 if (PRE && !PRE->isImplicitProperty()) {
11686 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11688 LHSType = PD->getType();
11691 if (LHSType.isNull())
11692 LHSType = LHS->getType();
11694 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11696 if (LT == Qualifiers::OCL_Weak) {
11697 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11698 getCurFunction()->markSafeWeakUse(LHS);
11701 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11704 // FIXME. Check for other life times.
11705 if (LT != Qualifiers::OCL_None)
11709 if (PRE->isImplicitProperty())
11711 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11715 unsigned Attributes = PD->getPropertyAttributes();
11716 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11717 // when 'assign' attribute was not explicitly specified
11718 // by user, ignore it and rely on property type itself
11719 // for lifetime info.
11720 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11721 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11722 LHSType->isObjCRetainableType())
11725 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11726 if (cast->getCastKind() == CK_ARCConsumeObject) {
11727 Diag(Loc, diag::warn_arc_retained_property_assign)
11728 << RHS->getSourceRange();
11731 RHS = cast->getSubExpr();
11734 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11735 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11741 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11743 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11744 SourceLocation StmtLoc,
11745 const NullStmt *Body) {
11746 // Do not warn if the body is a macro that expands to nothing, e.g:
11751 if (Body->hasLeadingEmptyMacro())
11754 // Get line numbers of statement and body.
11755 bool StmtLineInvalid;
11756 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11758 if (StmtLineInvalid)
11761 bool BodyLineInvalid;
11762 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11764 if (BodyLineInvalid)
11767 // Warn if null statement and body are on the same line.
11768 if (StmtLine != BodyLine)
11774 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11777 // Since this is a syntactic check, don't emit diagnostic for template
11778 // instantiations, this just adds noise.
11779 if (CurrentInstantiationScope)
11782 // The body should be a null statement.
11783 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11787 // Do the usual checks.
11788 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11791 Diag(NBody->getSemiLoc(), DiagID);
11792 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11795 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11796 const Stmt *PossibleBody) {
11797 assert(!CurrentInstantiationScope); // Ensured by caller
11799 SourceLocation StmtLoc;
11802 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11803 StmtLoc = FS->getRParenLoc();
11804 Body = FS->getBody();
11805 DiagID = diag::warn_empty_for_body;
11806 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11807 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11808 Body = WS->getBody();
11809 DiagID = diag::warn_empty_while_body;
11811 return; // Neither `for' nor `while'.
11813 // The body should be a null statement.
11814 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11818 // Skip expensive checks if diagnostic is disabled.
11819 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11822 // Do the usual checks.
11823 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11826 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11827 // noise level low, emit diagnostics only if for/while is followed by a
11828 // CompoundStmt, e.g.:
11829 // for (int i = 0; i < n; i++);
11833 // or if for/while is followed by a statement with more indentation
11834 // than for/while itself:
11835 // for (int i = 0; i < n; i++);
11837 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11838 if (!ProbableTypo) {
11839 bool BodyColInvalid;
11840 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11841 PossibleBody->getLocStart(),
11843 if (BodyColInvalid)
11846 bool StmtColInvalid;
11847 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11850 if (StmtColInvalid)
11853 if (BodyCol > StmtCol)
11854 ProbableTypo = true;
11857 if (ProbableTypo) {
11858 Diag(NBody->getSemiLoc(), DiagID);
11859 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11863 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11865 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11866 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11867 SourceLocation OpLoc) {
11868 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11871 if (inTemplateInstantiation())
11874 // Strip parens and casts away.
11875 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11876 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11878 // Check for a call expression
11879 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11880 if (!CE || CE->getNumArgs() != 1)
11883 // Check for a call to std::move
11884 if (!CE->isCallToStdMove())
11887 // Get argument from std::move
11888 RHSExpr = CE->getArg(0);
11890 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11891 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11893 // Two DeclRefExpr's, check that the decls are the same.
11894 if (LHSDeclRef && RHSDeclRef) {
11895 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11897 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11898 RHSDeclRef->getDecl()->getCanonicalDecl())
11901 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11902 << LHSExpr->getSourceRange()
11903 << RHSExpr->getSourceRange();
11907 // Member variables require a different approach to check for self moves.
11908 // MemberExpr's are the same if every nested MemberExpr refers to the same
11909 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11910 // the base Expr's are CXXThisExpr's.
11911 const Expr *LHSBase = LHSExpr;
11912 const Expr *RHSBase = RHSExpr;
11913 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11914 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11915 if (!LHSME || !RHSME)
11918 while (LHSME && RHSME) {
11919 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11920 RHSME->getMemberDecl()->getCanonicalDecl())
11923 LHSBase = LHSME->getBase();
11924 RHSBase = RHSME->getBase();
11925 LHSME = dyn_cast<MemberExpr>(LHSBase);
11926 RHSME = dyn_cast<MemberExpr>(RHSBase);
11929 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11930 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11931 if (LHSDeclRef && RHSDeclRef) {
11932 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11934 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11935 RHSDeclRef->getDecl()->getCanonicalDecl())
11938 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11939 << LHSExpr->getSourceRange()
11940 << RHSExpr->getSourceRange();
11944 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11945 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11946 << LHSExpr->getSourceRange()
11947 << RHSExpr->getSourceRange();
11950 //===--- Layout compatibility ----------------------------------------------//
11952 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11954 /// \brief Check if two enumeration types are layout-compatible.
11955 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11956 // C++11 [dcl.enum] p8:
11957 // Two enumeration types are layout-compatible if they have the same
11958 // underlying type.
11959 return ED1->isComplete() && ED2->isComplete() &&
11960 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11963 /// \brief Check if two fields are layout-compatible.
11964 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
11965 FieldDecl *Field2) {
11966 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11969 if (Field1->isBitField() != Field2->isBitField())
11972 if (Field1->isBitField()) {
11973 // Make sure that the bit-fields are the same length.
11974 unsigned Bits1 = Field1->getBitWidthValue(C);
11975 unsigned Bits2 = Field2->getBitWidthValue(C);
11977 if (Bits1 != Bits2)
11984 /// \brief Check if two standard-layout structs are layout-compatible.
11985 /// (C++11 [class.mem] p17)
11986 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
11988 // If both records are C++ classes, check that base classes match.
11989 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11990 // If one of records is a CXXRecordDecl we are in C++ mode,
11991 // thus the other one is a CXXRecordDecl, too.
11992 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11993 // Check number of base classes.
11994 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11997 // Check the base classes.
11998 for (CXXRecordDecl::base_class_const_iterator
11999 Base1 = D1CXX->bases_begin(),
12000 BaseEnd1 = D1CXX->bases_end(),
12001 Base2 = D2CXX->bases_begin();
12003 ++Base1, ++Base2) {
12004 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12007 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12008 // If only RD2 is a C++ class, it should have zero base classes.
12009 if (D2CXX->getNumBases() > 0)
12013 // Check the fields.
12014 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12015 Field2End = RD2->field_end(),
12016 Field1 = RD1->field_begin(),
12017 Field1End = RD1->field_end();
12018 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12019 if (!isLayoutCompatible(C, *Field1, *Field2))
12022 if (Field1 != Field1End || Field2 != Field2End)
12028 /// \brief Check if two standard-layout unions are layout-compatible.
12029 /// (C++11 [class.mem] p18)
12030 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12032 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
12033 for (auto *Field2 : RD2->fields())
12034 UnmatchedFields.insert(Field2);
12036 for (auto *Field1 : RD1->fields()) {
12037 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12038 I = UnmatchedFields.begin(),
12039 E = UnmatchedFields.end();
12041 for ( ; I != E; ++I) {
12042 if (isLayoutCompatible(C, Field1, *I)) {
12043 bool Result = UnmatchedFields.erase(*I);
12053 return UnmatchedFields.empty();
12056 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12058 if (RD1->isUnion() != RD2->isUnion())
12061 if (RD1->isUnion())
12062 return isLayoutCompatibleUnion(C, RD1, RD2);
12064 return isLayoutCompatibleStruct(C, RD1, RD2);
12067 /// \brief Check if two types are layout-compatible in C++11 sense.
12068 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12069 if (T1.isNull() || T2.isNull())
12072 // C++11 [basic.types] p11:
12073 // If two types T1 and T2 are the same type, then T1 and T2 are
12074 // layout-compatible types.
12075 if (C.hasSameType(T1, T2))
12078 T1 = T1.getCanonicalType().getUnqualifiedType();
12079 T2 = T2.getCanonicalType().getUnqualifiedType();
12081 const Type::TypeClass TC1 = T1->getTypeClass();
12082 const Type::TypeClass TC2 = T2->getTypeClass();
12087 if (TC1 == Type::Enum) {
12088 return isLayoutCompatible(C,
12089 cast<EnumType>(T1)->getDecl(),
12090 cast<EnumType>(T2)->getDecl());
12091 } else if (TC1 == Type::Record) {
12092 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12095 return isLayoutCompatible(C,
12096 cast<RecordType>(T1)->getDecl(),
12097 cast<RecordType>(T2)->getDecl());
12103 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12105 /// \brief Given a type tag expression find the type tag itself.
12107 /// \param TypeExpr Type tag expression, as it appears in user's code.
12109 /// \param VD Declaration of an identifier that appears in a type tag.
12111 /// \param MagicValue Type tag magic value.
12112 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12113 const ValueDecl **VD, uint64_t *MagicValue) {
12118 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12120 switch (TypeExpr->getStmtClass()) {
12121 case Stmt::UnaryOperatorClass: {
12122 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12123 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12124 TypeExpr = UO->getSubExpr();
12130 case Stmt::DeclRefExprClass: {
12131 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12132 *VD = DRE->getDecl();
12136 case Stmt::IntegerLiteralClass: {
12137 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12138 llvm::APInt MagicValueAPInt = IL->getValue();
12139 if (MagicValueAPInt.getActiveBits() <= 64) {
12140 *MagicValue = MagicValueAPInt.getZExtValue();
12146 case Stmt::BinaryConditionalOperatorClass:
12147 case Stmt::ConditionalOperatorClass: {
12148 const AbstractConditionalOperator *ACO =
12149 cast<AbstractConditionalOperator>(TypeExpr);
12151 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12153 TypeExpr = ACO->getTrueExpr();
12155 TypeExpr = ACO->getFalseExpr();
12161 case Stmt::BinaryOperatorClass: {
12162 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12163 if (BO->getOpcode() == BO_Comma) {
12164 TypeExpr = BO->getRHS();
12176 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
12178 /// \param TypeExpr Expression that specifies a type tag.
12180 /// \param MagicValues Registered magic values.
12182 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12185 /// \param TypeInfo Information about the corresponding C type.
12187 /// \returns true if the corresponding C type was found.
12188 static bool GetMatchingCType(
12189 const IdentifierInfo *ArgumentKind,
12190 const Expr *TypeExpr, const ASTContext &Ctx,
12191 const llvm::DenseMap<Sema::TypeTagMagicValue,
12192 Sema::TypeTagData> *MagicValues,
12193 bool &FoundWrongKind,
12194 Sema::TypeTagData &TypeInfo) {
12195 FoundWrongKind = false;
12197 // Variable declaration that has type_tag_for_datatype attribute.
12198 const ValueDecl *VD = nullptr;
12200 uint64_t MagicValue;
12202 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12206 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12207 if (I->getArgumentKind() != ArgumentKind) {
12208 FoundWrongKind = true;
12211 TypeInfo.Type = I->getMatchingCType();
12212 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12213 TypeInfo.MustBeNull = I->getMustBeNull();
12222 llvm::DenseMap<Sema::TypeTagMagicValue,
12223 Sema::TypeTagData>::const_iterator I =
12224 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12225 if (I == MagicValues->end())
12228 TypeInfo = I->second;
12232 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12233 uint64_t MagicValue, QualType Type,
12234 bool LayoutCompatible,
12236 if (!TypeTagForDatatypeMagicValues)
12237 TypeTagForDatatypeMagicValues.reset(
12238 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12240 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12241 (*TypeTagForDatatypeMagicValues)[Magic] =
12242 TypeTagData(Type, LayoutCompatible, MustBeNull);
12245 static bool IsSameCharType(QualType T1, QualType T2) {
12246 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12250 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12254 BuiltinType::Kind T1Kind = BT1->getKind();
12255 BuiltinType::Kind T2Kind = BT2->getKind();
12257 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12258 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12259 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12260 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12263 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12264 const ArrayRef<const Expr *> ExprArgs,
12265 SourceLocation CallSiteLoc) {
12266 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12267 bool IsPointerAttr = Attr->getIsPointer();
12269 // Retrieve the argument representing the 'type_tag'.
12270 if (Attr->getTypeTagIdx() >= ExprArgs.size()) {
12271 // Add 1 to display the user's specified value.
12272 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12273 << 0 << Attr->getTypeTagIdx() + 1;
12276 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12277 bool FoundWrongKind;
12278 TypeTagData TypeInfo;
12279 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12280 TypeTagForDatatypeMagicValues.get(),
12281 FoundWrongKind, TypeInfo)) {
12282 if (FoundWrongKind)
12283 Diag(TypeTagExpr->getExprLoc(),
12284 diag::warn_type_tag_for_datatype_wrong_kind)
12285 << TypeTagExpr->getSourceRange();
12289 // Retrieve the argument representing the 'arg_idx'.
12290 if (Attr->getArgumentIdx() >= ExprArgs.size()) {
12291 // Add 1 to display the user's specified value.
12292 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12293 << 1 << Attr->getArgumentIdx() + 1;
12296 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12297 if (IsPointerAttr) {
12298 // Skip implicit cast of pointer to `void *' (as a function argument).
12299 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12300 if (ICE->getType()->isVoidPointerType() &&
12301 ICE->getCastKind() == CK_BitCast)
12302 ArgumentExpr = ICE->getSubExpr();
12304 QualType ArgumentType = ArgumentExpr->getType();
12306 // Passing a `void*' pointer shouldn't trigger a warning.
12307 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12310 if (TypeInfo.MustBeNull) {
12311 // Type tag with matching void type requires a null pointer.
12312 if (!ArgumentExpr->isNullPointerConstant(Context,
12313 Expr::NPC_ValueDependentIsNotNull)) {
12314 Diag(ArgumentExpr->getExprLoc(),
12315 diag::warn_type_safety_null_pointer_required)
12316 << ArgumentKind->getName()
12317 << ArgumentExpr->getSourceRange()
12318 << TypeTagExpr->getSourceRange();
12323 QualType RequiredType = TypeInfo.Type;
12325 RequiredType = Context.getPointerType(RequiredType);
12327 bool mismatch = false;
12328 if (!TypeInfo.LayoutCompatible) {
12329 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12331 // C++11 [basic.fundamental] p1:
12332 // Plain char, signed char, and unsigned char are three distinct types.
12334 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12335 // char' depending on the current char signedness mode.
12337 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12338 RequiredType->getPointeeType())) ||
12339 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12343 mismatch = !isLayoutCompatible(Context,
12344 ArgumentType->getPointeeType(),
12345 RequiredType->getPointeeType());
12347 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12350 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12351 << ArgumentType << ArgumentKind
12352 << TypeInfo.LayoutCompatible << RequiredType
12353 << ArgumentExpr->getSourceRange()
12354 << TypeTagExpr->getSourceRange();
12357 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12358 CharUnits Alignment) {
12359 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12362 void Sema::DiagnoseMisalignedMembers() {
12363 for (MisalignedMember &m : MisalignedMembers) {
12364 const NamedDecl *ND = m.RD;
12365 if (ND->getName().empty()) {
12366 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12369 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12370 << m.MD << ND << m.E->getSourceRange();
12372 MisalignedMembers.clear();
12375 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12376 E = E->IgnoreParens();
12377 if (!T->isPointerType() && !T->isIntegerType())
12379 if (isa<UnaryOperator>(E) &&
12380 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12381 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12382 if (isa<MemberExpr>(Op)) {
12383 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12384 MisalignedMember(Op));
12385 if (MA != MisalignedMembers.end() &&
12386 (T->isIntegerType() ||
12387 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12388 Context.getTypeAlignInChars(
12389 T->getPointeeType()) <= MA->Alignment))))
12390 MisalignedMembers.erase(MA);
12395 void Sema::RefersToMemberWithReducedAlignment(
12397 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12399 const auto *ME = dyn_cast<MemberExpr>(E);
12403 // No need to check expressions with an __unaligned-qualified type.
12404 if (E->getType().getQualifiers().hasUnaligned())
12407 // For a chain of MemberExpr like "a.b.c.d" this list
12408 // will keep FieldDecl's like [d, c, b].
12409 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12410 const MemberExpr *TopME = nullptr;
12411 bool AnyIsPacked = false;
12413 QualType BaseType = ME->getBase()->getType();
12415 BaseType = BaseType->getPointeeType();
12416 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12417 if (RD->isInvalidDecl())
12420 ValueDecl *MD = ME->getMemberDecl();
12421 auto *FD = dyn_cast<FieldDecl>(MD);
12422 // We do not care about non-data members.
12423 if (!FD || FD->isInvalidDecl())
12427 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12428 ReverseMemberChain.push_back(FD);
12431 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12433 assert(TopME && "We did not compute a topmost MemberExpr!");
12435 // Not the scope of this diagnostic.
12439 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12440 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12441 // TODO: The innermost base of the member expression may be too complicated.
12442 // For now, just disregard these cases. This is left for future
12444 if (!DRE && !isa<CXXThisExpr>(TopBase))
12447 // Alignment expected by the whole expression.
12448 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12450 // No need to do anything else with this case.
12451 if (ExpectedAlignment.isOne())
12454 // Synthesize offset of the whole access.
12456 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12458 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12461 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12462 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12463 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12465 // The base expression of the innermost MemberExpr may give
12466 // stronger guarantees than the class containing the member.
12467 if (DRE && !TopME->isArrow()) {
12468 const ValueDecl *VD = DRE->getDecl();
12469 if (!VD->getType()->isReferenceType())
12470 CompleteObjectAlignment =
12471 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12474 // Check if the synthesized offset fulfills the alignment.
12475 if (Offset % ExpectedAlignment != 0 ||
12476 // It may fulfill the offset it but the effective alignment may still be
12477 // lower than the expected expression alignment.
12478 CompleteObjectAlignment < ExpectedAlignment) {
12479 // If this happens, we want to determine a sensible culprit of this.
12480 // Intuitively, watching the chain of member expressions from right to
12481 // left, we start with the required alignment (as required by the field
12482 // type) but some packed attribute in that chain has reduced the alignment.
12483 // It may happen that another packed structure increases it again. But if
12484 // we are here such increase has not been enough. So pointing the first
12485 // FieldDecl that either is packed or else its RecordDecl is,
12486 // seems reasonable.
12487 FieldDecl *FD = nullptr;
12488 CharUnits Alignment;
12489 for (FieldDecl *FDI : ReverseMemberChain) {
12490 if (FDI->hasAttr<PackedAttr>() ||
12491 FDI->getParent()->hasAttr<PackedAttr>()) {
12493 Alignment = std::min(
12494 Context.getTypeAlignInChars(FD->getType()),
12495 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12499 assert(FD && "We did not find a packed FieldDecl!");
12500 Action(E, FD->getParent(), FD, Alignment);
12504 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12505 using namespace std::placeholders;
12507 RefersToMemberWithReducedAlignment(
12508 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,