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/ASTContext.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExprOpenMP.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/Locale.h"
42 #include "llvm/Support/raw_ostream.h"
44 using namespace clang;
47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48 unsigned ByteNo) const {
49 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50 Context.getTargetInfo());
53 /// Checks that a call expression's argument count is the desired number.
54 /// This is useful when doing custom type-checking. Returns true on error.
55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56 unsigned argCount = call->getNumArgs();
57 if (argCount == desiredArgCount) return false;
59 if (argCount < desiredArgCount)
60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61 << 0 /*function call*/ << desiredArgCount << argCount
62 << call->getSourceRange();
64 // Highlight all the excess arguments.
65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66 call->getArg(argCount - 1)->getLocEnd());
68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69 << 0 /*function call*/ << desiredArgCount << argCount
70 << call->getArg(1)->getSourceRange();
73 /// Check that the first argument to __builtin_annotation is an integer
74 /// and the second argument is a non-wide string literal.
75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76 if (checkArgCount(S, TheCall, 2))
79 // First argument should be an integer.
80 Expr *ValArg = TheCall->getArg(0);
81 QualType Ty = ValArg->getType();
82 if (!Ty->isIntegerType()) {
83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84 << ValArg->getSourceRange();
88 // Second argument should be a constant string.
89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91 if (!Literal || !Literal->isAscii()) {
92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93 << StrArg->getSourceRange();
101 /// Check that the argument to __builtin_addressof is a glvalue, and set the
102 /// result type to the corresponding pointer type.
103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104 if (checkArgCount(S, TheCall, 1))
107 ExprResult Arg(TheCall->getArg(0));
108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109 if (ResultType.isNull())
112 TheCall->setArg(0, Arg.get());
113 TheCall->setType(ResultType);
117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118 if (checkArgCount(S, TheCall, 3))
121 // First two arguments should be integers.
122 for (unsigned I = 0; I < 2; ++I) {
123 Expr *Arg = TheCall->getArg(I);
124 QualType Ty = Arg->getType();
125 if (!Ty->isIntegerType()) {
126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127 << Ty << Arg->getSourceRange();
132 // Third argument should be a pointer to a non-const integer.
133 // IRGen correctly handles volatile, restrict, and address spaces, and
134 // the other qualifiers aren't possible.
136 Expr *Arg = TheCall->getArg(2);
137 QualType Ty = Arg->getType();
138 const auto *PtrTy = Ty->getAs<PointerType>();
139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140 !PtrTy->getPointeeType().isConstQualified())) {
141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142 << Ty << Arg->getSourceRange();
150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 CallExpr *TheCall, unsigned SizeIdx,
152 unsigned DstSizeIdx) {
153 if (TheCall->getNumArgs() <= SizeIdx ||
154 TheCall->getNumArgs() <= DstSizeIdx)
157 const Expr *SizeArg = TheCall->getArg(SizeIdx);
158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
160 llvm::APSInt Size, DstSize;
162 // find out if both sizes are known at compile time
163 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
167 if (Size.ule(DstSize))
170 // confirmed overflow so generate the diagnostic.
171 IdentifierInfo *FnName = FDecl->getIdentifier();
172 SourceLocation SL = TheCall->getLocStart();
173 SourceRange SR = TheCall->getSourceRange();
175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179 if (checkArgCount(S, BuiltinCall, 2))
182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184 Expr *Call = BuiltinCall->getArg(0);
185 Expr *Chain = BuiltinCall->getArg(1);
187 if (Call->getStmtClass() != Stmt::CallExprClass) {
188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189 << Call->getSourceRange();
193 auto CE = cast<CallExpr>(Call);
194 if (CE->getCallee()->getType()->isBlockPointerType()) {
195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196 << Call->getSourceRange();
200 const Decl *TargetDecl = CE->getCalleeDecl();
201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202 if (FD->getBuiltinID()) {
203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204 << Call->getSourceRange();
208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210 << Call->getSourceRange();
214 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215 if (ChainResult.isInvalid())
217 if (!ChainResult.get()->getType()->isPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219 << Chain->getSourceRange();
223 QualType ReturnTy = CE->getCallReturnType(S.Context);
224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225 QualType BuiltinTy = S.Context.getFunctionType(
226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
232 BuiltinCall->setType(CE->getType());
233 BuiltinCall->setValueKind(CE->getValueKind());
234 BuiltinCall->setObjectKind(CE->getObjectKind());
235 BuiltinCall->setCallee(Builtin);
236 BuiltinCall->setArg(1, ChainResult.get());
241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242 Scope::ScopeFlags NeededScopeFlags,
244 // Scopes aren't available during instantiation. Fortunately, builtin
245 // functions cannot be template args so they cannot be formed through template
246 // instantiation. Therefore checking once during the parse is sufficient.
247 if (!SemaRef.ActiveTemplateInstantiations.empty())
250 Scope *S = SemaRef.getCurScope();
251 while (S && !S->isSEHExceptScope())
253 if (!S || !(S->getFlags() & NeededScopeFlags)) {
254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256 << DRE->getDecl()->getIdentifier();
263 static inline bool isBlockPointer(Expr *Arg) {
264 return Arg->getType()->isBlockPointerType();
267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268 /// void*, which is a requirement of device side enqueue.
269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270 const BlockPointerType *BPT =
271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272 ArrayRef<QualType> Params =
273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274 unsigned ArgCounter = 0;
275 bool IllegalParams = false;
276 // Iterate through the block parameters until either one is found that is not
277 // a local void*, or the block is valid.
278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279 I != E; ++I, ++ArgCounter) {
280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282 LangAS::opencl_local) {
283 // Get the location of the error. If a block literal has been passed
284 // (BlockExpr) then we can point straight to the offending argument,
285 // else we just point to the variable reference.
286 SourceLocation ErrorLoc;
287 if (isa<BlockExpr>(BlockArg)) {
288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290 } else if (isa<DeclRefExpr>(BlockArg)) {
291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295 IllegalParams = true;
299 return IllegalParams;
302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303 /// get_kernel_work_group_size
304 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306 if (checkArgCount(S, TheCall, 1))
309 Expr *BlockArg = TheCall->getArg(0);
310 if (!isBlockPointer(BlockArg)) {
311 S.Diag(BlockArg->getLocStart(),
312 diag::err_opencl_enqueue_kernel_expected_type) << "block";
315 return checkOpenCLBlockArgs(S, BlockArg);
318 /// Diagnose integer type and any valid implicit convertion to it.
319 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
320 const QualType &IntType);
322 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
323 unsigned Start, unsigned End) {
324 bool IllegalParams = false;
325 for (unsigned I = Start; I <= End; ++I)
326 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
327 S.Context.getSizeType());
328 return IllegalParams;
331 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
332 /// 'local void*' parameter of passed block.
333 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
335 unsigned NumNonVarArgs) {
336 const BlockPointerType *BPT =
337 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
338 unsigned NumBlockParams =
339 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
340 unsigned TotalNumArgs = TheCall->getNumArgs();
342 // For each argument passed to the block, a corresponding uint needs to
343 // be passed to describe the size of the local memory.
344 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
345 S.Diag(TheCall->getLocStart(),
346 diag::err_opencl_enqueue_kernel_local_size_args);
350 // Check that the sizes of the local memory are specified by integers.
351 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
355 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
356 /// overload formats specified in Table 6.13.17.1.
357 /// int enqueue_kernel(queue_t queue,
358 /// kernel_enqueue_flags_t flags,
359 /// const ndrange_t ndrange,
360 /// void (^block)(void))
361 /// int enqueue_kernel(queue_t queue,
362 /// kernel_enqueue_flags_t flags,
363 /// const ndrange_t ndrange,
364 /// uint num_events_in_wait_list,
365 /// clk_event_t *event_wait_list,
366 /// clk_event_t *event_ret,
367 /// void (^block)(void))
368 /// int enqueue_kernel(queue_t queue,
369 /// kernel_enqueue_flags_t flags,
370 /// const ndrange_t ndrange,
371 /// void (^block)(local void*, ...),
373 /// int enqueue_kernel(queue_t queue,
374 /// kernel_enqueue_flags_t flags,
375 /// const ndrange_t ndrange,
376 /// uint num_events_in_wait_list,
377 /// clk_event_t *event_wait_list,
378 /// clk_event_t *event_ret,
379 /// void (^block)(local void*, ...),
381 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
382 unsigned NumArgs = TheCall->getNumArgs();
385 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
389 Expr *Arg0 = TheCall->getArg(0);
390 Expr *Arg1 = TheCall->getArg(1);
391 Expr *Arg2 = TheCall->getArg(2);
392 Expr *Arg3 = TheCall->getArg(3);
394 // First argument always needs to be a queue_t type.
395 if (!Arg0->getType()->isQueueT()) {
396 S.Diag(TheCall->getArg(0)->getLocStart(),
397 diag::err_opencl_enqueue_kernel_expected_type)
398 << S.Context.OCLQueueTy;
402 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
403 if (!Arg1->getType()->isIntegerType()) {
404 S.Diag(TheCall->getArg(1)->getLocStart(),
405 diag::err_opencl_enqueue_kernel_expected_type)
406 << "'kernel_enqueue_flags_t' (i.e. uint)";
410 // Third argument is always an ndrange_t type.
411 if (!Arg2->getType()->isNDRangeT()) {
412 S.Diag(TheCall->getArg(2)->getLocStart(),
413 diag::err_opencl_enqueue_kernel_expected_type)
414 << S.Context.OCLNDRangeTy;
418 // With four arguments, there is only one form that the function could be
419 // called in: no events and no variable arguments.
421 // check that the last argument is the right block type.
422 if (!isBlockPointer(Arg3)) {
423 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
427 // we have a block type, check the prototype
428 const BlockPointerType *BPT =
429 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
430 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
431 S.Diag(Arg3->getLocStart(),
432 diag::err_opencl_enqueue_kernel_blocks_no_args);
437 // we can have block + varargs.
438 if (isBlockPointer(Arg3))
439 return (checkOpenCLBlockArgs(S, Arg3) ||
440 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
441 // last two cases with either exactly 7 args or 7 args and varargs.
443 // check common block argument.
444 Expr *Arg6 = TheCall->getArg(6);
445 if (!isBlockPointer(Arg6)) {
446 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
450 if (checkOpenCLBlockArgs(S, Arg6))
453 // Forth argument has to be any integer type.
454 if (!Arg3->getType()->isIntegerType()) {
455 S.Diag(TheCall->getArg(3)->getLocStart(),
456 diag::err_opencl_enqueue_kernel_expected_type)
460 // check remaining common arguments.
461 Expr *Arg4 = TheCall->getArg(4);
462 Expr *Arg5 = TheCall->getArg(5);
464 // Fifth argument is always passed as a pointer to clk_event_t.
465 if (!Arg4->isNullPointerConstant(S.Context,
466 Expr::NPC_ValueDependentIsNotNull) &&
467 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
468 S.Diag(TheCall->getArg(4)->getLocStart(),
469 diag::err_opencl_enqueue_kernel_expected_type)
470 << S.Context.getPointerType(S.Context.OCLClkEventTy);
474 // Sixth argument is always passed as a pointer to clk_event_t.
475 if (!Arg5->isNullPointerConstant(S.Context,
476 Expr::NPC_ValueDependentIsNotNull) &&
477 !(Arg5->getType()->isPointerType() &&
478 Arg5->getType()->getPointeeType()->isClkEventT())) {
479 S.Diag(TheCall->getArg(5)->getLocStart(),
480 diag::err_opencl_enqueue_kernel_expected_type)
481 << S.Context.getPointerType(S.Context.OCLClkEventTy);
488 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
491 // None of the specific case has been detected, give generic error
492 S.Diag(TheCall->getLocStart(),
493 diag::err_opencl_enqueue_kernel_incorrect_args);
497 /// Returns OpenCL access qual.
498 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
499 return D->getAttr<OpenCLAccessAttr>();
502 /// Returns true if pipe element type is different from the pointer.
503 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
504 const Expr *Arg0 = Call->getArg(0);
505 // First argument type should always be pipe.
506 if (!Arg0->getType()->isPipeType()) {
507 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
508 << Call->getDirectCallee() << Arg0->getSourceRange();
511 OpenCLAccessAttr *AccessQual =
512 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
513 // Validates the access qualifier is compatible with the call.
514 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
515 // read_only and write_only, and assumed to be read_only if no qualifier is
517 switch (Call->getDirectCallee()->getBuiltinID()) {
518 case Builtin::BIread_pipe:
519 case Builtin::BIreserve_read_pipe:
520 case Builtin::BIcommit_read_pipe:
521 case Builtin::BIwork_group_reserve_read_pipe:
522 case Builtin::BIsub_group_reserve_read_pipe:
523 case Builtin::BIwork_group_commit_read_pipe:
524 case Builtin::BIsub_group_commit_read_pipe:
525 if (!(!AccessQual || AccessQual->isReadOnly())) {
526 S.Diag(Arg0->getLocStart(),
527 diag::err_opencl_builtin_pipe_invalid_access_modifier)
528 << "read_only" << Arg0->getSourceRange();
532 case Builtin::BIwrite_pipe:
533 case Builtin::BIreserve_write_pipe:
534 case Builtin::BIcommit_write_pipe:
535 case Builtin::BIwork_group_reserve_write_pipe:
536 case Builtin::BIsub_group_reserve_write_pipe:
537 case Builtin::BIwork_group_commit_write_pipe:
538 case Builtin::BIsub_group_commit_write_pipe:
539 if (!(AccessQual && AccessQual->isWriteOnly())) {
540 S.Diag(Arg0->getLocStart(),
541 diag::err_opencl_builtin_pipe_invalid_access_modifier)
542 << "write_only" << Arg0->getSourceRange();
552 /// Returns true if pipe element type is different from the pointer.
553 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
554 const Expr *Arg0 = Call->getArg(0);
555 const Expr *ArgIdx = Call->getArg(Idx);
556 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
557 const QualType EltTy = PipeTy->getElementType();
558 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
559 // The Idx argument should be a pointer and the type of the pointer and
560 // the type of pipe element should also be the same.
562 !S.Context.hasSameType(
563 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
564 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
565 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
566 << ArgIdx->getType() << ArgIdx->getSourceRange();
572 // \brief Performs semantic analysis for the read/write_pipe call.
573 // \param S Reference to the semantic analyzer.
574 // \param Call A pointer to the builtin call.
575 // \return True if a semantic error has been found, false otherwise.
576 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
577 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
578 // functions have two forms.
579 switch (Call->getNumArgs()) {
581 if (checkOpenCLPipeArg(S, Call))
583 // The call with 2 arguments should be
584 // read/write_pipe(pipe T, T*).
585 // Check packet type T.
586 if (checkOpenCLPipePacketType(S, Call, 1))
591 if (checkOpenCLPipeArg(S, Call))
593 // The call with 4 arguments should be
594 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
595 // Check reserve_id_t.
596 if (!Call->getArg(1)->getType()->isReserveIDT()) {
597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
598 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
599 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
604 const Expr *Arg2 = Call->getArg(2);
605 if (!Arg2->getType()->isIntegerType() &&
606 !Arg2->getType()->isUnsignedIntegerType()) {
607 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
608 << Call->getDirectCallee() << S.Context.UnsignedIntTy
609 << Arg2->getType() << Arg2->getSourceRange();
613 // Check packet type T.
614 if (checkOpenCLPipePacketType(S, Call, 3))
618 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
619 << Call->getDirectCallee() << Call->getSourceRange();
626 // \brief Performs a semantic analysis on the {work_group_/sub_group_
627 // /_}reserve_{read/write}_pipe
628 // \param S Reference to the semantic analyzer.
629 // \param Call The call to the builtin function to be analyzed.
630 // \return True if a semantic error was found, false otherwise.
631 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
632 if (checkArgCount(S, Call, 2))
635 if (checkOpenCLPipeArg(S, Call))
638 // Check the reserve size.
639 if (!Call->getArg(1)->getType()->isIntegerType() &&
640 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
641 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
642 << Call->getDirectCallee() << S.Context.UnsignedIntTy
643 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
650 // \brief Performs a semantic analysis on {work_group_/sub_group_
651 // /_}commit_{read/write}_pipe
652 // \param S Reference to the semantic analyzer.
653 // \param Call The call to the builtin function to be analyzed.
654 // \return True if a semantic error was found, false otherwise.
655 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
656 if (checkArgCount(S, Call, 2))
659 if (checkOpenCLPipeArg(S, Call))
662 // Check reserve_id_t.
663 if (!Call->getArg(1)->getType()->isReserveIDT()) {
664 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
665 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
666 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
673 // \brief Performs a semantic analysis on the call to built-in Pipe
675 // \param S Reference to the semantic analyzer.
676 // \param Call The call to the builtin function to be analyzed.
677 // \return True if a semantic error was found, false otherwise.
678 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
679 if (checkArgCount(S, Call, 1))
682 if (!Call->getArg(0)->getType()->isPipeType()) {
683 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
684 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
690 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
691 // \brief Performs semantic analysis for the to_global/local/private call.
692 // \param S Reference to the semantic analyzer.
693 // \param BuiltinID ID of the builtin function.
694 // \param Call A pointer to the builtin call.
695 // \return True if a semantic error has been found, false otherwise.
696 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
698 if (Call->getNumArgs() != 1) {
699 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
700 << Call->getDirectCallee() << Call->getSourceRange();
704 auto RT = Call->getArg(0)->getType();
705 if (!RT->isPointerType() || RT->getPointeeType()
706 .getAddressSpace() == LangAS::opencl_constant) {
707 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
708 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
712 RT = RT->getPointeeType();
713 auto Qual = RT.getQualifiers();
715 case Builtin::BIto_global:
716 Qual.setAddressSpace(LangAS::opencl_global);
718 case Builtin::BIto_local:
719 Qual.setAddressSpace(LangAS::opencl_local);
722 Qual.removeAddressSpace();
724 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
725 RT.getUnqualifiedType(), Qual)));
731 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
733 ExprResult TheCallResult(TheCall);
735 // Find out if any arguments are required to be integer constant expressions.
736 unsigned ICEArguments = 0;
737 ASTContext::GetBuiltinTypeError Error;
738 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
739 if (Error != ASTContext::GE_None)
740 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
742 // If any arguments are required to be ICE's, check and diagnose.
743 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
744 // Skip arguments not required to be ICE's.
745 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
748 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
750 ICEArguments &= ~(1 << ArgNo);
754 case Builtin::BI__builtin___CFStringMakeConstantString:
755 assert(TheCall->getNumArgs() == 1 &&
756 "Wrong # arguments to builtin CFStringMakeConstantString");
757 if (CheckObjCString(TheCall->getArg(0)))
760 case Builtin::BI__builtin_stdarg_start:
761 case Builtin::BI__builtin_va_start:
762 if (SemaBuiltinVAStart(TheCall))
765 case Builtin::BI__va_start: {
766 switch (Context.getTargetInfo().getTriple().getArch()) {
767 case llvm::Triple::arm:
768 case llvm::Triple::thumb:
769 if (SemaBuiltinVAStartARM(TheCall))
773 if (SemaBuiltinVAStart(TheCall))
779 case Builtin::BI__builtin_isgreater:
780 case Builtin::BI__builtin_isgreaterequal:
781 case Builtin::BI__builtin_isless:
782 case Builtin::BI__builtin_islessequal:
783 case Builtin::BI__builtin_islessgreater:
784 case Builtin::BI__builtin_isunordered:
785 if (SemaBuiltinUnorderedCompare(TheCall))
788 case Builtin::BI__builtin_fpclassify:
789 if (SemaBuiltinFPClassification(TheCall, 6))
792 case Builtin::BI__builtin_isfinite:
793 case Builtin::BI__builtin_isinf:
794 case Builtin::BI__builtin_isinf_sign:
795 case Builtin::BI__builtin_isnan:
796 case Builtin::BI__builtin_isnormal:
797 if (SemaBuiltinFPClassification(TheCall, 1))
800 case Builtin::BI__builtin_shufflevector:
801 return SemaBuiltinShuffleVector(TheCall);
802 // TheCall will be freed by the smart pointer here, but that's fine, since
803 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
804 case Builtin::BI__builtin_prefetch:
805 if (SemaBuiltinPrefetch(TheCall))
808 case Builtin::BI__builtin_alloca_with_align:
809 if (SemaBuiltinAllocaWithAlign(TheCall))
812 case Builtin::BI__assume:
813 case Builtin::BI__builtin_assume:
814 if (SemaBuiltinAssume(TheCall))
817 case Builtin::BI__builtin_assume_aligned:
818 if (SemaBuiltinAssumeAligned(TheCall))
821 case Builtin::BI__builtin_object_size:
822 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
825 case Builtin::BI__builtin_longjmp:
826 if (SemaBuiltinLongjmp(TheCall))
829 case Builtin::BI__builtin_setjmp:
830 if (SemaBuiltinSetjmp(TheCall))
833 case Builtin::BI_setjmp:
834 case Builtin::BI_setjmpex:
835 if (checkArgCount(*this, TheCall, 1))
839 case Builtin::BI__builtin_classify_type:
840 if (checkArgCount(*this, TheCall, 1)) return true;
841 TheCall->setType(Context.IntTy);
843 case Builtin::BI__builtin_constant_p:
844 if (checkArgCount(*this, TheCall, 1)) return true;
845 TheCall->setType(Context.IntTy);
847 case Builtin::BI__sync_fetch_and_add:
848 case Builtin::BI__sync_fetch_and_add_1:
849 case Builtin::BI__sync_fetch_and_add_2:
850 case Builtin::BI__sync_fetch_and_add_4:
851 case Builtin::BI__sync_fetch_and_add_8:
852 case Builtin::BI__sync_fetch_and_add_16:
853 case Builtin::BI__sync_fetch_and_sub:
854 case Builtin::BI__sync_fetch_and_sub_1:
855 case Builtin::BI__sync_fetch_and_sub_2:
856 case Builtin::BI__sync_fetch_and_sub_4:
857 case Builtin::BI__sync_fetch_and_sub_8:
858 case Builtin::BI__sync_fetch_and_sub_16:
859 case Builtin::BI__sync_fetch_and_or:
860 case Builtin::BI__sync_fetch_and_or_1:
861 case Builtin::BI__sync_fetch_and_or_2:
862 case Builtin::BI__sync_fetch_and_or_4:
863 case Builtin::BI__sync_fetch_and_or_8:
864 case Builtin::BI__sync_fetch_and_or_16:
865 case Builtin::BI__sync_fetch_and_and:
866 case Builtin::BI__sync_fetch_and_and_1:
867 case Builtin::BI__sync_fetch_and_and_2:
868 case Builtin::BI__sync_fetch_and_and_4:
869 case Builtin::BI__sync_fetch_and_and_8:
870 case Builtin::BI__sync_fetch_and_and_16:
871 case Builtin::BI__sync_fetch_and_xor:
872 case Builtin::BI__sync_fetch_and_xor_1:
873 case Builtin::BI__sync_fetch_and_xor_2:
874 case Builtin::BI__sync_fetch_and_xor_4:
875 case Builtin::BI__sync_fetch_and_xor_8:
876 case Builtin::BI__sync_fetch_and_xor_16:
877 case Builtin::BI__sync_fetch_and_nand:
878 case Builtin::BI__sync_fetch_and_nand_1:
879 case Builtin::BI__sync_fetch_and_nand_2:
880 case Builtin::BI__sync_fetch_and_nand_4:
881 case Builtin::BI__sync_fetch_and_nand_8:
882 case Builtin::BI__sync_fetch_and_nand_16:
883 case Builtin::BI__sync_add_and_fetch:
884 case Builtin::BI__sync_add_and_fetch_1:
885 case Builtin::BI__sync_add_and_fetch_2:
886 case Builtin::BI__sync_add_and_fetch_4:
887 case Builtin::BI__sync_add_and_fetch_8:
888 case Builtin::BI__sync_add_and_fetch_16:
889 case Builtin::BI__sync_sub_and_fetch:
890 case Builtin::BI__sync_sub_and_fetch_1:
891 case Builtin::BI__sync_sub_and_fetch_2:
892 case Builtin::BI__sync_sub_and_fetch_4:
893 case Builtin::BI__sync_sub_and_fetch_8:
894 case Builtin::BI__sync_sub_and_fetch_16:
895 case Builtin::BI__sync_and_and_fetch:
896 case Builtin::BI__sync_and_and_fetch_1:
897 case Builtin::BI__sync_and_and_fetch_2:
898 case Builtin::BI__sync_and_and_fetch_4:
899 case Builtin::BI__sync_and_and_fetch_8:
900 case Builtin::BI__sync_and_and_fetch_16:
901 case Builtin::BI__sync_or_and_fetch:
902 case Builtin::BI__sync_or_and_fetch_1:
903 case Builtin::BI__sync_or_and_fetch_2:
904 case Builtin::BI__sync_or_and_fetch_4:
905 case Builtin::BI__sync_or_and_fetch_8:
906 case Builtin::BI__sync_or_and_fetch_16:
907 case Builtin::BI__sync_xor_and_fetch:
908 case Builtin::BI__sync_xor_and_fetch_1:
909 case Builtin::BI__sync_xor_and_fetch_2:
910 case Builtin::BI__sync_xor_and_fetch_4:
911 case Builtin::BI__sync_xor_and_fetch_8:
912 case Builtin::BI__sync_xor_and_fetch_16:
913 case Builtin::BI__sync_nand_and_fetch:
914 case Builtin::BI__sync_nand_and_fetch_1:
915 case Builtin::BI__sync_nand_and_fetch_2:
916 case Builtin::BI__sync_nand_and_fetch_4:
917 case Builtin::BI__sync_nand_and_fetch_8:
918 case Builtin::BI__sync_nand_and_fetch_16:
919 case Builtin::BI__sync_val_compare_and_swap:
920 case Builtin::BI__sync_val_compare_and_swap_1:
921 case Builtin::BI__sync_val_compare_and_swap_2:
922 case Builtin::BI__sync_val_compare_and_swap_4:
923 case Builtin::BI__sync_val_compare_and_swap_8:
924 case Builtin::BI__sync_val_compare_and_swap_16:
925 case Builtin::BI__sync_bool_compare_and_swap:
926 case Builtin::BI__sync_bool_compare_and_swap_1:
927 case Builtin::BI__sync_bool_compare_and_swap_2:
928 case Builtin::BI__sync_bool_compare_and_swap_4:
929 case Builtin::BI__sync_bool_compare_and_swap_8:
930 case Builtin::BI__sync_bool_compare_and_swap_16:
931 case Builtin::BI__sync_lock_test_and_set:
932 case Builtin::BI__sync_lock_test_and_set_1:
933 case Builtin::BI__sync_lock_test_and_set_2:
934 case Builtin::BI__sync_lock_test_and_set_4:
935 case Builtin::BI__sync_lock_test_and_set_8:
936 case Builtin::BI__sync_lock_test_and_set_16:
937 case Builtin::BI__sync_lock_release:
938 case Builtin::BI__sync_lock_release_1:
939 case Builtin::BI__sync_lock_release_2:
940 case Builtin::BI__sync_lock_release_4:
941 case Builtin::BI__sync_lock_release_8:
942 case Builtin::BI__sync_lock_release_16:
943 case Builtin::BI__sync_swap:
944 case Builtin::BI__sync_swap_1:
945 case Builtin::BI__sync_swap_2:
946 case Builtin::BI__sync_swap_4:
947 case Builtin::BI__sync_swap_8:
948 case Builtin::BI__sync_swap_16:
949 return SemaBuiltinAtomicOverloaded(TheCallResult);
950 case Builtin::BI__builtin_nontemporal_load:
951 case Builtin::BI__builtin_nontemporal_store:
952 return SemaBuiltinNontemporalOverloaded(TheCallResult);
953 #define BUILTIN(ID, TYPE, ATTRS)
954 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
955 case Builtin::BI##ID: \
956 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
957 #include "clang/Basic/Builtins.def"
958 case Builtin::BI__builtin_annotation:
959 if (SemaBuiltinAnnotation(*this, TheCall))
962 case Builtin::BI__builtin_addressof:
963 if (SemaBuiltinAddressof(*this, TheCall))
966 case Builtin::BI__builtin_add_overflow:
967 case Builtin::BI__builtin_sub_overflow:
968 case Builtin::BI__builtin_mul_overflow:
969 if (SemaBuiltinOverflow(*this, TheCall))
972 case Builtin::BI__builtin_operator_new:
973 case Builtin::BI__builtin_operator_delete:
974 if (!getLangOpts().CPlusPlus) {
975 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
976 << (BuiltinID == Builtin::BI__builtin_operator_new
977 ? "__builtin_operator_new"
978 : "__builtin_operator_delete")
982 // CodeGen assumes it can find the global new and delete to call,
983 // so ensure that they are declared.
984 DeclareGlobalNewDelete();
987 // check secure string manipulation functions where overflows
988 // are detectable at compile time
989 case Builtin::BI__builtin___memcpy_chk:
990 case Builtin::BI__builtin___memmove_chk:
991 case Builtin::BI__builtin___memset_chk:
992 case Builtin::BI__builtin___strlcat_chk:
993 case Builtin::BI__builtin___strlcpy_chk:
994 case Builtin::BI__builtin___strncat_chk:
995 case Builtin::BI__builtin___strncpy_chk:
996 case Builtin::BI__builtin___stpncpy_chk:
997 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
999 case Builtin::BI__builtin___memccpy_chk:
1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1002 case Builtin::BI__builtin___snprintf_chk:
1003 case Builtin::BI__builtin___vsnprintf_chk:
1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1006 case Builtin::BI__builtin_call_with_static_chain:
1007 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1010 case Builtin::BI__exception_code:
1011 case Builtin::BI_exception_code:
1012 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1013 diag::err_seh___except_block))
1016 case Builtin::BI__exception_info:
1017 case Builtin::BI_exception_info:
1018 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1019 diag::err_seh___except_filter))
1022 case Builtin::BI__GetExceptionInfo:
1023 if (checkArgCount(*this, TheCall, 1))
1026 if (CheckCXXThrowOperand(
1027 TheCall->getLocStart(),
1028 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1032 TheCall->setType(Context.VoidPtrTy);
1034 // OpenCL v2.0, s6.13.16 - Pipe functions
1035 case Builtin::BIread_pipe:
1036 case Builtin::BIwrite_pipe:
1037 // Since those two functions are declared with var args, we need a semantic
1038 // check for the argument.
1039 if (SemaBuiltinRWPipe(*this, TheCall))
1041 TheCall->setType(Context.IntTy);
1043 case Builtin::BIreserve_read_pipe:
1044 case Builtin::BIreserve_write_pipe:
1045 case Builtin::BIwork_group_reserve_read_pipe:
1046 case Builtin::BIwork_group_reserve_write_pipe:
1047 case Builtin::BIsub_group_reserve_read_pipe:
1048 case Builtin::BIsub_group_reserve_write_pipe:
1049 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1051 // Since return type of reserve_read/write_pipe built-in function is
1052 // reserve_id_t, which is not defined in the builtin def file , we used int
1053 // as return type and need to override the return type of these functions.
1054 TheCall->setType(Context.OCLReserveIDTy);
1056 case Builtin::BIcommit_read_pipe:
1057 case Builtin::BIcommit_write_pipe:
1058 case Builtin::BIwork_group_commit_read_pipe:
1059 case Builtin::BIwork_group_commit_write_pipe:
1060 case Builtin::BIsub_group_commit_read_pipe:
1061 case Builtin::BIsub_group_commit_write_pipe:
1062 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1065 case Builtin::BIget_pipe_num_packets:
1066 case Builtin::BIget_pipe_max_packets:
1067 if (SemaBuiltinPipePackets(*this, TheCall))
1069 TheCall->setType(Context.UnsignedIntTy);
1071 case Builtin::BIto_global:
1072 case Builtin::BIto_local:
1073 case Builtin::BIto_private:
1074 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1077 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1078 case Builtin::BIenqueue_kernel:
1079 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1082 case Builtin::BIget_kernel_work_group_size:
1083 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1084 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1087 case Builtin::BI__builtin_os_log_format:
1088 case Builtin::BI__builtin_os_log_format_buffer_size:
1089 if (SemaBuiltinOSLogFormat(TheCall)) {
1095 // Since the target specific builtins for each arch overlap, only check those
1096 // of the arch we are compiling for.
1097 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1098 switch (Context.getTargetInfo().getTriple().getArch()) {
1099 case llvm::Triple::arm:
1100 case llvm::Triple::armeb:
1101 case llvm::Triple::thumb:
1102 case llvm::Triple::thumbeb:
1103 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1106 case llvm::Triple::aarch64:
1107 case llvm::Triple::aarch64_be:
1108 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1111 case llvm::Triple::mips:
1112 case llvm::Triple::mipsel:
1113 case llvm::Triple::mips64:
1114 case llvm::Triple::mips64el:
1115 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1118 case llvm::Triple::systemz:
1119 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1122 case llvm::Triple::x86:
1123 case llvm::Triple::x86_64:
1124 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1127 case llvm::Triple::ppc:
1128 case llvm::Triple::ppc64:
1129 case llvm::Triple::ppc64le:
1130 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1138 return TheCallResult;
1141 // Get the valid immediate range for the specified NEON type code.
1142 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1143 NeonTypeFlags Type(t);
1144 int IsQuad = ForceQuad ? true : Type.isQuad();
1145 switch (Type.getEltType()) {
1146 case NeonTypeFlags::Int8:
1147 case NeonTypeFlags::Poly8:
1148 return shift ? 7 : (8 << IsQuad) - 1;
1149 case NeonTypeFlags::Int16:
1150 case NeonTypeFlags::Poly16:
1151 return shift ? 15 : (4 << IsQuad) - 1;
1152 case NeonTypeFlags::Int32:
1153 return shift ? 31 : (2 << IsQuad) - 1;
1154 case NeonTypeFlags::Int64:
1155 case NeonTypeFlags::Poly64:
1156 return shift ? 63 : (1 << IsQuad) - 1;
1157 case NeonTypeFlags::Poly128:
1158 return shift ? 127 : (1 << IsQuad) - 1;
1159 case NeonTypeFlags::Float16:
1160 assert(!shift && "cannot shift float types!");
1161 return (4 << IsQuad) - 1;
1162 case NeonTypeFlags::Float32:
1163 assert(!shift && "cannot shift float types!");
1164 return (2 << IsQuad) - 1;
1165 case NeonTypeFlags::Float64:
1166 assert(!shift && "cannot shift float types!");
1167 return (1 << IsQuad) - 1;
1169 llvm_unreachable("Invalid NeonTypeFlag!");
1172 /// getNeonEltType - Return the QualType corresponding to the elements of
1173 /// the vector type specified by the NeonTypeFlags. This is used to check
1174 /// the pointer arguments for Neon load/store intrinsics.
1175 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1176 bool IsPolyUnsigned, bool IsInt64Long) {
1177 switch (Flags.getEltType()) {
1178 case NeonTypeFlags::Int8:
1179 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1180 case NeonTypeFlags::Int16:
1181 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1182 case NeonTypeFlags::Int32:
1183 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1184 case NeonTypeFlags::Int64:
1186 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1188 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1189 : Context.LongLongTy;
1190 case NeonTypeFlags::Poly8:
1191 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1192 case NeonTypeFlags::Poly16:
1193 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1194 case NeonTypeFlags::Poly64:
1196 return Context.UnsignedLongTy;
1198 return Context.UnsignedLongLongTy;
1199 case NeonTypeFlags::Poly128:
1201 case NeonTypeFlags::Float16:
1202 return Context.HalfTy;
1203 case NeonTypeFlags::Float32:
1204 return Context.FloatTy;
1205 case NeonTypeFlags::Float64:
1206 return Context.DoubleTy;
1208 llvm_unreachable("Invalid NeonTypeFlag!");
1211 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1212 llvm::APSInt Result;
1216 bool HasConstPtr = false;
1217 switch (BuiltinID) {
1218 #define GET_NEON_OVERLOAD_CHECK
1219 #include "clang/Basic/arm_neon.inc"
1220 #undef GET_NEON_OVERLOAD_CHECK
1223 // For NEON intrinsics which are overloaded on vector element type, validate
1224 // the immediate which specifies which variant to emit.
1225 unsigned ImmArg = TheCall->getNumArgs()-1;
1227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1230 TV = Result.getLimitedValue(64);
1231 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1232 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1233 << TheCall->getArg(ImmArg)->getSourceRange();
1236 if (PtrArgNum >= 0) {
1237 // Check that pointer arguments have the specified type.
1238 Expr *Arg = TheCall->getArg(PtrArgNum);
1239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1240 Arg = ICE->getSubExpr();
1241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1242 QualType RHSTy = RHS.get()->getType();
1244 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1246 Arch == llvm::Triple::aarch64_be;
1248 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1250 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1252 EltTy = EltTy.withConst();
1253 QualType LHSTy = Context.getPointerType(EltTy);
1254 AssignConvertType ConvTy;
1255 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1256 if (RHS.isInvalid())
1258 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1259 RHS.get(), AA_Assigning))
1263 // For NEON intrinsics which take an immediate value as part of the
1264 // instruction, range check them here.
1265 unsigned i = 0, l = 0, u = 0;
1266 switch (BuiltinID) {
1269 #define GET_NEON_IMMEDIATE_CHECK
1270 #include "clang/Basic/arm_neon.inc"
1271 #undef GET_NEON_IMMEDIATE_CHECK
1274 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1277 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1278 unsigned MaxWidth) {
1279 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1280 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1281 BuiltinID == ARM::BI__builtin_arm_strex ||
1282 BuiltinID == ARM::BI__builtin_arm_stlex ||
1283 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1284 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1285 BuiltinID == AArch64::BI__builtin_arm_strex ||
1286 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1287 "unexpected ARM builtin");
1288 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1289 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1290 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1291 BuiltinID == AArch64::BI__builtin_arm_ldaex;
1293 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1295 // Ensure that we have the proper number of arguments.
1296 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1299 // Inspect the pointer argument of the atomic builtin. This should always be
1300 // a pointer type, whose element is an integral scalar or pointer type.
1301 // Because it is a pointer type, we don't have to worry about any implicit
1303 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1304 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1305 if (PointerArgRes.isInvalid())
1307 PointerArg = PointerArgRes.get();
1309 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1311 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1312 << PointerArg->getType() << PointerArg->getSourceRange();
1316 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1317 // task is to insert the appropriate casts into the AST. First work out just
1318 // what the appropriate type is.
1319 QualType ValType = pointerType->getPointeeType();
1320 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1322 AddrType.addConst();
1324 // Issue a warning if the cast is dodgy.
1325 CastKind CastNeeded = CK_NoOp;
1326 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1327 CastNeeded = CK_BitCast;
1328 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1329 << PointerArg->getType()
1330 << Context.getPointerType(AddrType)
1331 << AA_Passing << PointerArg->getSourceRange();
1334 // Finally, do the cast and replace the argument with the corrected version.
1335 AddrType = Context.getPointerType(AddrType);
1336 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1337 if (PointerArgRes.isInvalid())
1339 PointerArg = PointerArgRes.get();
1341 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1343 // In general, we allow ints, floats and pointers to be loaded and stored.
1344 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1345 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1346 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1347 << PointerArg->getType() << PointerArg->getSourceRange();
1351 // But ARM doesn't have instructions to deal with 128-bit versions.
1352 if (Context.getTypeSize(ValType) > MaxWidth) {
1353 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1354 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1355 << PointerArg->getType() << PointerArg->getSourceRange();
1359 switch (ValType.getObjCLifetime()) {
1360 case Qualifiers::OCL_None:
1361 case Qualifiers::OCL_ExplicitNone:
1365 case Qualifiers::OCL_Weak:
1366 case Qualifiers::OCL_Strong:
1367 case Qualifiers::OCL_Autoreleasing:
1368 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1369 << ValType << PointerArg->getSourceRange();
1374 TheCall->setType(ValType);
1378 // Initialize the argument to be stored.
1379 ExprResult ValArg = TheCall->getArg(0);
1380 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1381 Context, ValType, /*consume*/ false);
1382 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1383 if (ValArg.isInvalid())
1385 TheCall->setArg(0, ValArg.get());
1387 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1388 // but the custom checker bypasses all default analysis.
1389 TheCall->setType(Context.IntTy);
1393 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1394 llvm::APSInt Result;
1396 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1397 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1398 BuiltinID == ARM::BI__builtin_arm_strex ||
1399 BuiltinID == ARM::BI__builtin_arm_stlex) {
1400 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1403 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1404 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1405 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1408 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1409 BuiltinID == ARM::BI__builtin_arm_wsr64)
1410 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1412 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1413 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1414 BuiltinID == ARM::BI__builtin_arm_wsr ||
1415 BuiltinID == ARM::BI__builtin_arm_wsrp)
1416 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1418 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1421 // For intrinsics which take an immediate value as part of the instruction,
1422 // range check them here.
1423 unsigned i = 0, l = 0, u = 0;
1424 switch (BuiltinID) {
1425 default: return false;
1426 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1427 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1428 case ARM::BI__builtin_arm_vcvtr_f:
1429 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1430 case ARM::BI__builtin_arm_dmb:
1431 case ARM::BI__builtin_arm_dsb:
1432 case ARM::BI__builtin_arm_isb:
1433 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1436 // FIXME: VFP Intrinsics should error if VFP not present.
1437 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1440 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1441 CallExpr *TheCall) {
1442 llvm::APSInt Result;
1444 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1445 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1446 BuiltinID == AArch64::BI__builtin_arm_strex ||
1447 BuiltinID == AArch64::BI__builtin_arm_stlex) {
1448 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1451 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1452 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1453 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1454 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1455 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1458 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1459 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1460 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1462 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1463 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1465 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1466 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1468 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1471 // For intrinsics which take an immediate value as part of the instruction,
1472 // range check them here.
1473 unsigned i = 0, l = 0, u = 0;
1474 switch (BuiltinID) {
1475 default: return false;
1476 case AArch64::BI__builtin_arm_dmb:
1477 case AArch64::BI__builtin_arm_dsb:
1478 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1481 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1484 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1485 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1486 // ordering for DSP is unspecified. MSA is ordered by the data format used
1487 // by the underlying instruction i.e., df/m, df/n and then by size.
1489 // FIXME: The size tests here should instead be tablegen'd along with the
1490 // definitions from include/clang/Basic/BuiltinsMips.def.
1491 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1493 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1494 unsigned i = 0, l = 0, u = 0, m = 0;
1495 switch (BuiltinID) {
1496 default: return false;
1497 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1498 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1499 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1500 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1501 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1502 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1503 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1504 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1506 // These intrinsics take an unsigned 3 bit immediate.
1507 case Mips::BI__builtin_msa_bclri_b:
1508 case Mips::BI__builtin_msa_bnegi_b:
1509 case Mips::BI__builtin_msa_bseti_b:
1510 case Mips::BI__builtin_msa_sat_s_b:
1511 case Mips::BI__builtin_msa_sat_u_b:
1512 case Mips::BI__builtin_msa_slli_b:
1513 case Mips::BI__builtin_msa_srai_b:
1514 case Mips::BI__builtin_msa_srari_b:
1515 case Mips::BI__builtin_msa_srli_b:
1516 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1517 case Mips::BI__builtin_msa_binsli_b:
1518 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1519 // These intrinsics take an unsigned 4 bit immediate.
1520 case Mips::BI__builtin_msa_bclri_h:
1521 case Mips::BI__builtin_msa_bnegi_h:
1522 case Mips::BI__builtin_msa_bseti_h:
1523 case Mips::BI__builtin_msa_sat_s_h:
1524 case Mips::BI__builtin_msa_sat_u_h:
1525 case Mips::BI__builtin_msa_slli_h:
1526 case Mips::BI__builtin_msa_srai_h:
1527 case Mips::BI__builtin_msa_srari_h:
1528 case Mips::BI__builtin_msa_srli_h:
1529 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1530 case Mips::BI__builtin_msa_binsli_h:
1531 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1532 // These intrinsics take an unsigned 5 bit immedate.
1533 // The first block of intrinsics actually have an unsigned 5 bit field,
1534 // not a df/n field.
1535 case Mips::BI__builtin_msa_clei_u_b:
1536 case Mips::BI__builtin_msa_clei_u_h:
1537 case Mips::BI__builtin_msa_clei_u_w:
1538 case Mips::BI__builtin_msa_clei_u_d:
1539 case Mips::BI__builtin_msa_clti_u_b:
1540 case Mips::BI__builtin_msa_clti_u_h:
1541 case Mips::BI__builtin_msa_clti_u_w:
1542 case Mips::BI__builtin_msa_clti_u_d:
1543 case Mips::BI__builtin_msa_maxi_u_b:
1544 case Mips::BI__builtin_msa_maxi_u_h:
1545 case Mips::BI__builtin_msa_maxi_u_w:
1546 case Mips::BI__builtin_msa_maxi_u_d:
1547 case Mips::BI__builtin_msa_mini_u_b:
1548 case Mips::BI__builtin_msa_mini_u_h:
1549 case Mips::BI__builtin_msa_mini_u_w:
1550 case Mips::BI__builtin_msa_mini_u_d:
1551 case Mips::BI__builtin_msa_addvi_b:
1552 case Mips::BI__builtin_msa_addvi_h:
1553 case Mips::BI__builtin_msa_addvi_w:
1554 case Mips::BI__builtin_msa_addvi_d:
1555 case Mips::BI__builtin_msa_bclri_w:
1556 case Mips::BI__builtin_msa_bnegi_w:
1557 case Mips::BI__builtin_msa_bseti_w:
1558 case Mips::BI__builtin_msa_sat_s_w:
1559 case Mips::BI__builtin_msa_sat_u_w:
1560 case Mips::BI__builtin_msa_slli_w:
1561 case Mips::BI__builtin_msa_srai_w:
1562 case Mips::BI__builtin_msa_srari_w:
1563 case Mips::BI__builtin_msa_srli_w:
1564 case Mips::BI__builtin_msa_srlri_w:
1565 case Mips::BI__builtin_msa_subvi_b:
1566 case Mips::BI__builtin_msa_subvi_h:
1567 case Mips::BI__builtin_msa_subvi_w:
1568 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1569 case Mips::BI__builtin_msa_binsli_w:
1570 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1571 // These intrinsics take an unsigned 6 bit immediate.
1572 case Mips::BI__builtin_msa_bclri_d:
1573 case Mips::BI__builtin_msa_bnegi_d:
1574 case Mips::BI__builtin_msa_bseti_d:
1575 case Mips::BI__builtin_msa_sat_s_d:
1576 case Mips::BI__builtin_msa_sat_u_d:
1577 case Mips::BI__builtin_msa_slli_d:
1578 case Mips::BI__builtin_msa_srai_d:
1579 case Mips::BI__builtin_msa_srari_d:
1580 case Mips::BI__builtin_msa_srli_d:
1581 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1582 case Mips::BI__builtin_msa_binsli_d:
1583 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1584 // These intrinsics take a signed 5 bit immediate.
1585 case Mips::BI__builtin_msa_ceqi_b:
1586 case Mips::BI__builtin_msa_ceqi_h:
1587 case Mips::BI__builtin_msa_ceqi_w:
1588 case Mips::BI__builtin_msa_ceqi_d:
1589 case Mips::BI__builtin_msa_clti_s_b:
1590 case Mips::BI__builtin_msa_clti_s_h:
1591 case Mips::BI__builtin_msa_clti_s_w:
1592 case Mips::BI__builtin_msa_clti_s_d:
1593 case Mips::BI__builtin_msa_clei_s_b:
1594 case Mips::BI__builtin_msa_clei_s_h:
1595 case Mips::BI__builtin_msa_clei_s_w:
1596 case Mips::BI__builtin_msa_clei_s_d:
1597 case Mips::BI__builtin_msa_maxi_s_b:
1598 case Mips::BI__builtin_msa_maxi_s_h:
1599 case Mips::BI__builtin_msa_maxi_s_w:
1600 case Mips::BI__builtin_msa_maxi_s_d:
1601 case Mips::BI__builtin_msa_mini_s_b:
1602 case Mips::BI__builtin_msa_mini_s_h:
1603 case Mips::BI__builtin_msa_mini_s_w:
1604 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1605 // These intrinsics take an unsigned 8 bit immediate.
1606 case Mips::BI__builtin_msa_andi_b:
1607 case Mips::BI__builtin_msa_nori_b:
1608 case Mips::BI__builtin_msa_ori_b:
1609 case Mips::BI__builtin_msa_shf_b:
1610 case Mips::BI__builtin_msa_shf_h:
1611 case Mips::BI__builtin_msa_shf_w:
1612 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1613 case Mips::BI__builtin_msa_bseli_b:
1614 case Mips::BI__builtin_msa_bmnzi_b:
1615 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1617 // These intrinsics take an unsigned 4 bit immediate.
1618 case Mips::BI__builtin_msa_copy_s_b:
1619 case Mips::BI__builtin_msa_copy_u_b:
1620 case Mips::BI__builtin_msa_insve_b:
1621 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1622 case Mips::BI__builtin_msa_sld_b:
1623 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1624 // These intrinsics take an unsigned 3 bit immediate.
1625 case Mips::BI__builtin_msa_copy_s_h:
1626 case Mips::BI__builtin_msa_copy_u_h:
1627 case Mips::BI__builtin_msa_insve_h:
1628 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1629 case Mips::BI__builtin_msa_sld_h:
1630 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1631 // These intrinsics take an unsigned 2 bit immediate.
1632 case Mips::BI__builtin_msa_copy_s_w:
1633 case Mips::BI__builtin_msa_copy_u_w:
1634 case Mips::BI__builtin_msa_insve_w:
1635 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1636 case Mips::BI__builtin_msa_sld_w:
1637 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1638 // These intrinsics take an unsigned 1 bit immediate.
1639 case Mips::BI__builtin_msa_copy_s_d:
1640 case Mips::BI__builtin_msa_copy_u_d:
1641 case Mips::BI__builtin_msa_insve_d:
1642 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1643 case Mips::BI__builtin_msa_sld_d:
1644 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1645 // Memory offsets and immediate loads.
1646 // These intrinsics take a signed 10 bit immediate.
1647 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1648 case Mips::BI__builtin_msa_ldi_h:
1649 case Mips::BI__builtin_msa_ldi_w:
1650 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1651 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1652 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1653 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1654 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1655 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1656 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1657 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1658 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1662 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1664 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1665 SemaBuiltinConstantArgMultiple(TheCall, i, m);
1668 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1669 unsigned i = 0, l = 0, u = 0;
1670 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1671 BuiltinID == PPC::BI__builtin_divdeu ||
1672 BuiltinID == PPC::BI__builtin_bpermd;
1673 bool IsTarget64Bit = Context.getTargetInfo()
1674 .getTypeWidth(Context
1676 .getIntPtrType()) == 64;
1677 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1678 BuiltinID == PPC::BI__builtin_divweu ||
1679 BuiltinID == PPC::BI__builtin_divde ||
1680 BuiltinID == PPC::BI__builtin_divdeu;
1682 if (Is64BitBltin && !IsTarget64Bit)
1683 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1684 << TheCall->getSourceRange();
1686 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1687 (BuiltinID == PPC::BI__builtin_bpermd &&
1688 !Context.getTargetInfo().hasFeature("bpermd")))
1689 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1690 << TheCall->getSourceRange();
1692 switch (BuiltinID) {
1693 default: return false;
1694 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1695 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1696 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1697 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1698 case PPC::BI__builtin_tbegin:
1699 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1700 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1701 case PPC::BI__builtin_tabortwc:
1702 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1703 case PPC::BI__builtin_tabortwci:
1704 case PPC::BI__builtin_tabortdci:
1705 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1706 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1708 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1711 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1712 CallExpr *TheCall) {
1713 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1714 Expr *Arg = TheCall->getArg(0);
1715 llvm::APSInt AbortCode(32);
1716 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1717 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1718 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1719 << Arg->getSourceRange();
1722 // For intrinsics which take an immediate value as part of the instruction,
1723 // range check them here.
1724 unsigned i = 0, l = 0, u = 0;
1725 switch (BuiltinID) {
1726 default: return false;
1727 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1728 case SystemZ::BI__builtin_s390_verimb:
1729 case SystemZ::BI__builtin_s390_verimh:
1730 case SystemZ::BI__builtin_s390_verimf:
1731 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1732 case SystemZ::BI__builtin_s390_vfaeb:
1733 case SystemZ::BI__builtin_s390_vfaeh:
1734 case SystemZ::BI__builtin_s390_vfaef:
1735 case SystemZ::BI__builtin_s390_vfaebs:
1736 case SystemZ::BI__builtin_s390_vfaehs:
1737 case SystemZ::BI__builtin_s390_vfaefs:
1738 case SystemZ::BI__builtin_s390_vfaezb:
1739 case SystemZ::BI__builtin_s390_vfaezh:
1740 case SystemZ::BI__builtin_s390_vfaezf:
1741 case SystemZ::BI__builtin_s390_vfaezbs:
1742 case SystemZ::BI__builtin_s390_vfaezhs:
1743 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1744 case SystemZ::BI__builtin_s390_vfidb:
1745 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1746 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1747 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1748 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1749 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1750 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1751 case SystemZ::BI__builtin_s390_vstrcb:
1752 case SystemZ::BI__builtin_s390_vstrch:
1753 case SystemZ::BI__builtin_s390_vstrcf:
1754 case SystemZ::BI__builtin_s390_vstrczb:
1755 case SystemZ::BI__builtin_s390_vstrczh:
1756 case SystemZ::BI__builtin_s390_vstrczf:
1757 case SystemZ::BI__builtin_s390_vstrcbs:
1758 case SystemZ::BI__builtin_s390_vstrchs:
1759 case SystemZ::BI__builtin_s390_vstrcfs:
1760 case SystemZ::BI__builtin_s390_vstrczbs:
1761 case SystemZ::BI__builtin_s390_vstrczhs:
1762 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1764 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1767 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1768 /// This checks that the target supports __builtin_cpu_supports and
1769 /// that the string argument is constant and valid.
1770 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1771 Expr *Arg = TheCall->getArg(0);
1773 // Check if the argument is a string literal.
1774 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1775 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1776 << Arg->getSourceRange();
1778 // Check the contents of the string.
1780 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1781 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1782 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1783 << Arg->getSourceRange();
1787 // Check if the rounding mode is legal.
1788 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1789 // Indicates if this instruction has rounding control or just SAE.
1792 unsigned ArgNum = 0;
1793 switch (BuiltinID) {
1796 case X86::BI__builtin_ia32_vcvttsd2si32:
1797 case X86::BI__builtin_ia32_vcvttsd2si64:
1798 case X86::BI__builtin_ia32_vcvttsd2usi32:
1799 case X86::BI__builtin_ia32_vcvttsd2usi64:
1800 case X86::BI__builtin_ia32_vcvttss2si32:
1801 case X86::BI__builtin_ia32_vcvttss2si64:
1802 case X86::BI__builtin_ia32_vcvttss2usi32:
1803 case X86::BI__builtin_ia32_vcvttss2usi64:
1806 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1807 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1808 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1809 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1810 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1811 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1812 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1813 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1814 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1815 case X86::BI__builtin_ia32_exp2pd_mask:
1816 case X86::BI__builtin_ia32_exp2ps_mask:
1817 case X86::BI__builtin_ia32_getexppd512_mask:
1818 case X86::BI__builtin_ia32_getexpps512_mask:
1819 case X86::BI__builtin_ia32_rcp28pd_mask:
1820 case X86::BI__builtin_ia32_rcp28ps_mask:
1821 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1822 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1823 case X86::BI__builtin_ia32_vcomisd:
1824 case X86::BI__builtin_ia32_vcomiss:
1825 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1828 case X86::BI__builtin_ia32_cmppd512_mask:
1829 case X86::BI__builtin_ia32_cmpps512_mask:
1830 case X86::BI__builtin_ia32_cmpsd_mask:
1831 case X86::BI__builtin_ia32_cmpss_mask:
1832 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1833 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1834 case X86::BI__builtin_ia32_getexpss128_round_mask:
1835 case X86::BI__builtin_ia32_maxpd512_mask:
1836 case X86::BI__builtin_ia32_maxps512_mask:
1837 case X86::BI__builtin_ia32_maxsd_round_mask:
1838 case X86::BI__builtin_ia32_maxss_round_mask:
1839 case X86::BI__builtin_ia32_minpd512_mask:
1840 case X86::BI__builtin_ia32_minps512_mask:
1841 case X86::BI__builtin_ia32_minsd_round_mask:
1842 case X86::BI__builtin_ia32_minss_round_mask:
1843 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1844 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1845 case X86::BI__builtin_ia32_reducepd512_mask:
1846 case X86::BI__builtin_ia32_reduceps512_mask:
1847 case X86::BI__builtin_ia32_rndscalepd_mask:
1848 case X86::BI__builtin_ia32_rndscaleps_mask:
1849 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1850 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1853 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1854 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1855 case X86::BI__builtin_ia32_fixupimmps512_mask:
1856 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1857 case X86::BI__builtin_ia32_fixupimmsd_mask:
1858 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1859 case X86::BI__builtin_ia32_fixupimmss_mask:
1860 case X86::BI__builtin_ia32_fixupimmss_maskz:
1861 case X86::BI__builtin_ia32_rangepd512_mask:
1862 case X86::BI__builtin_ia32_rangeps512_mask:
1863 case X86::BI__builtin_ia32_rangesd128_round_mask:
1864 case X86::BI__builtin_ia32_rangess128_round_mask:
1865 case X86::BI__builtin_ia32_reducesd_mask:
1866 case X86::BI__builtin_ia32_reducess_mask:
1867 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1868 case X86::BI__builtin_ia32_rndscaless_round_mask:
1871 case X86::BI__builtin_ia32_vcvtsd2si64:
1872 case X86::BI__builtin_ia32_vcvtsd2si32:
1873 case X86::BI__builtin_ia32_vcvtsd2usi32:
1874 case X86::BI__builtin_ia32_vcvtsd2usi64:
1875 case X86::BI__builtin_ia32_vcvtss2si32:
1876 case X86::BI__builtin_ia32_vcvtss2si64:
1877 case X86::BI__builtin_ia32_vcvtss2usi32:
1878 case X86::BI__builtin_ia32_vcvtss2usi64:
1882 case X86::BI__builtin_ia32_cvtsi2sd64:
1883 case X86::BI__builtin_ia32_cvtsi2ss32:
1884 case X86::BI__builtin_ia32_cvtsi2ss64:
1885 case X86::BI__builtin_ia32_cvtusi2sd64:
1886 case X86::BI__builtin_ia32_cvtusi2ss32:
1887 case X86::BI__builtin_ia32_cvtusi2ss64:
1891 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1892 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1893 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1894 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1895 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1896 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1897 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1898 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1899 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1900 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1901 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1902 case X86::BI__builtin_ia32_sqrtpd512_mask:
1903 case X86::BI__builtin_ia32_sqrtps512_mask:
1907 case X86::BI__builtin_ia32_addpd512_mask:
1908 case X86::BI__builtin_ia32_addps512_mask:
1909 case X86::BI__builtin_ia32_divpd512_mask:
1910 case X86::BI__builtin_ia32_divps512_mask:
1911 case X86::BI__builtin_ia32_mulpd512_mask:
1912 case X86::BI__builtin_ia32_mulps512_mask:
1913 case X86::BI__builtin_ia32_subpd512_mask:
1914 case X86::BI__builtin_ia32_subps512_mask:
1915 case X86::BI__builtin_ia32_addss_round_mask:
1916 case X86::BI__builtin_ia32_addsd_round_mask:
1917 case X86::BI__builtin_ia32_divss_round_mask:
1918 case X86::BI__builtin_ia32_divsd_round_mask:
1919 case X86::BI__builtin_ia32_mulss_round_mask:
1920 case X86::BI__builtin_ia32_mulsd_round_mask:
1921 case X86::BI__builtin_ia32_subss_round_mask:
1922 case X86::BI__builtin_ia32_subsd_round_mask:
1923 case X86::BI__builtin_ia32_scalefpd512_mask:
1924 case X86::BI__builtin_ia32_scalefps512_mask:
1925 case X86::BI__builtin_ia32_scalefsd_round_mask:
1926 case X86::BI__builtin_ia32_scalefss_round_mask:
1927 case X86::BI__builtin_ia32_getmantpd512_mask:
1928 case X86::BI__builtin_ia32_getmantps512_mask:
1929 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1930 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1931 case X86::BI__builtin_ia32_sqrtss_round_mask:
1932 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1933 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1934 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1935 case X86::BI__builtin_ia32_vfmaddps512_mask:
1936 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1937 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1938 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1939 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1940 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1941 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1942 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1943 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1944 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1945 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1946 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1947 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1948 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1949 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1950 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1951 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1952 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1953 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1954 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1955 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1956 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1957 case X86::BI__builtin_ia32_vfmaddss3_mask:
1958 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1959 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1963 case X86::BI__builtin_ia32_getmantsd_round_mask:
1964 case X86::BI__builtin_ia32_getmantss_round_mask:
1970 llvm::APSInt Result;
1972 // We can't check the value of a dependent argument.
1973 Expr *Arg = TheCall->getArg(ArgNum);
1974 if (Arg->isTypeDependent() || Arg->isValueDependent())
1977 // Check constant-ness first.
1978 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1981 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1982 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1983 // combined with ROUND_NO_EXC.
1984 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1985 Result == 8/*ROUND_NO_EXC*/ ||
1986 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1989 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1990 << Arg->getSourceRange();
1993 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1994 if (BuiltinID == X86::BI__builtin_cpu_supports)
1995 return SemaBuiltinCpuSupports(*this, TheCall);
1997 if (BuiltinID == X86::BI__builtin_ms_va_start)
1998 return SemaBuiltinMSVAStart(TheCall);
2000 // If the intrinsic has rounding or SAE make sure its valid.
2001 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2004 // For intrinsics which take an immediate value as part of the instruction,
2005 // range check them here.
2006 int i = 0, l = 0, u = 0;
2007 switch (BuiltinID) {
2010 case X86::BI_mm_prefetch:
2011 i = 1; l = 0; u = 3;
2013 case X86::BI__builtin_ia32_sha1rnds4:
2014 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2015 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2016 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2017 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2018 i = 2; l = 0; u = 3;
2020 case X86::BI__builtin_ia32_vpermil2pd:
2021 case X86::BI__builtin_ia32_vpermil2pd256:
2022 case X86::BI__builtin_ia32_vpermil2ps:
2023 case X86::BI__builtin_ia32_vpermil2ps256:
2024 i = 3; l = 0; u = 3;
2026 case X86::BI__builtin_ia32_cmpb128_mask:
2027 case X86::BI__builtin_ia32_cmpw128_mask:
2028 case X86::BI__builtin_ia32_cmpd128_mask:
2029 case X86::BI__builtin_ia32_cmpq128_mask:
2030 case X86::BI__builtin_ia32_cmpb256_mask:
2031 case X86::BI__builtin_ia32_cmpw256_mask:
2032 case X86::BI__builtin_ia32_cmpd256_mask:
2033 case X86::BI__builtin_ia32_cmpq256_mask:
2034 case X86::BI__builtin_ia32_cmpb512_mask:
2035 case X86::BI__builtin_ia32_cmpw512_mask:
2036 case X86::BI__builtin_ia32_cmpd512_mask:
2037 case X86::BI__builtin_ia32_cmpq512_mask:
2038 case X86::BI__builtin_ia32_ucmpb128_mask:
2039 case X86::BI__builtin_ia32_ucmpw128_mask:
2040 case X86::BI__builtin_ia32_ucmpd128_mask:
2041 case X86::BI__builtin_ia32_ucmpq128_mask:
2042 case X86::BI__builtin_ia32_ucmpb256_mask:
2043 case X86::BI__builtin_ia32_ucmpw256_mask:
2044 case X86::BI__builtin_ia32_ucmpd256_mask:
2045 case X86::BI__builtin_ia32_ucmpq256_mask:
2046 case X86::BI__builtin_ia32_ucmpb512_mask:
2047 case X86::BI__builtin_ia32_ucmpw512_mask:
2048 case X86::BI__builtin_ia32_ucmpd512_mask:
2049 case X86::BI__builtin_ia32_ucmpq512_mask:
2050 case X86::BI__builtin_ia32_vpcomub:
2051 case X86::BI__builtin_ia32_vpcomuw:
2052 case X86::BI__builtin_ia32_vpcomud:
2053 case X86::BI__builtin_ia32_vpcomuq:
2054 case X86::BI__builtin_ia32_vpcomb:
2055 case X86::BI__builtin_ia32_vpcomw:
2056 case X86::BI__builtin_ia32_vpcomd:
2057 case X86::BI__builtin_ia32_vpcomq:
2058 i = 2; l = 0; u = 7;
2060 case X86::BI__builtin_ia32_roundps:
2061 case X86::BI__builtin_ia32_roundpd:
2062 case X86::BI__builtin_ia32_roundps256:
2063 case X86::BI__builtin_ia32_roundpd256:
2064 i = 1; l = 0; u = 15;
2066 case X86::BI__builtin_ia32_roundss:
2067 case X86::BI__builtin_ia32_roundsd:
2068 case X86::BI__builtin_ia32_rangepd128_mask:
2069 case X86::BI__builtin_ia32_rangepd256_mask:
2070 case X86::BI__builtin_ia32_rangepd512_mask:
2071 case X86::BI__builtin_ia32_rangeps128_mask:
2072 case X86::BI__builtin_ia32_rangeps256_mask:
2073 case X86::BI__builtin_ia32_rangeps512_mask:
2074 case X86::BI__builtin_ia32_getmantsd_round_mask:
2075 case X86::BI__builtin_ia32_getmantss_round_mask:
2076 i = 2; l = 0; u = 15;
2078 case X86::BI__builtin_ia32_cmpps:
2079 case X86::BI__builtin_ia32_cmpss:
2080 case X86::BI__builtin_ia32_cmppd:
2081 case X86::BI__builtin_ia32_cmpsd:
2082 case X86::BI__builtin_ia32_cmpps256:
2083 case X86::BI__builtin_ia32_cmppd256:
2084 case X86::BI__builtin_ia32_cmpps128_mask:
2085 case X86::BI__builtin_ia32_cmppd128_mask:
2086 case X86::BI__builtin_ia32_cmpps256_mask:
2087 case X86::BI__builtin_ia32_cmppd256_mask:
2088 case X86::BI__builtin_ia32_cmpps512_mask:
2089 case X86::BI__builtin_ia32_cmppd512_mask:
2090 case X86::BI__builtin_ia32_cmpsd_mask:
2091 case X86::BI__builtin_ia32_cmpss_mask:
2092 i = 2; l = 0; u = 31;
2094 case X86::BI__builtin_ia32_xabort:
2095 i = 0; l = -128; u = 255;
2097 case X86::BI__builtin_ia32_pshufw:
2098 case X86::BI__builtin_ia32_aeskeygenassist128:
2099 i = 1; l = -128; u = 255;
2101 case X86::BI__builtin_ia32_vcvtps2ph:
2102 case X86::BI__builtin_ia32_vcvtps2ph256:
2103 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2104 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2105 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2106 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2107 case X86::BI__builtin_ia32_rndscaleps_mask:
2108 case X86::BI__builtin_ia32_rndscalepd_mask:
2109 case X86::BI__builtin_ia32_reducepd128_mask:
2110 case X86::BI__builtin_ia32_reducepd256_mask:
2111 case X86::BI__builtin_ia32_reducepd512_mask:
2112 case X86::BI__builtin_ia32_reduceps128_mask:
2113 case X86::BI__builtin_ia32_reduceps256_mask:
2114 case X86::BI__builtin_ia32_reduceps512_mask:
2115 case X86::BI__builtin_ia32_prold512_mask:
2116 case X86::BI__builtin_ia32_prolq512_mask:
2117 case X86::BI__builtin_ia32_prold128_mask:
2118 case X86::BI__builtin_ia32_prold256_mask:
2119 case X86::BI__builtin_ia32_prolq128_mask:
2120 case X86::BI__builtin_ia32_prolq256_mask:
2121 case X86::BI__builtin_ia32_prord128_mask:
2122 case X86::BI__builtin_ia32_prord256_mask:
2123 case X86::BI__builtin_ia32_prorq128_mask:
2124 case X86::BI__builtin_ia32_prorq256_mask:
2125 case X86::BI__builtin_ia32_fpclasspd128_mask:
2126 case X86::BI__builtin_ia32_fpclasspd256_mask:
2127 case X86::BI__builtin_ia32_fpclassps128_mask:
2128 case X86::BI__builtin_ia32_fpclassps256_mask:
2129 case X86::BI__builtin_ia32_fpclassps512_mask:
2130 case X86::BI__builtin_ia32_fpclasspd512_mask:
2131 case X86::BI__builtin_ia32_fpclasssd_mask:
2132 case X86::BI__builtin_ia32_fpclassss_mask:
2133 i = 1; l = 0; u = 255;
2135 case X86::BI__builtin_ia32_palignr:
2136 case X86::BI__builtin_ia32_insertps128:
2137 case X86::BI__builtin_ia32_dpps:
2138 case X86::BI__builtin_ia32_dppd:
2139 case X86::BI__builtin_ia32_dpps256:
2140 case X86::BI__builtin_ia32_mpsadbw128:
2141 case X86::BI__builtin_ia32_mpsadbw256:
2142 case X86::BI__builtin_ia32_pcmpistrm128:
2143 case X86::BI__builtin_ia32_pcmpistri128:
2144 case X86::BI__builtin_ia32_pcmpistria128:
2145 case X86::BI__builtin_ia32_pcmpistric128:
2146 case X86::BI__builtin_ia32_pcmpistrio128:
2147 case X86::BI__builtin_ia32_pcmpistris128:
2148 case X86::BI__builtin_ia32_pcmpistriz128:
2149 case X86::BI__builtin_ia32_pclmulqdq128:
2150 case X86::BI__builtin_ia32_vperm2f128_pd256:
2151 case X86::BI__builtin_ia32_vperm2f128_ps256:
2152 case X86::BI__builtin_ia32_vperm2f128_si256:
2153 case X86::BI__builtin_ia32_permti256:
2154 i = 2; l = -128; u = 255;
2156 case X86::BI__builtin_ia32_palignr128:
2157 case X86::BI__builtin_ia32_palignr256:
2158 case X86::BI__builtin_ia32_palignr512_mask:
2159 case X86::BI__builtin_ia32_vcomisd:
2160 case X86::BI__builtin_ia32_vcomiss:
2161 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2162 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2163 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2164 case X86::BI__builtin_ia32_shuf_i64x2_mask:
2165 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2166 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2167 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2168 i = 2; l = 0; u = 255;
2170 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2171 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2172 case X86::BI__builtin_ia32_fixupimmps512_mask:
2173 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2174 case X86::BI__builtin_ia32_fixupimmsd_mask:
2175 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2176 case X86::BI__builtin_ia32_fixupimmss_mask:
2177 case X86::BI__builtin_ia32_fixupimmss_maskz:
2178 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2179 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2180 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2181 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2182 case X86::BI__builtin_ia32_fixupimmps128_mask:
2183 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2184 case X86::BI__builtin_ia32_fixupimmps256_mask:
2185 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2186 case X86::BI__builtin_ia32_pternlogd512_mask:
2187 case X86::BI__builtin_ia32_pternlogd512_maskz:
2188 case X86::BI__builtin_ia32_pternlogq512_mask:
2189 case X86::BI__builtin_ia32_pternlogq512_maskz:
2190 case X86::BI__builtin_ia32_pternlogd128_mask:
2191 case X86::BI__builtin_ia32_pternlogd128_maskz:
2192 case X86::BI__builtin_ia32_pternlogd256_mask:
2193 case X86::BI__builtin_ia32_pternlogd256_maskz:
2194 case X86::BI__builtin_ia32_pternlogq128_mask:
2195 case X86::BI__builtin_ia32_pternlogq128_maskz:
2196 case X86::BI__builtin_ia32_pternlogq256_mask:
2197 case X86::BI__builtin_ia32_pternlogq256_maskz:
2198 i = 3; l = 0; u = 255;
2200 case X86::BI__builtin_ia32_pcmpestrm128:
2201 case X86::BI__builtin_ia32_pcmpestri128:
2202 case X86::BI__builtin_ia32_pcmpestria128:
2203 case X86::BI__builtin_ia32_pcmpestric128:
2204 case X86::BI__builtin_ia32_pcmpestrio128:
2205 case X86::BI__builtin_ia32_pcmpestris128:
2206 case X86::BI__builtin_ia32_pcmpestriz128:
2207 i = 4; l = -128; u = 255;
2209 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2210 case X86::BI__builtin_ia32_rndscaless_round_mask:
2211 i = 4; l = 0; u = 255;
2214 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2217 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2218 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2219 /// Returns true when the format fits the function and the FormatStringInfo has
2221 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2222 FormatStringInfo *FSI) {
2223 FSI->HasVAListArg = Format->getFirstArg() == 0;
2224 FSI->FormatIdx = Format->getFormatIdx() - 1;
2225 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2227 // The way the format attribute works in GCC, the implicit this argument
2228 // of member functions is counted. However, it doesn't appear in our own
2229 // lists, so decrement format_idx in that case.
2231 if(FSI->FormatIdx == 0)
2234 if (FSI->FirstDataArg != 0)
2235 --FSI->FirstDataArg;
2240 /// Checks if a the given expression evaluates to null.
2242 /// \brief Returns true if the value evaluates to null.
2243 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2244 // If the expression has non-null type, it doesn't evaluate to null.
2245 if (auto nullability
2246 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2247 if (*nullability == NullabilityKind::NonNull)
2251 // As a special case, transparent unions initialized with zero are
2252 // considered null for the purposes of the nonnull attribute.
2253 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2254 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2255 if (const CompoundLiteralExpr *CLE =
2256 dyn_cast<CompoundLiteralExpr>(Expr))
2257 if (const InitListExpr *ILE =
2258 dyn_cast<InitListExpr>(CLE->getInitializer()))
2259 Expr = ILE->getInit(0);
2263 return (!Expr->isValueDependent() &&
2264 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2268 static void CheckNonNullArgument(Sema &S,
2269 const Expr *ArgExpr,
2270 SourceLocation CallSiteLoc) {
2271 if (CheckNonNullExpr(S, ArgExpr))
2272 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2273 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2276 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2277 FormatStringInfo FSI;
2278 if ((GetFormatStringType(Format) == FST_NSString) &&
2279 getFormatStringInfo(Format, false, &FSI)) {
2280 Idx = FSI.FormatIdx;
2285 /// \brief Diagnose use of %s directive in an NSString which is being passed
2286 /// as formatting string to formatting method.
2288 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2289 const NamedDecl *FDecl,
2293 bool Format = false;
2294 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2295 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2300 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2301 if (S.GetFormatNSStringIdx(I, Idx)) {
2306 if (!Format || NumArgs <= Idx)
2308 const Expr *FormatExpr = Args[Idx];
2309 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2310 FormatExpr = CSCE->getSubExpr();
2311 const StringLiteral *FormatString;
2312 if (const ObjCStringLiteral *OSL =
2313 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2314 FormatString = OSL->getString();
2316 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2319 if (S.FormatStringHasSArg(FormatString)) {
2320 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2322 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2323 << FDecl->getDeclName();
2327 /// Determine whether the given type has a non-null nullability annotation.
2328 static bool isNonNullType(ASTContext &ctx, QualType type) {
2329 if (auto nullability = type->getNullability(ctx))
2330 return *nullability == NullabilityKind::NonNull;
2335 static void CheckNonNullArguments(Sema &S,
2336 const NamedDecl *FDecl,
2337 const FunctionProtoType *Proto,
2338 ArrayRef<const Expr *> Args,
2339 SourceLocation CallSiteLoc) {
2340 assert((FDecl || Proto) && "Need a function declaration or prototype");
2342 // Check the attributes attached to the method/function itself.
2343 llvm::SmallBitVector NonNullArgs;
2345 // Handle the nonnull attribute on the function/method declaration itself.
2346 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2347 if (!NonNull->args_size()) {
2348 // Easy case: all pointer arguments are nonnull.
2349 for (const auto *Arg : Args)
2350 if (S.isValidPointerAttrType(Arg->getType()))
2351 CheckNonNullArgument(S, Arg, CallSiteLoc);
2355 for (unsigned Val : NonNull->args()) {
2356 if (Val >= Args.size())
2358 if (NonNullArgs.empty())
2359 NonNullArgs.resize(Args.size());
2360 NonNullArgs.set(Val);
2365 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2366 // Handle the nonnull attribute on the parameters of the
2368 ArrayRef<ParmVarDecl*> parms;
2369 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2370 parms = FD->parameters();
2372 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2374 unsigned ParamIndex = 0;
2375 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2376 I != E; ++I, ++ParamIndex) {
2377 const ParmVarDecl *PVD = *I;
2378 if (PVD->hasAttr<NonNullAttr>() ||
2379 isNonNullType(S.Context, PVD->getType())) {
2380 if (NonNullArgs.empty())
2381 NonNullArgs.resize(Args.size());
2383 NonNullArgs.set(ParamIndex);
2387 // If we have a non-function, non-method declaration but no
2388 // function prototype, try to dig out the function prototype.
2390 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2391 QualType type = VD->getType().getNonReferenceType();
2392 if (auto pointerType = type->getAs<PointerType>())
2393 type = pointerType->getPointeeType();
2394 else if (auto blockType = type->getAs<BlockPointerType>())
2395 type = blockType->getPointeeType();
2396 // FIXME: data member pointers?
2398 // Dig out the function prototype, if there is one.
2399 Proto = type->getAs<FunctionProtoType>();
2403 // Fill in non-null argument information from the nullability
2404 // information on the parameter types (if we have them).
2407 for (auto paramType : Proto->getParamTypes()) {
2408 if (isNonNullType(S.Context, paramType)) {
2409 if (NonNullArgs.empty())
2410 NonNullArgs.resize(Args.size());
2412 NonNullArgs.set(Index);
2420 // Check for non-null arguments.
2421 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2422 ArgIndex != ArgIndexEnd; ++ArgIndex) {
2423 if (NonNullArgs[ArgIndex])
2424 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2428 /// Handles the checks for format strings, non-POD arguments to vararg
2429 /// functions, and NULL arguments passed to non-NULL parameters.
2430 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2431 ArrayRef<const Expr *> Args, bool IsMemberFunction,
2432 SourceLocation Loc, SourceRange Range,
2433 VariadicCallType CallType) {
2434 // FIXME: We should check as much as we can in the template definition.
2435 if (CurContext->isDependentContext())
2438 // Printf and scanf checking.
2439 llvm::SmallBitVector CheckedVarArgs;
2441 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2442 // Only create vector if there are format attributes.
2443 CheckedVarArgs.resize(Args.size());
2445 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2450 // Refuse POD arguments that weren't caught by the format string
2452 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2453 if (CallType != VariadicDoesNotApply &&
2454 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2455 unsigned NumParams = Proto ? Proto->getNumParams()
2456 : FDecl && isa<FunctionDecl>(FDecl)
2457 ? cast<FunctionDecl>(FDecl)->getNumParams()
2458 : FDecl && isa<ObjCMethodDecl>(FDecl)
2459 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2462 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2463 // Args[ArgIdx] can be null in malformed code.
2464 if (const Expr *Arg = Args[ArgIdx]) {
2465 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2466 checkVariadicArgument(Arg, CallType);
2471 if (FDecl || Proto) {
2472 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2474 // Type safety checking.
2476 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2477 CheckArgumentWithTypeTag(I, Args.data());
2482 /// CheckConstructorCall - Check a constructor call for correctness and safety
2483 /// properties not enforced by the C type system.
2484 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2485 ArrayRef<const Expr *> Args,
2486 const FunctionProtoType *Proto,
2487 SourceLocation Loc) {
2488 VariadicCallType CallType =
2489 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2490 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2494 /// CheckFunctionCall - Check a direct function call for various correctness
2495 /// and safety properties not strictly enforced by the C type system.
2496 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2497 const FunctionProtoType *Proto) {
2498 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2499 isa<CXXMethodDecl>(FDecl);
2500 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2501 IsMemberOperatorCall;
2502 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2503 TheCall->getCallee());
2504 Expr** Args = TheCall->getArgs();
2505 unsigned NumArgs = TheCall->getNumArgs();
2506 if (IsMemberOperatorCall) {
2507 // If this is a call to a member operator, hide the first argument
2509 // FIXME: Our choice of AST representation here is less than ideal.
2513 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
2514 IsMemberFunction, TheCall->getRParenLoc(),
2515 TheCall->getCallee()->getSourceRange(), CallType);
2517 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2518 // None of the checks below are needed for functions that don't have
2519 // simple names (e.g., C++ conversion functions).
2523 CheckAbsoluteValueFunction(TheCall, FDecl);
2524 CheckMaxUnsignedZero(TheCall, FDecl);
2526 if (getLangOpts().ObjC1)
2527 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2529 unsigned CMId = FDecl->getMemoryFunctionKind();
2533 // Handle memory setting and copying functions.
2534 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2535 CheckStrlcpycatArguments(TheCall, FnInfo);
2536 else if (CMId == Builtin::BIstrncat)
2537 CheckStrncatArguments(TheCall, FnInfo);
2539 CheckMemaccessArguments(TheCall, CMId, FnInfo);
2544 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2545 ArrayRef<const Expr *> Args) {
2546 VariadicCallType CallType =
2547 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2549 checkCall(Method, nullptr, Args,
2550 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2556 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2557 const FunctionProtoType *Proto) {
2559 if (const auto *V = dyn_cast<VarDecl>(NDecl))
2560 Ty = V->getType().getNonReferenceType();
2561 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2562 Ty = F->getType().getNonReferenceType();
2566 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2567 !Ty->isFunctionProtoType())
2570 VariadicCallType CallType;
2571 if (!Proto || !Proto->isVariadic()) {
2572 CallType = VariadicDoesNotApply;
2573 } else if (Ty->isBlockPointerType()) {
2574 CallType = VariadicBlock;
2575 } else { // Ty->isFunctionPointerType()
2576 CallType = VariadicFunction;
2579 checkCall(NDecl, Proto,
2580 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2581 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2582 TheCall->getCallee()->getSourceRange(), CallType);
2587 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2588 /// such as function pointers returned from functions.
2589 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2590 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2591 TheCall->getCallee());
2592 checkCall(/*FDecl=*/nullptr, Proto,
2593 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2594 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2595 TheCall->getCallee()->getSourceRange(), CallType);
2600 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2601 if (!llvm::isValidAtomicOrderingCABI(Ordering))
2604 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2606 case AtomicExpr::AO__c11_atomic_init:
2607 llvm_unreachable("There is no ordering argument for an init");
2609 case AtomicExpr::AO__c11_atomic_load:
2610 case AtomicExpr::AO__atomic_load_n:
2611 case AtomicExpr::AO__atomic_load:
2612 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2613 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2615 case AtomicExpr::AO__c11_atomic_store:
2616 case AtomicExpr::AO__atomic_store:
2617 case AtomicExpr::AO__atomic_store_n:
2618 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2619 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2620 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2627 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2628 AtomicExpr::AtomicOp Op) {
2629 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2630 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2632 // All these operations take one of the following forms:
2634 // C __c11_atomic_init(A *, C)
2636 // C __c11_atomic_load(A *, int)
2638 // void __atomic_load(A *, CP, int)
2640 // void __atomic_store(A *, CP, int)
2642 // C __c11_atomic_add(A *, M, int)
2644 // C __atomic_exchange_n(A *, CP, int)
2646 // void __atomic_exchange(A *, C *, CP, int)
2648 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2650 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2653 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2654 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2656 // C is an appropriate type,
2657 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2658 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2659 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2660 // the int parameters are for orderings.
2662 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2663 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2664 AtomicExpr::AO__atomic_load,
2665 "need to update code for modified C11 atomics");
2666 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2667 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2668 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2669 Op == AtomicExpr::AO__atomic_store_n ||
2670 Op == AtomicExpr::AO__atomic_exchange_n ||
2671 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2672 bool IsAddSub = false;
2675 case AtomicExpr::AO__c11_atomic_init:
2679 case AtomicExpr::AO__c11_atomic_load:
2680 case AtomicExpr::AO__atomic_load_n:
2684 case AtomicExpr::AO__atomic_load:
2688 case AtomicExpr::AO__c11_atomic_store:
2689 case AtomicExpr::AO__atomic_store:
2690 case AtomicExpr::AO__atomic_store_n:
2694 case AtomicExpr::AO__c11_atomic_fetch_add:
2695 case AtomicExpr::AO__c11_atomic_fetch_sub:
2696 case AtomicExpr::AO__atomic_fetch_add:
2697 case AtomicExpr::AO__atomic_fetch_sub:
2698 case AtomicExpr::AO__atomic_add_fetch:
2699 case AtomicExpr::AO__atomic_sub_fetch:
2702 case AtomicExpr::AO__c11_atomic_fetch_and:
2703 case AtomicExpr::AO__c11_atomic_fetch_or:
2704 case AtomicExpr::AO__c11_atomic_fetch_xor:
2705 case AtomicExpr::AO__atomic_fetch_and:
2706 case AtomicExpr::AO__atomic_fetch_or:
2707 case AtomicExpr::AO__atomic_fetch_xor:
2708 case AtomicExpr::AO__atomic_fetch_nand:
2709 case AtomicExpr::AO__atomic_and_fetch:
2710 case AtomicExpr::AO__atomic_or_fetch:
2711 case AtomicExpr::AO__atomic_xor_fetch:
2712 case AtomicExpr::AO__atomic_nand_fetch:
2716 case AtomicExpr::AO__c11_atomic_exchange:
2717 case AtomicExpr::AO__atomic_exchange_n:
2721 case AtomicExpr::AO__atomic_exchange:
2725 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2726 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2730 case AtomicExpr::AO__atomic_compare_exchange:
2731 case AtomicExpr::AO__atomic_compare_exchange_n:
2736 // Check we have the right number of arguments.
2737 if (TheCall->getNumArgs() < NumArgs[Form]) {
2738 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2739 << 0 << NumArgs[Form] << TheCall->getNumArgs()
2740 << TheCall->getCallee()->getSourceRange();
2742 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2743 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2744 diag::err_typecheck_call_too_many_args)
2745 << 0 << NumArgs[Form] << TheCall->getNumArgs()
2746 << TheCall->getCallee()->getSourceRange();
2750 // Inspect the first argument of the atomic operation.
2751 Expr *Ptr = TheCall->getArg(0);
2752 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2753 if (ConvertedPtr.isInvalid())
2756 Ptr = ConvertedPtr.get();
2757 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2759 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2760 << Ptr->getType() << Ptr->getSourceRange();
2764 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2765 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2766 QualType ValType = AtomTy; // 'C'
2768 if (!AtomTy->isAtomicType()) {
2769 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2770 << Ptr->getType() << Ptr->getSourceRange();
2773 if (AtomTy.isConstQualified()) {
2774 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2775 << Ptr->getType() << Ptr->getSourceRange();
2778 ValType = AtomTy->getAs<AtomicType>()->getValueType();
2779 } else if (Form != Load && Form != LoadCopy) {
2780 if (ValType.isConstQualified()) {
2781 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2782 << Ptr->getType() << Ptr->getSourceRange();
2787 // For an arithmetic operation, the implied arithmetic must be well-formed.
2788 if (Form == Arithmetic) {
2789 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2790 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2791 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2792 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2795 if (!IsAddSub && !ValType->isIntegerType()) {
2796 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2797 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2800 if (IsC11 && ValType->isPointerType() &&
2801 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2802 diag::err_incomplete_type)) {
2805 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2806 // For __atomic_*_n operations, the value type must be a scalar integral or
2807 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2808 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2809 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2813 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2814 !AtomTy->isScalarType()) {
2815 // For GNU atomics, require a trivially-copyable type. This is not part of
2816 // the GNU atomics specification, but we enforce it for sanity.
2817 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2818 << Ptr->getType() << Ptr->getSourceRange();
2822 switch (ValType.getObjCLifetime()) {
2823 case Qualifiers::OCL_None:
2824 case Qualifiers::OCL_ExplicitNone:
2828 case Qualifiers::OCL_Weak:
2829 case Qualifiers::OCL_Strong:
2830 case Qualifiers::OCL_Autoreleasing:
2831 // FIXME: Can this happen? By this point, ValType should be known
2832 // to be trivially copyable.
2833 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2834 << ValType << Ptr->getSourceRange();
2838 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2839 // volatile-ness of the pointee-type inject itself into the result or the
2840 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2841 ValType.removeLocalVolatile();
2842 ValType.removeLocalConst();
2843 QualType ResultType = ValType;
2844 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2845 ResultType = Context.VoidTy;
2846 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2847 ResultType = Context.BoolTy;
2849 // The type of a parameter passed 'by value'. In the GNU atomics, such
2850 // arguments are actually passed as pointers.
2851 QualType ByValType = ValType; // 'CP'
2853 ByValType = Ptr->getType();
2855 // The first argument --- the pointer --- has a fixed type; we
2856 // deduce the types of the rest of the arguments accordingly. Walk
2857 // the remaining arguments, converting them to the deduced value type.
2858 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2860 if (i < NumVals[Form] + 1) {
2863 // The second argument is the non-atomic operand. For arithmetic, this
2864 // is always passed by value, and for a compare_exchange it is always
2865 // passed by address. For the rest, GNU uses by-address and C11 uses
2867 assert(Form != Load);
2868 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2870 else if (Form == Copy || Form == Xchg)
2872 else if (Form == Arithmetic)
2873 Ty = Context.getPointerDiffType();
2875 Expr *ValArg = TheCall->getArg(i);
2876 // Treat this argument as _Nonnull as we want to show a warning if
2877 // NULL is passed into it.
2878 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
2880 // Keep address space of non-atomic pointer type.
2881 if (const PointerType *PtrTy =
2882 ValArg->getType()->getAs<PointerType>()) {
2883 AS = PtrTy->getPointeeType().getAddressSpace();
2885 Ty = Context.getPointerType(
2886 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2890 // The third argument to compare_exchange / GNU exchange is a
2891 // (pointer to a) desired value.
2895 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2896 Ty = Context.BoolTy;
2900 // The order(s) are always converted to int.
2904 InitializedEntity Entity =
2905 InitializedEntity::InitializeParameter(Context, Ty, false);
2906 ExprResult Arg = TheCall->getArg(i);
2907 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2908 if (Arg.isInvalid())
2910 TheCall->setArg(i, Arg.get());
2913 // Permute the arguments into a 'consistent' order.
2914 SmallVector<Expr*, 5> SubExprs;
2915 SubExprs.push_back(Ptr);
2918 // Note, AtomicExpr::getVal1() has a special case for this atomic.
2919 SubExprs.push_back(TheCall->getArg(1)); // Val1
2922 SubExprs.push_back(TheCall->getArg(1)); // Order
2928 SubExprs.push_back(TheCall->getArg(2)); // Order
2929 SubExprs.push_back(TheCall->getArg(1)); // Val1
2932 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2933 SubExprs.push_back(TheCall->getArg(3)); // Order
2934 SubExprs.push_back(TheCall->getArg(1)); // Val1
2935 SubExprs.push_back(TheCall->getArg(2)); // Val2
2938 SubExprs.push_back(TheCall->getArg(3)); // Order
2939 SubExprs.push_back(TheCall->getArg(1)); // Val1
2940 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2941 SubExprs.push_back(TheCall->getArg(2)); // Val2
2944 SubExprs.push_back(TheCall->getArg(4)); // Order
2945 SubExprs.push_back(TheCall->getArg(1)); // Val1
2946 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2947 SubExprs.push_back(TheCall->getArg(2)); // Val2
2948 SubExprs.push_back(TheCall->getArg(3)); // Weak
2952 if (SubExprs.size() >= 2 && Form != Init) {
2953 llvm::APSInt Result(32);
2954 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2955 !isValidOrderingForOp(Result.getSExtValue(), Op))
2956 Diag(SubExprs[1]->getLocStart(),
2957 diag::warn_atomic_op_has_invalid_memory_order)
2958 << SubExprs[1]->getSourceRange();
2961 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2962 SubExprs, ResultType, Op,
2963 TheCall->getRParenLoc());
2965 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2966 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2967 Context.AtomicUsesUnsupportedLibcall(AE))
2968 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2969 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2974 /// checkBuiltinArgument - Given a call to a builtin function, perform
2975 /// normal type-checking on the given argument, updating the call in
2976 /// place. This is useful when a builtin function requires custom
2977 /// type-checking for some of its arguments but not necessarily all of
2980 /// Returns true on error.
2981 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2982 FunctionDecl *Fn = E->getDirectCallee();
2983 assert(Fn && "builtin call without direct callee!");
2985 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2986 InitializedEntity Entity =
2987 InitializedEntity::InitializeParameter(S.Context, Param);
2989 ExprResult Arg = E->getArg(0);
2990 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2991 if (Arg.isInvalid())
2994 E->setArg(ArgIndex, Arg.get());
2998 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
2999 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3000 /// type of its first argument. The main ActOnCallExpr routines have already
3001 /// promoted the types of arguments because all of these calls are prototyped as
3004 /// This function goes through and does final semantic checking for these
3007 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3008 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3009 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3010 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3012 // Ensure that we have at least one argument to do type inference from.
3013 if (TheCall->getNumArgs() < 1) {
3014 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3015 << 0 << 1 << TheCall->getNumArgs()
3016 << TheCall->getCallee()->getSourceRange();
3020 // Inspect the first argument of the atomic builtin. This should always be
3021 // a pointer type, whose element is an integral scalar or pointer type.
3022 // Because it is a pointer type, we don't have to worry about any implicit
3024 // FIXME: We don't allow floating point scalars as input.
3025 Expr *FirstArg = TheCall->getArg(0);
3026 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3027 if (FirstArgResult.isInvalid())
3029 FirstArg = FirstArgResult.get();
3030 TheCall->setArg(0, FirstArg);
3032 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3034 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3035 << FirstArg->getType() << FirstArg->getSourceRange();
3039 QualType ValType = pointerType->getPointeeType();
3040 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3041 !ValType->isBlockPointerType()) {
3042 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3043 << FirstArg->getType() << FirstArg->getSourceRange();
3047 switch (ValType.getObjCLifetime()) {
3048 case Qualifiers::OCL_None:
3049 case Qualifiers::OCL_ExplicitNone:
3053 case Qualifiers::OCL_Weak:
3054 case Qualifiers::OCL_Strong:
3055 case Qualifiers::OCL_Autoreleasing:
3056 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3057 << ValType << FirstArg->getSourceRange();
3061 // Strip any qualifiers off ValType.
3062 ValType = ValType.getUnqualifiedType();
3064 // The majority of builtins return a value, but a few have special return
3065 // types, so allow them to override appropriately below.
3066 QualType ResultType = ValType;
3068 // We need to figure out which concrete builtin this maps onto. For example,
3069 // __sync_fetch_and_add with a 2 byte object turns into
3070 // __sync_fetch_and_add_2.
3071 #define BUILTIN_ROW(x) \
3072 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3073 Builtin::BI##x##_8, Builtin::BI##x##_16 }
3075 static const unsigned BuiltinIndices[][5] = {
3076 BUILTIN_ROW(__sync_fetch_and_add),
3077 BUILTIN_ROW(__sync_fetch_and_sub),
3078 BUILTIN_ROW(__sync_fetch_and_or),
3079 BUILTIN_ROW(__sync_fetch_and_and),
3080 BUILTIN_ROW(__sync_fetch_and_xor),
3081 BUILTIN_ROW(__sync_fetch_and_nand),
3083 BUILTIN_ROW(__sync_add_and_fetch),
3084 BUILTIN_ROW(__sync_sub_and_fetch),
3085 BUILTIN_ROW(__sync_and_and_fetch),
3086 BUILTIN_ROW(__sync_or_and_fetch),
3087 BUILTIN_ROW(__sync_xor_and_fetch),
3088 BUILTIN_ROW(__sync_nand_and_fetch),
3090 BUILTIN_ROW(__sync_val_compare_and_swap),
3091 BUILTIN_ROW(__sync_bool_compare_and_swap),
3092 BUILTIN_ROW(__sync_lock_test_and_set),
3093 BUILTIN_ROW(__sync_lock_release),
3094 BUILTIN_ROW(__sync_swap)
3098 // Determine the index of the size.
3100 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3101 case 1: SizeIndex = 0; break;
3102 case 2: SizeIndex = 1; break;
3103 case 4: SizeIndex = 2; break;
3104 case 8: SizeIndex = 3; break;
3105 case 16: SizeIndex = 4; break;
3107 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3108 << FirstArg->getType() << FirstArg->getSourceRange();
3112 // Each of these builtins has one pointer argument, followed by some number of
3113 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3114 // that we ignore. Find out which row of BuiltinIndices to read from as well
3115 // as the number of fixed args.
3116 unsigned BuiltinID = FDecl->getBuiltinID();
3117 unsigned BuiltinIndex, NumFixed = 1;
3118 bool WarnAboutSemanticsChange = false;
3119 switch (BuiltinID) {
3120 default: llvm_unreachable("Unknown overloaded atomic builtin!");
3121 case Builtin::BI__sync_fetch_and_add:
3122 case Builtin::BI__sync_fetch_and_add_1:
3123 case Builtin::BI__sync_fetch_and_add_2:
3124 case Builtin::BI__sync_fetch_and_add_4:
3125 case Builtin::BI__sync_fetch_and_add_8:
3126 case Builtin::BI__sync_fetch_and_add_16:
3130 case Builtin::BI__sync_fetch_and_sub:
3131 case Builtin::BI__sync_fetch_and_sub_1:
3132 case Builtin::BI__sync_fetch_and_sub_2:
3133 case Builtin::BI__sync_fetch_and_sub_4:
3134 case Builtin::BI__sync_fetch_and_sub_8:
3135 case Builtin::BI__sync_fetch_and_sub_16:
3139 case Builtin::BI__sync_fetch_and_or:
3140 case Builtin::BI__sync_fetch_and_or_1:
3141 case Builtin::BI__sync_fetch_and_or_2:
3142 case Builtin::BI__sync_fetch_and_or_4:
3143 case Builtin::BI__sync_fetch_and_or_8:
3144 case Builtin::BI__sync_fetch_and_or_16:
3148 case Builtin::BI__sync_fetch_and_and:
3149 case Builtin::BI__sync_fetch_and_and_1:
3150 case Builtin::BI__sync_fetch_and_and_2:
3151 case Builtin::BI__sync_fetch_and_and_4:
3152 case Builtin::BI__sync_fetch_and_and_8:
3153 case Builtin::BI__sync_fetch_and_and_16:
3157 case Builtin::BI__sync_fetch_and_xor:
3158 case Builtin::BI__sync_fetch_and_xor_1:
3159 case Builtin::BI__sync_fetch_and_xor_2:
3160 case Builtin::BI__sync_fetch_and_xor_4:
3161 case Builtin::BI__sync_fetch_and_xor_8:
3162 case Builtin::BI__sync_fetch_and_xor_16:
3166 case Builtin::BI__sync_fetch_and_nand:
3167 case Builtin::BI__sync_fetch_and_nand_1:
3168 case Builtin::BI__sync_fetch_and_nand_2:
3169 case Builtin::BI__sync_fetch_and_nand_4:
3170 case Builtin::BI__sync_fetch_and_nand_8:
3171 case Builtin::BI__sync_fetch_and_nand_16:
3173 WarnAboutSemanticsChange = true;
3176 case Builtin::BI__sync_add_and_fetch:
3177 case Builtin::BI__sync_add_and_fetch_1:
3178 case Builtin::BI__sync_add_and_fetch_2:
3179 case Builtin::BI__sync_add_and_fetch_4:
3180 case Builtin::BI__sync_add_and_fetch_8:
3181 case Builtin::BI__sync_add_and_fetch_16:
3185 case Builtin::BI__sync_sub_and_fetch:
3186 case Builtin::BI__sync_sub_and_fetch_1:
3187 case Builtin::BI__sync_sub_and_fetch_2:
3188 case Builtin::BI__sync_sub_and_fetch_4:
3189 case Builtin::BI__sync_sub_and_fetch_8:
3190 case Builtin::BI__sync_sub_and_fetch_16:
3194 case Builtin::BI__sync_and_and_fetch:
3195 case Builtin::BI__sync_and_and_fetch_1:
3196 case Builtin::BI__sync_and_and_fetch_2:
3197 case Builtin::BI__sync_and_and_fetch_4:
3198 case Builtin::BI__sync_and_and_fetch_8:
3199 case Builtin::BI__sync_and_and_fetch_16:
3203 case Builtin::BI__sync_or_and_fetch:
3204 case Builtin::BI__sync_or_and_fetch_1:
3205 case Builtin::BI__sync_or_and_fetch_2:
3206 case Builtin::BI__sync_or_and_fetch_4:
3207 case Builtin::BI__sync_or_and_fetch_8:
3208 case Builtin::BI__sync_or_and_fetch_16:
3212 case Builtin::BI__sync_xor_and_fetch:
3213 case Builtin::BI__sync_xor_and_fetch_1:
3214 case Builtin::BI__sync_xor_and_fetch_2:
3215 case Builtin::BI__sync_xor_and_fetch_4:
3216 case Builtin::BI__sync_xor_and_fetch_8:
3217 case Builtin::BI__sync_xor_and_fetch_16:
3221 case Builtin::BI__sync_nand_and_fetch:
3222 case Builtin::BI__sync_nand_and_fetch_1:
3223 case Builtin::BI__sync_nand_and_fetch_2:
3224 case Builtin::BI__sync_nand_and_fetch_4:
3225 case Builtin::BI__sync_nand_and_fetch_8:
3226 case Builtin::BI__sync_nand_and_fetch_16:
3228 WarnAboutSemanticsChange = true;
3231 case Builtin::BI__sync_val_compare_and_swap:
3232 case Builtin::BI__sync_val_compare_and_swap_1:
3233 case Builtin::BI__sync_val_compare_and_swap_2:
3234 case Builtin::BI__sync_val_compare_and_swap_4:
3235 case Builtin::BI__sync_val_compare_and_swap_8:
3236 case Builtin::BI__sync_val_compare_and_swap_16:
3241 case Builtin::BI__sync_bool_compare_and_swap:
3242 case Builtin::BI__sync_bool_compare_and_swap_1:
3243 case Builtin::BI__sync_bool_compare_and_swap_2:
3244 case Builtin::BI__sync_bool_compare_and_swap_4:
3245 case Builtin::BI__sync_bool_compare_and_swap_8:
3246 case Builtin::BI__sync_bool_compare_and_swap_16:
3249 ResultType = Context.BoolTy;
3252 case Builtin::BI__sync_lock_test_and_set:
3253 case Builtin::BI__sync_lock_test_and_set_1:
3254 case Builtin::BI__sync_lock_test_and_set_2:
3255 case Builtin::BI__sync_lock_test_and_set_4:
3256 case Builtin::BI__sync_lock_test_and_set_8:
3257 case Builtin::BI__sync_lock_test_and_set_16:
3261 case Builtin::BI__sync_lock_release:
3262 case Builtin::BI__sync_lock_release_1:
3263 case Builtin::BI__sync_lock_release_2:
3264 case Builtin::BI__sync_lock_release_4:
3265 case Builtin::BI__sync_lock_release_8:
3266 case Builtin::BI__sync_lock_release_16:
3269 ResultType = Context.VoidTy;
3272 case Builtin::BI__sync_swap:
3273 case Builtin::BI__sync_swap_1:
3274 case Builtin::BI__sync_swap_2:
3275 case Builtin::BI__sync_swap_4:
3276 case Builtin::BI__sync_swap_8:
3277 case Builtin::BI__sync_swap_16:
3282 // Now that we know how many fixed arguments we expect, first check that we
3283 // have at least that many.
3284 if (TheCall->getNumArgs() < 1+NumFixed) {
3285 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3286 << 0 << 1+NumFixed << TheCall->getNumArgs()
3287 << TheCall->getCallee()->getSourceRange();
3291 if (WarnAboutSemanticsChange) {
3292 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3293 << TheCall->getCallee()->getSourceRange();
3296 // Get the decl for the concrete builtin from this, we can tell what the
3297 // concrete integer type we should convert to is.
3298 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3299 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3300 FunctionDecl *NewBuiltinDecl;
3301 if (NewBuiltinID == BuiltinID)
3302 NewBuiltinDecl = FDecl;
3304 // Perform builtin lookup to avoid redeclaring it.
3305 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3306 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3307 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3308 assert(Res.getFoundDecl());
3309 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3310 if (!NewBuiltinDecl)
3314 // The first argument --- the pointer --- has a fixed type; we
3315 // deduce the types of the rest of the arguments accordingly. Walk
3316 // the remaining arguments, converting them to the deduced value type.
3317 for (unsigned i = 0; i != NumFixed; ++i) {
3318 ExprResult Arg = TheCall->getArg(i+1);
3320 // GCC does an implicit conversion to the pointer or integer ValType. This
3321 // can fail in some cases (1i -> int**), check for this error case now.
3322 // Initialize the argument.
3323 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3324 ValType, /*consume*/ false);
3325 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3326 if (Arg.isInvalid())
3329 // Okay, we have something that *can* be converted to the right type. Check
3330 // to see if there is a potentially weird extension going on here. This can
3331 // happen when you do an atomic operation on something like an char* and
3332 // pass in 42. The 42 gets converted to char. This is even more strange
3333 // for things like 45.123 -> char, etc.
3334 // FIXME: Do this check.
3335 TheCall->setArg(i+1, Arg.get());
3338 ASTContext& Context = this->getASTContext();
3340 // Create a new DeclRefExpr to refer to the new decl.
3341 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3343 DRE->getQualifierLoc(),
3346 /*enclosing*/ false,
3348 Context.BuiltinFnTy,
3349 DRE->getValueKind());
3351 // Set the callee in the CallExpr.
3352 // FIXME: This loses syntactic information.
3353 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3354 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3355 CK_BuiltinFnToFnPtr);
3356 TheCall->setCallee(PromotedCall.get());
3358 // Change the result type of the call to match the original value type. This
3359 // is arbitrary, but the codegen for these builtins ins design to handle it
3361 TheCall->setType(ResultType);
3363 return TheCallResult;
3366 /// SemaBuiltinNontemporalOverloaded - We have a call to
3367 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3368 /// overloaded function based on the pointer type of its last argument.
3370 /// This function goes through and does final semantic checking for these
3372 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3373 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3375 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3376 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3377 unsigned BuiltinID = FDecl->getBuiltinID();
3378 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3379 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3380 "Unexpected nontemporal load/store builtin!");
3381 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3382 unsigned numArgs = isStore ? 2 : 1;
3384 // Ensure that we have the proper number of arguments.
3385 if (checkArgCount(*this, TheCall, numArgs))
3388 // Inspect the last argument of the nontemporal builtin. This should always
3389 // be a pointer type, from which we imply the type of the memory access.
3390 // Because it is a pointer type, we don't have to worry about any implicit
3392 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3393 ExprResult PointerArgResult =
3394 DefaultFunctionArrayLvalueConversion(PointerArg);
3396 if (PointerArgResult.isInvalid())
3398 PointerArg = PointerArgResult.get();
3399 TheCall->setArg(numArgs - 1, PointerArg);
3401 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3403 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3404 << PointerArg->getType() << PointerArg->getSourceRange();
3408 QualType ValType = pointerType->getPointeeType();
3410 // Strip any qualifiers off ValType.
3411 ValType = ValType.getUnqualifiedType();
3412 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3413 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3414 !ValType->isVectorType()) {
3415 Diag(DRE->getLocStart(),
3416 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3417 << PointerArg->getType() << PointerArg->getSourceRange();
3422 TheCall->setType(ValType);
3423 return TheCallResult;
3426 ExprResult ValArg = TheCall->getArg(0);
3427 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3428 Context, ValType, /*consume*/ false);
3429 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3430 if (ValArg.isInvalid())
3433 TheCall->setArg(0, ValArg.get());
3434 TheCall->setType(Context.VoidTy);
3435 return TheCallResult;
3438 /// CheckObjCString - Checks that the argument to the builtin
3439 /// CFString constructor is correct
3440 /// Note: It might also make sense to do the UTF-16 conversion here (would
3441 /// simplify the backend).
3442 bool Sema::CheckObjCString(Expr *Arg) {
3443 Arg = Arg->IgnoreParenCasts();
3444 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3446 if (!Literal || !Literal->isAscii()) {
3447 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3448 << Arg->getSourceRange();
3452 if (Literal->containsNonAsciiOrNull()) {
3453 StringRef String = Literal->getString();
3454 unsigned NumBytes = String.size();
3455 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3456 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3457 llvm::UTF16 *ToPtr = &ToBuf[0];
3459 llvm::ConversionResult Result =
3460 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3461 ToPtr + NumBytes, llvm::strictConversion);
3462 // Check for conversion failure.
3463 if (Result != llvm::conversionOK)
3464 Diag(Arg->getLocStart(),
3465 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3470 /// CheckObjCString - Checks that the format string argument to the os_log()
3471 /// and os_trace() functions is correct, and converts it to const char *.
3472 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3473 Arg = Arg->IgnoreParenCasts();
3474 auto *Literal = dyn_cast<StringLiteral>(Arg);
3476 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3477 Literal = ObjcLiteral->getString();
3481 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3483 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3484 << Arg->getSourceRange());
3487 ExprResult Result(Literal);
3488 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3489 InitializedEntity Entity =
3490 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3491 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3495 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3496 /// for validity. Emit an error and return true on failure; return false
3498 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3499 Expr *Fn = TheCall->getCallee();
3500 if (TheCall->getNumArgs() > 2) {
3501 Diag(TheCall->getArg(2)->getLocStart(),
3502 diag::err_typecheck_call_too_many_args)
3503 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3504 << Fn->getSourceRange()
3505 << SourceRange(TheCall->getArg(2)->getLocStart(),
3506 (*(TheCall->arg_end()-1))->getLocEnd());
3510 if (TheCall->getNumArgs() < 2) {
3511 return Diag(TheCall->getLocEnd(),
3512 diag::err_typecheck_call_too_few_args_at_least)
3513 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3516 // Type-check the first argument normally.
3517 if (checkBuiltinArgument(*this, TheCall, 0))
3520 // Determine whether the current function is variadic or not.
3521 BlockScopeInfo *CurBlock = getCurBlock();
3524 isVariadic = CurBlock->TheDecl->isVariadic();
3525 else if (FunctionDecl *FD = getCurFunctionDecl())
3526 isVariadic = FD->isVariadic();
3528 isVariadic = getCurMethodDecl()->isVariadic();
3531 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3535 // Verify that the second argument to the builtin is the last argument of the
3536 // current function or method.
3537 bool SecondArgIsLastNamedArgument = false;
3538 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3540 // These are valid if SecondArgIsLastNamedArgument is false after the next
3543 SourceLocation ParamLoc;
3544 bool IsCRegister = false;
3546 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3547 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3548 // FIXME: This isn't correct for methods (results in bogus warning).
3549 // Get the last formal in the current function.
3550 const ParmVarDecl *LastArg;
3552 LastArg = CurBlock->TheDecl->parameters().back();
3553 else if (FunctionDecl *FD = getCurFunctionDecl())
3554 LastArg = FD->parameters().back();
3556 LastArg = getCurMethodDecl()->parameters().back();
3557 SecondArgIsLastNamedArgument = PV == LastArg;
3559 Type = PV->getType();
3560 ParamLoc = PV->getLocation();
3562 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3566 if (!SecondArgIsLastNamedArgument)
3567 Diag(TheCall->getArg(1)->getLocStart(),
3568 diag::warn_second_arg_of_va_start_not_last_named_param);
3569 else if (IsCRegister || Type->isReferenceType() ||
3570 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3571 // Promotable integers are UB, but enumerations need a bit of
3572 // extra checking to see what their promotable type actually is.
3573 if (!Type->isPromotableIntegerType())
3575 if (!Type->isEnumeralType())
3577 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3579 Context.typesAreCompatible(ED->getPromotionType(), Type));
3581 unsigned Reason = 0;
3582 if (Type->isReferenceType()) Reason = 1;
3583 else if (IsCRegister) Reason = 2;
3584 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3585 Diag(ParamLoc, diag::note_parameter_type) << Type;
3588 TheCall->setType(Context.VoidTy);
3592 /// Check the arguments to '__builtin_va_start' for validity, and that
3593 /// it was called from a function of the native ABI.
3594 /// Emit an error and return true on failure; return false on success.
3595 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3596 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3597 // On x64 Windows, don't allow this in System V ABI functions.
3598 // (Yes, that means there's no corresponding way to support variadic
3599 // System V ABI functions on Windows.)
3600 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3601 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3602 clang::CallingConv CC = CC_C;
3603 if (const FunctionDecl *FD = getCurFunctionDecl())
3604 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3605 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3606 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3607 return Diag(TheCall->getCallee()->getLocStart(),
3608 diag::err_va_start_used_in_wrong_abi_function)
3609 << (OS != llvm::Triple::Win32);
3611 return SemaBuiltinVAStartImpl(TheCall);
3614 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3615 /// it was called from a Win64 ABI function.
3616 /// Emit an error and return true on failure; return false on success.
3617 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3618 // This only makes sense for x86-64.
3619 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3620 Expr *Callee = TheCall->getCallee();
3621 if (TT.getArch() != llvm::Triple::x86_64)
3622 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3623 // Don't allow this in System V ABI functions.
3624 clang::CallingConv CC = CC_C;
3625 if (const FunctionDecl *FD = getCurFunctionDecl())
3626 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3627 if (CC == CC_X86_64SysV ||
3628 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3629 return Diag(Callee->getLocStart(),
3630 diag::err_ms_va_start_used_in_sysv_function);
3631 return SemaBuiltinVAStartImpl(TheCall);
3634 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3635 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3636 // const char *named_addr);
3638 Expr *Func = Call->getCallee();
3640 if (Call->getNumArgs() < 3)
3641 return Diag(Call->getLocEnd(),
3642 diag::err_typecheck_call_too_few_args_at_least)
3643 << 0 /*function call*/ << 3 << Call->getNumArgs();
3645 // Determine whether the current function is variadic or not.
3647 if (BlockScopeInfo *CurBlock = getCurBlock())
3648 IsVariadic = CurBlock->TheDecl->isVariadic();
3649 else if (FunctionDecl *FD = getCurFunctionDecl())
3650 IsVariadic = FD->isVariadic();
3651 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3652 IsVariadic = MD->isVariadic();
3654 llvm_unreachable("unexpected statement type");
3657 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3661 // Type-check the first argument normally.
3662 if (checkBuiltinArgument(*this, Call, 0))
3668 } ArgumentTypes[] = {
3669 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3670 { 2, Context.getSizeType() },
3673 for (const auto &AT : ArgumentTypes) {
3674 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3675 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3677 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3678 << Arg->getType() << AT.Type << 1 /* different class */
3679 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3680 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3686 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3687 /// friends. This is declared to take (...), so we have to check everything.
3688 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3689 if (TheCall->getNumArgs() < 2)
3690 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3691 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3692 if (TheCall->getNumArgs() > 2)
3693 return Diag(TheCall->getArg(2)->getLocStart(),
3694 diag::err_typecheck_call_too_many_args)
3695 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3696 << SourceRange(TheCall->getArg(2)->getLocStart(),
3697 (*(TheCall->arg_end()-1))->getLocEnd());
3699 ExprResult OrigArg0 = TheCall->getArg(0);
3700 ExprResult OrigArg1 = TheCall->getArg(1);
3702 // Do standard promotions between the two arguments, returning their common
3704 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3705 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3708 // Make sure any conversions are pushed back into the call; this is
3709 // type safe since unordered compare builtins are declared as "_Bool
3711 TheCall->setArg(0, OrigArg0.get());
3712 TheCall->setArg(1, OrigArg1.get());
3714 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3717 // If the common type isn't a real floating type, then the arguments were
3718 // invalid for this operation.
3719 if (Res.isNull() || !Res->isRealFloatingType())
3720 return Diag(OrigArg0.get()->getLocStart(),
3721 diag::err_typecheck_call_invalid_ordered_compare)
3722 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3723 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3728 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3729 /// __builtin_isnan and friends. This is declared to take (...), so we have
3730 /// to check everything. We expect the last argument to be a floating point
3732 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3733 if (TheCall->getNumArgs() < NumArgs)
3734 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3735 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3736 if (TheCall->getNumArgs() > NumArgs)
3737 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3738 diag::err_typecheck_call_too_many_args)
3739 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3740 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3741 (*(TheCall->arg_end()-1))->getLocEnd());
3743 Expr *OrigArg = TheCall->getArg(NumArgs-1);
3745 if (OrigArg->isTypeDependent())
3748 // This operation requires a non-_Complex floating-point number.
3749 if (!OrigArg->getType()->isRealFloatingType())
3750 return Diag(OrigArg->getLocStart(),
3751 diag::err_typecheck_call_invalid_unary_fp)
3752 << OrigArg->getType() << OrigArg->getSourceRange();
3754 // If this is an implicit conversion from float -> float or double, remove it.
3755 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3756 // Only remove standard FloatCasts, leaving other casts inplace
3757 if (Cast->getCastKind() == CK_FloatingCast) {
3758 Expr *CastArg = Cast->getSubExpr();
3759 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3760 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3761 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3762 "promotion from float to either float or double is the only expected cast here");
3763 Cast->setSubExpr(nullptr);
3764 TheCall->setArg(NumArgs-1, CastArg);
3772 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3773 // This is declared to take (...), so we have to check everything.
3774 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3775 if (TheCall->getNumArgs() < 2)
3776 return ExprError(Diag(TheCall->getLocEnd(),
3777 diag::err_typecheck_call_too_few_args_at_least)
3778 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3779 << TheCall->getSourceRange());
3781 // Determine which of the following types of shufflevector we're checking:
3782 // 1) unary, vector mask: (lhs, mask)
3783 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3784 QualType resType = TheCall->getArg(0)->getType();
3785 unsigned numElements = 0;
3787 if (!TheCall->getArg(0)->isTypeDependent() &&
3788 !TheCall->getArg(1)->isTypeDependent()) {
3789 QualType LHSType = TheCall->getArg(0)->getType();
3790 QualType RHSType = TheCall->getArg(1)->getType();
3792 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3793 return ExprError(Diag(TheCall->getLocStart(),
3794 diag::err_shufflevector_non_vector)
3795 << SourceRange(TheCall->getArg(0)->getLocStart(),
3796 TheCall->getArg(1)->getLocEnd()));
3798 numElements = LHSType->getAs<VectorType>()->getNumElements();
3799 unsigned numResElements = TheCall->getNumArgs() - 2;
3801 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3802 // with mask. If so, verify that RHS is an integer vector type with the
3803 // same number of elts as lhs.
3804 if (TheCall->getNumArgs() == 2) {
3805 if (!RHSType->hasIntegerRepresentation() ||
3806 RHSType->getAs<VectorType>()->getNumElements() != numElements)
3807 return ExprError(Diag(TheCall->getLocStart(),
3808 diag::err_shufflevector_incompatible_vector)
3809 << SourceRange(TheCall->getArg(1)->getLocStart(),
3810 TheCall->getArg(1)->getLocEnd()));
3811 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3812 return ExprError(Diag(TheCall->getLocStart(),
3813 diag::err_shufflevector_incompatible_vector)
3814 << SourceRange(TheCall->getArg(0)->getLocStart(),
3815 TheCall->getArg(1)->getLocEnd()));
3816 } else if (numElements != numResElements) {
3817 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3818 resType = Context.getVectorType(eltType, numResElements,
3819 VectorType::GenericVector);
3823 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3824 if (TheCall->getArg(i)->isTypeDependent() ||
3825 TheCall->getArg(i)->isValueDependent())
3828 llvm::APSInt Result(32);
3829 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3830 return ExprError(Diag(TheCall->getLocStart(),
3831 diag::err_shufflevector_nonconstant_argument)
3832 << TheCall->getArg(i)->getSourceRange());
3834 // Allow -1 which will be translated to undef in the IR.
3835 if (Result.isSigned() && Result.isAllOnesValue())
3838 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3839 return ExprError(Diag(TheCall->getLocStart(),
3840 diag::err_shufflevector_argument_too_large)
3841 << TheCall->getArg(i)->getSourceRange());
3844 SmallVector<Expr*, 32> exprs;
3846 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3847 exprs.push_back(TheCall->getArg(i));
3848 TheCall->setArg(i, nullptr);
3851 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3852 TheCall->getCallee()->getLocStart(),
3853 TheCall->getRParenLoc());
3856 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3857 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3858 SourceLocation BuiltinLoc,
3859 SourceLocation RParenLoc) {
3860 ExprValueKind VK = VK_RValue;
3861 ExprObjectKind OK = OK_Ordinary;
3862 QualType DstTy = TInfo->getType();
3863 QualType SrcTy = E->getType();
3865 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3866 return ExprError(Diag(BuiltinLoc,
3867 diag::err_convertvector_non_vector)
3868 << E->getSourceRange());
3869 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3870 return ExprError(Diag(BuiltinLoc,
3871 diag::err_convertvector_non_vector_type));
3873 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3874 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3875 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3876 if (SrcElts != DstElts)
3877 return ExprError(Diag(BuiltinLoc,
3878 diag::err_convertvector_incompatible_vector)
3879 << E->getSourceRange());
3882 return new (Context)
3883 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3886 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3887 // This is declared to take (const void*, ...) and can take two
3888 // optional constant int args.
3889 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3890 unsigned NumArgs = TheCall->getNumArgs();
3893 return Diag(TheCall->getLocEnd(),
3894 diag::err_typecheck_call_too_many_args_at_most)
3895 << 0 /*function call*/ << 3 << NumArgs
3896 << TheCall->getSourceRange();
3898 // Argument 0 is checked for us and the remaining arguments must be
3899 // constant integers.
3900 for (unsigned i = 1; i != NumArgs; ++i)
3901 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3907 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3908 // __assume does not evaluate its arguments, and should warn if its argument
3909 // has side effects.
3910 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3911 Expr *Arg = TheCall->getArg(0);
3912 if (Arg->isInstantiationDependent()) return false;
3914 if (Arg->HasSideEffects(Context))
3915 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3916 << Arg->getSourceRange()
3917 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3922 /// Handle __builtin_alloca_with_align. This is declared
3923 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3925 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3926 // The alignment must be a constant integer.
3927 Expr *Arg = TheCall->getArg(1);
3929 // We can't check the value of a dependent argument.
3930 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3931 if (const auto *UE =
3932 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3933 if (UE->getKind() == UETT_AlignOf)
3934 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3935 << Arg->getSourceRange();
3937 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3939 if (!Result.isPowerOf2())
3940 return Diag(TheCall->getLocStart(),
3941 diag::err_alignment_not_power_of_two)
3942 << Arg->getSourceRange();
3944 if (Result < Context.getCharWidth())
3945 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3946 << (unsigned)Context.getCharWidth()
3947 << Arg->getSourceRange();
3949 if (Result > INT32_MAX)
3950 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3952 << Arg->getSourceRange();
3958 /// Handle __builtin_assume_aligned. This is declared
3959 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3960 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3961 unsigned NumArgs = TheCall->getNumArgs();
3964 return Diag(TheCall->getLocEnd(),
3965 diag::err_typecheck_call_too_many_args_at_most)
3966 << 0 /*function call*/ << 3 << NumArgs
3967 << TheCall->getSourceRange();
3969 // The alignment must be a constant integer.
3970 Expr *Arg = TheCall->getArg(1);
3972 // We can't check the value of a dependent argument.
3973 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3974 llvm::APSInt Result;
3975 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3978 if (!Result.isPowerOf2())
3979 return Diag(TheCall->getLocStart(),
3980 diag::err_alignment_not_power_of_two)
3981 << Arg->getSourceRange();
3985 ExprResult Arg(TheCall->getArg(2));
3986 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3987 Context.getSizeType(), false);
3988 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3989 if (Arg.isInvalid()) return true;
3990 TheCall->setArg(2, Arg.get());
3996 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
3997 unsigned BuiltinID =
3998 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
3999 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4001 unsigned NumArgs = TheCall->getNumArgs();
4002 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4003 if (NumArgs < NumRequiredArgs) {
4004 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4005 << 0 /* function call */ << NumRequiredArgs << NumArgs
4006 << TheCall->getSourceRange();
4008 if (NumArgs >= NumRequiredArgs + 0x100) {
4009 return Diag(TheCall->getLocEnd(),
4010 diag::err_typecheck_call_too_many_args_at_most)
4011 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4012 << TheCall->getSourceRange();
4016 // For formatting call, check buffer arg.
4018 ExprResult Arg(TheCall->getArg(i));
4019 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4020 Context, Context.VoidPtrTy, false);
4021 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4022 if (Arg.isInvalid())
4024 TheCall->setArg(i, Arg.get());
4028 // Check string literal arg.
4029 unsigned FormatIdx = i;
4031 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4032 if (Arg.isInvalid())
4034 TheCall->setArg(i, Arg.get());
4038 // Make sure variadic args are scalar.
4039 unsigned FirstDataArg = i;
4040 while (i < NumArgs) {
4041 ExprResult Arg = DefaultVariadicArgumentPromotion(
4042 TheCall->getArg(i), VariadicFunction, nullptr);
4043 if (Arg.isInvalid())
4045 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4046 if (ArgSize.getQuantity() >= 0x100) {
4047 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4048 << i << (int)ArgSize.getQuantity() << 0xff
4049 << TheCall->getSourceRange();
4051 TheCall->setArg(i, Arg.get());
4055 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4056 // call to avoid duplicate diagnostics.
4058 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4059 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4060 bool Success = CheckFormatArguments(
4061 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4062 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4069 TheCall->setType(Context.getSizeType());
4071 TheCall->setType(Context.VoidPtrTy);
4076 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4077 /// TheCall is a constant expression.
4078 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4079 llvm::APSInt &Result) {
4080 Expr *Arg = TheCall->getArg(ArgNum);
4081 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4082 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4084 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4086 if (!Arg->isIntegerConstantExpr(Result, Context))
4087 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4088 << FDecl->getDeclName() << Arg->getSourceRange();
4093 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4094 /// TheCall is a constant expression in the range [Low, High].
4095 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4096 int Low, int High) {
4097 llvm::APSInt Result;
4099 // We can't check the value of a dependent argument.
4100 Expr *Arg = TheCall->getArg(ArgNum);
4101 if (Arg->isTypeDependent() || Arg->isValueDependent())
4104 // Check constant-ness first.
4105 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4108 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4109 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4110 << Low << High << Arg->getSourceRange();
4115 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4116 /// TheCall is a constant expression is a multiple of Num..
4117 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4119 llvm::APSInt Result;
4121 // We can't check the value of a dependent argument.
4122 Expr *Arg = TheCall->getArg(ArgNum);
4123 if (Arg->isTypeDependent() || Arg->isValueDependent())
4126 // Check constant-ness first.
4127 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4130 if (Result.getSExtValue() % Num != 0)
4131 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4132 << Num << Arg->getSourceRange();
4137 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4138 /// TheCall is an ARM/AArch64 special register string literal.
4139 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4140 int ArgNum, unsigned ExpectedFieldNum,
4142 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4143 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4144 BuiltinID == ARM::BI__builtin_arm_rsr ||
4145 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4146 BuiltinID == ARM::BI__builtin_arm_wsr ||
4147 BuiltinID == ARM::BI__builtin_arm_wsrp;
4148 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4149 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4150 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4151 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4152 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4153 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4154 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4156 // We can't check the value of a dependent argument.
4157 Expr *Arg = TheCall->getArg(ArgNum);
4158 if (Arg->isTypeDependent() || Arg->isValueDependent())
4161 // Check if the argument is a string literal.
4162 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4163 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4164 << Arg->getSourceRange();
4166 // Check the type of special register given.
4167 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4168 SmallVector<StringRef, 6> Fields;
4169 Reg.split(Fields, ":");
4171 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4172 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4173 << Arg->getSourceRange();
4175 // If the string is the name of a register then we cannot check that it is
4176 // valid here but if the string is of one the forms described in ACLE then we
4177 // can check that the supplied fields are integers and within the valid
4179 if (Fields.size() > 1) {
4180 bool FiveFields = Fields.size() == 5;
4182 bool ValidString = true;
4184 ValidString &= Fields[0].startswith_lower("cp") ||
4185 Fields[0].startswith_lower("p");
4188 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4190 ValidString &= Fields[2].startswith_lower("c");
4192 Fields[2] = Fields[2].drop_front(1);
4195 ValidString &= Fields[3].startswith_lower("c");
4197 Fields[3] = Fields[3].drop_front(1);
4201 SmallVector<int, 5> Ranges;
4203 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4205 Ranges.append({15, 7, 15});
4207 for (unsigned i=0; i<Fields.size(); ++i) {
4209 ValidString &= !Fields[i].getAsInteger(10, IntField);
4210 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4214 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4215 << Arg->getSourceRange();
4217 } else if (IsAArch64Builtin && Fields.size() == 1) {
4218 // If the register name is one of those that appear in the condition below
4219 // and the special register builtin being used is one of the write builtins,
4220 // then we require that the argument provided for writing to the register
4221 // is an integer constant expression. This is because it will be lowered to
4222 // an MSR (immediate) instruction, so we need to know the immediate at
4224 if (TheCall->getNumArgs() != 2)
4227 std::string RegLower = Reg.lower();
4228 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4229 RegLower != "pan" && RegLower != "uao")
4232 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4238 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4239 /// This checks that the target supports __builtin_longjmp and
4240 /// that val is a constant 1.
4241 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4242 if (!Context.getTargetInfo().hasSjLjLowering())
4243 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4244 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4246 Expr *Arg = TheCall->getArg(1);
4247 llvm::APSInt Result;
4249 // TODO: This is less than ideal. Overload this to take a value.
4250 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4254 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4255 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4260 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4261 /// This checks that the target supports __builtin_setjmp.
4262 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4263 if (!Context.getTargetInfo().hasSjLjLowering())
4264 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4265 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4270 class UncoveredArgHandler {
4271 enum { Unknown = -1, AllCovered = -2 };
4272 signed FirstUncoveredArg;
4273 SmallVector<const Expr *, 4> DiagnosticExprs;
4276 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4278 bool hasUncoveredArg() const {
4279 return (FirstUncoveredArg >= 0);
4282 unsigned getUncoveredArg() const {
4283 assert(hasUncoveredArg() && "no uncovered argument");
4284 return FirstUncoveredArg;
4287 void setAllCovered() {
4288 // A string has been found with all arguments covered, so clear out
4290 DiagnosticExprs.clear();
4291 FirstUncoveredArg = AllCovered;
4294 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4295 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4297 // Don't update if a previous string covers all arguments.
4298 if (FirstUncoveredArg == AllCovered)
4301 // UncoveredArgHandler tracks the highest uncovered argument index
4302 // and with it all the strings that match this index.
4303 if (NewFirstUncoveredArg == FirstUncoveredArg)
4304 DiagnosticExprs.push_back(StrExpr);
4305 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4306 DiagnosticExprs.clear();
4307 DiagnosticExprs.push_back(StrExpr);
4308 FirstUncoveredArg = NewFirstUncoveredArg;
4312 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4315 enum StringLiteralCheckType {
4317 SLCT_UncheckedLiteral,
4320 } // end anonymous namespace
4322 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4323 BinaryOperatorKind BinOpKind,
4324 bool AddendIsRight) {
4325 unsigned BitWidth = Offset.getBitWidth();
4326 unsigned AddendBitWidth = Addend.getBitWidth();
4327 // There might be negative interim results.
4328 if (Addend.isUnsigned()) {
4329 Addend = Addend.zext(++AddendBitWidth);
4330 Addend.setIsSigned(true);
4332 // Adjust the bit width of the APSInts.
4333 if (AddendBitWidth > BitWidth) {
4334 Offset = Offset.sext(AddendBitWidth);
4335 BitWidth = AddendBitWidth;
4336 } else if (BitWidth > AddendBitWidth) {
4337 Addend = Addend.sext(BitWidth);
4341 llvm::APSInt ResOffset = Offset;
4342 if (BinOpKind == BO_Add)
4343 ResOffset = Offset.sadd_ov(Addend, Ov);
4345 assert(AddendIsRight && BinOpKind == BO_Sub &&
4346 "operator must be add or sub with addend on the right");
4347 ResOffset = Offset.ssub_ov(Addend, Ov);
4350 // We add an offset to a pointer here so we should support an offset as big as
4353 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4354 Offset = Offset.sext(2 * BitWidth);
4355 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4363 // This is a wrapper class around StringLiteral to support offsetted string
4364 // literals as format strings. It takes the offset into account when returning
4365 // the string and its length or the source locations to display notes correctly.
4366 class FormatStringLiteral {
4367 const StringLiteral *FExpr;
4371 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4372 : FExpr(fexpr), Offset(Offset) {}
4374 StringRef getString() const {
4375 return FExpr->getString().drop_front(Offset);
4378 unsigned getByteLength() const {
4379 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4381 unsigned getLength() const { return FExpr->getLength() - Offset; }
4382 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4384 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4386 QualType getType() const { return FExpr->getType(); }
4388 bool isAscii() const { return FExpr->isAscii(); }
4389 bool isWide() const { return FExpr->isWide(); }
4390 bool isUTF8() const { return FExpr->isUTF8(); }
4391 bool isUTF16() const { return FExpr->isUTF16(); }
4392 bool isUTF32() const { return FExpr->isUTF32(); }
4393 bool isPascal() const { return FExpr->isPascal(); }
4395 SourceLocation getLocationOfByte(
4396 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4397 const TargetInfo &Target, unsigned *StartToken = nullptr,
4398 unsigned *StartTokenByteOffset = nullptr) const {
4399 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4400 StartToken, StartTokenByteOffset);
4403 SourceLocation getLocStart() const LLVM_READONLY {
4404 return FExpr->getLocStart().getLocWithOffset(Offset);
4406 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4408 } // end anonymous namespace
4410 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4411 const Expr *OrigFormatExpr,
4412 ArrayRef<const Expr *> Args,
4413 bool HasVAListArg, unsigned format_idx,
4414 unsigned firstDataArg,
4415 Sema::FormatStringType Type,
4416 bool inFunctionCall,
4417 Sema::VariadicCallType CallType,
4418 llvm::SmallBitVector &CheckedVarArgs,
4419 UncoveredArgHandler &UncoveredArg);
4421 // Determine if an expression is a string literal or constant string.
4422 // If this function returns false on the arguments to a function expecting a
4423 // format string, we will usually need to emit a warning.
4424 // True string literals are then checked by CheckFormatString.
4425 static StringLiteralCheckType
4426 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4427 bool HasVAListArg, unsigned format_idx,
4428 unsigned firstDataArg, Sema::FormatStringType Type,
4429 Sema::VariadicCallType CallType, bool InFunctionCall,
4430 llvm::SmallBitVector &CheckedVarArgs,
4431 UncoveredArgHandler &UncoveredArg,
4432 llvm::APSInt Offset) {
4434 assert(Offset.isSigned() && "invalid offset");
4436 if (E->isTypeDependent() || E->isValueDependent())
4437 return SLCT_NotALiteral;
4439 E = E->IgnoreParenCasts();
4441 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4442 // Technically -Wformat-nonliteral does not warn about this case.
4443 // The behavior of printf and friends in this case is implementation
4444 // dependent. Ideally if the format string cannot be null then
4445 // it should have a 'nonnull' attribute in the function prototype.
4446 return SLCT_UncheckedLiteral;
4448 switch (E->getStmtClass()) {
4449 case Stmt::BinaryConditionalOperatorClass:
4450 case Stmt::ConditionalOperatorClass: {
4451 // The expression is a literal if both sub-expressions were, and it was
4452 // completely checked only if both sub-expressions were checked.
4453 const AbstractConditionalOperator *C =
4454 cast<AbstractConditionalOperator>(E);
4456 // Determine whether it is necessary to check both sub-expressions, for
4457 // example, because the condition expression is a constant that can be
4458 // evaluated at compile time.
4459 bool CheckLeft = true, CheckRight = true;
4462 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4469 // We need to maintain the offsets for the right and the left hand side
4470 // separately to check if every possible indexed expression is a valid
4471 // string literal. They might have different offsets for different string
4472 // literals in the end.
4473 StringLiteralCheckType Left;
4475 Left = SLCT_UncheckedLiteral;
4477 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4478 HasVAListArg, format_idx, firstDataArg,
4479 Type, CallType, InFunctionCall,
4480 CheckedVarArgs, UncoveredArg, Offset);
4481 if (Left == SLCT_NotALiteral || !CheckRight) {
4486 StringLiteralCheckType Right =
4487 checkFormatStringExpr(S, C->getFalseExpr(), Args,
4488 HasVAListArg, format_idx, firstDataArg,
4489 Type, CallType, InFunctionCall, CheckedVarArgs,
4490 UncoveredArg, Offset);
4492 return (CheckLeft && Left < Right) ? Left : Right;
4495 case Stmt::ImplicitCastExprClass: {
4496 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4500 case Stmt::OpaqueValueExprClass:
4501 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4505 return SLCT_NotALiteral;
4507 case Stmt::PredefinedExprClass:
4508 // While __func__, etc., are technically not string literals, they
4509 // cannot contain format specifiers and thus are not a security
4511 return SLCT_UncheckedLiteral;
4513 case Stmt::DeclRefExprClass: {
4514 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4516 // As an exception, do not flag errors for variables binding to
4517 // const string literals.
4518 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4519 bool isConstant = false;
4520 QualType T = DR->getType();
4522 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4523 isConstant = AT->getElementType().isConstant(S.Context);
4524 } else if (const PointerType *PT = T->getAs<PointerType>()) {
4525 isConstant = T.isConstant(S.Context) &&
4526 PT->getPointeeType().isConstant(S.Context);
4527 } else if (T->isObjCObjectPointerType()) {
4528 // In ObjC, there is usually no "const ObjectPointer" type,
4529 // so don't check if the pointee type is constant.
4530 isConstant = T.isConstant(S.Context);
4534 if (const Expr *Init = VD->getAnyInitializer()) {
4535 // Look through initializers like const char c[] = { "foo" }
4536 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4537 if (InitList->isStringLiteralInit())
4538 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4540 return checkFormatStringExpr(S, Init, Args,
4541 HasVAListArg, format_idx,
4542 firstDataArg, Type, CallType,
4543 /*InFunctionCall*/ false, CheckedVarArgs,
4544 UncoveredArg, Offset);
4548 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4549 // special check to see if the format string is a function parameter
4550 // of the function calling the printf function. If the function
4551 // has an attribute indicating it is a printf-like function, then we
4552 // should suppress warnings concerning non-literals being used in a call
4553 // to a vprintf function. For example:
4556 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4558 // va_start(ap, fmt);
4559 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4563 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4564 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4565 int PVIndex = PV->getFunctionScopeIndex() + 1;
4566 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4567 // adjust for implicit parameter
4568 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4569 if (MD->isInstance())
4571 // We also check if the formats are compatible.
4572 // We can't pass a 'scanf' string to a 'printf' function.
4573 if (PVIndex == PVFormat->getFormatIdx() &&
4574 Type == S.GetFormatStringType(PVFormat))
4575 return SLCT_UncheckedLiteral;
4582 return SLCT_NotALiteral;
4585 case Stmt::CallExprClass:
4586 case Stmt::CXXMemberCallExprClass: {
4587 const CallExpr *CE = cast<CallExpr>(E);
4588 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4589 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4590 unsigned ArgIndex = FA->getFormatIdx();
4591 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4592 if (MD->isInstance())
4594 const Expr *Arg = CE->getArg(ArgIndex - 1);
4596 return checkFormatStringExpr(S, Arg, Args,
4597 HasVAListArg, format_idx, firstDataArg,
4598 Type, CallType, InFunctionCall,
4599 CheckedVarArgs, UncoveredArg, Offset);
4600 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4601 unsigned BuiltinID = FD->getBuiltinID();
4602 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4603 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4604 const Expr *Arg = CE->getArg(0);
4605 return checkFormatStringExpr(S, Arg, Args,
4606 HasVAListArg, format_idx,
4607 firstDataArg, Type, CallType,
4608 InFunctionCall, CheckedVarArgs,
4609 UncoveredArg, Offset);
4614 return SLCT_NotALiteral;
4616 case Stmt::ObjCMessageExprClass: {
4617 const auto *ME = cast<ObjCMessageExpr>(E);
4618 if (const auto *ND = ME->getMethodDecl()) {
4619 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4620 unsigned ArgIndex = FA->getFormatIdx();
4621 const Expr *Arg = ME->getArg(ArgIndex - 1);
4622 return checkFormatStringExpr(
4623 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4624 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4628 return SLCT_NotALiteral;
4630 case Stmt::ObjCStringLiteralClass:
4631 case Stmt::StringLiteralClass: {
4632 const StringLiteral *StrE = nullptr;
4634 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4635 StrE = ObjCFExpr->getString();
4637 StrE = cast<StringLiteral>(E);
4640 if (Offset.isNegative() || Offset > StrE->getLength()) {
4641 // TODO: It would be better to have an explicit warning for out of
4643 return SLCT_NotALiteral;
4645 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4646 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4647 firstDataArg, Type, InFunctionCall, CallType,
4648 CheckedVarArgs, UncoveredArg);
4649 return SLCT_CheckedLiteral;
4652 return SLCT_NotALiteral;
4654 case Stmt::BinaryOperatorClass: {
4655 llvm::APSInt LResult;
4656 llvm::APSInt RResult;
4658 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4660 // A string literal + an int offset is still a string literal.
4661 if (BinOp->isAdditiveOp()) {
4662 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4663 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4665 if (LIsInt != RIsInt) {
4666 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4669 if (BinOpKind == BO_Add) {
4670 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4671 E = BinOp->getRHS();
4675 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4676 E = BinOp->getLHS();
4682 return SLCT_NotALiteral;
4684 case Stmt::UnaryOperatorClass: {
4685 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4686 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4687 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4688 llvm::APSInt IndexResult;
4689 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4690 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4696 return SLCT_NotALiteral;
4700 return SLCT_NotALiteral;
4704 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4705 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4706 .Case("scanf", FST_Scanf)
4707 .Cases("printf", "printf0", FST_Printf)
4708 .Cases("NSString", "CFString", FST_NSString)
4709 .Case("strftime", FST_Strftime)
4710 .Case("strfmon", FST_Strfmon)
4711 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4712 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4713 .Case("os_trace", FST_OSLog)
4714 .Case("os_log", FST_OSLog)
4715 .Default(FST_Unknown);
4718 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4719 /// functions) for correct use of format strings.
4720 /// Returns true if a format string has been fully checked.
4721 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4722 ArrayRef<const Expr *> Args,
4724 VariadicCallType CallType,
4725 SourceLocation Loc, SourceRange Range,
4726 llvm::SmallBitVector &CheckedVarArgs) {
4727 FormatStringInfo FSI;
4728 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4729 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4730 FSI.FirstDataArg, GetFormatStringType(Format),
4731 CallType, Loc, Range, CheckedVarArgs);
4735 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4736 bool HasVAListArg, unsigned format_idx,
4737 unsigned firstDataArg, FormatStringType Type,
4738 VariadicCallType CallType,
4739 SourceLocation Loc, SourceRange Range,
4740 llvm::SmallBitVector &CheckedVarArgs) {
4741 // CHECK: printf/scanf-like function is called with no format string.
4742 if (format_idx >= Args.size()) {
4743 Diag(Loc, diag::warn_missing_format_string) << Range;
4747 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4749 // CHECK: format string is not a string literal.
4751 // Dynamically generated format strings are difficult to
4752 // automatically vet at compile time. Requiring that format strings
4753 // are string literals: (1) permits the checking of format strings by
4754 // the compiler and thereby (2) can practically remove the source of
4755 // many format string exploits.
4757 // Format string can be either ObjC string (e.g. @"%d") or
4758 // C string (e.g. "%d")
4759 // ObjC string uses the same format specifiers as C string, so we can use
4760 // the same format string checking logic for both ObjC and C strings.
4761 UncoveredArgHandler UncoveredArg;
4762 StringLiteralCheckType CT =
4763 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4764 format_idx, firstDataArg, Type, CallType,
4765 /*IsFunctionCall*/ true, CheckedVarArgs,
4767 /*no string offset*/ llvm::APSInt(64, false) = 0);
4769 // Generate a diagnostic where an uncovered argument is detected.
4770 if (UncoveredArg.hasUncoveredArg()) {
4771 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4772 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4773 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4776 if (CT != SLCT_NotALiteral)
4777 // Literal format string found, check done!
4778 return CT == SLCT_CheckedLiteral;
4780 // Strftime is particular as it always uses a single 'time' argument,
4781 // so it is safe to pass a non-literal string.
4782 if (Type == FST_Strftime)
4785 // Do not emit diag when the string param is a macro expansion and the
4786 // format is either NSString or CFString. This is a hack to prevent
4787 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4788 // which are usually used in place of NS and CF string literals.
4789 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4790 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4793 // If there are no arguments specified, warn with -Wformat-security, otherwise
4794 // warn only with -Wformat-nonliteral.
4795 if (Args.size() == firstDataArg) {
4796 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4797 << OrigFormatExpr->getSourceRange();
4802 case FST_FreeBSDKPrintf:
4804 Diag(FormatLoc, diag::note_format_security_fixit)
4805 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4808 Diag(FormatLoc, diag::note_format_security_fixit)
4809 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4813 Diag(FormatLoc, diag::warn_format_nonliteral)
4814 << OrigFormatExpr->getSourceRange();
4820 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4823 const FormatStringLiteral *FExpr;
4824 const Expr *OrigFormatExpr;
4825 const Sema::FormatStringType FSType;
4826 const unsigned FirstDataArg;
4827 const unsigned NumDataArgs;
4828 const char *Beg; // Start of format string.
4829 const bool HasVAListArg;
4830 ArrayRef<const Expr *> Args;
4832 llvm::SmallBitVector CoveredArgs;
4833 bool usesPositionalArgs;
4835 bool inFunctionCall;
4836 Sema::VariadicCallType CallType;
4837 llvm::SmallBitVector &CheckedVarArgs;
4838 UncoveredArgHandler &UncoveredArg;
4841 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
4842 const Expr *origFormatExpr,
4843 const Sema::FormatStringType type, unsigned firstDataArg,
4844 unsigned numDataArgs, const char *beg, bool hasVAListArg,
4845 ArrayRef<const Expr *> Args, unsigned formatIdx,
4846 bool inFunctionCall, Sema::VariadicCallType callType,
4847 llvm::SmallBitVector &CheckedVarArgs,
4848 UncoveredArgHandler &UncoveredArg)
4849 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4850 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4851 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4852 usesPositionalArgs(false), atFirstArg(true),
4853 inFunctionCall(inFunctionCall), CallType(callType),
4854 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4855 CoveredArgs.resize(numDataArgs);
4856 CoveredArgs.reset();
4859 void DoneProcessing();
4861 void HandleIncompleteSpecifier(const char *startSpecifier,
4862 unsigned specifierLen) override;
4864 void HandleInvalidLengthModifier(
4865 const analyze_format_string::FormatSpecifier &FS,
4866 const analyze_format_string::ConversionSpecifier &CS,
4867 const char *startSpecifier, unsigned specifierLen,
4870 void HandleNonStandardLengthModifier(
4871 const analyze_format_string::FormatSpecifier &FS,
4872 const char *startSpecifier, unsigned specifierLen);
4874 void HandleNonStandardConversionSpecifier(
4875 const analyze_format_string::ConversionSpecifier &CS,
4876 const char *startSpecifier, unsigned specifierLen);
4878 void HandlePosition(const char *startPos, unsigned posLen) override;
4880 void HandleInvalidPosition(const char *startSpecifier,
4881 unsigned specifierLen,
4882 analyze_format_string::PositionContext p) override;
4884 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
4886 void HandleNullChar(const char *nullCharacter) override;
4888 template <typename Range>
4890 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4891 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4892 bool IsStringLocation, Range StringRange,
4893 ArrayRef<FixItHint> Fixit = None);
4896 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4897 const char *startSpec,
4898 unsigned specifierLen,
4899 const char *csStart, unsigned csLen);
4901 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4902 const char *startSpec,
4903 unsigned specifierLen);
4905 SourceRange getFormatStringRange();
4906 CharSourceRange getSpecifierRange(const char *startSpecifier,
4907 unsigned specifierLen);
4908 SourceLocation getLocationOfByte(const char *x);
4910 const Expr *getDataArg(unsigned i) const;
4912 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4913 const analyze_format_string::ConversionSpecifier &CS,
4914 const char *startSpecifier, unsigned specifierLen,
4917 template <typename Range>
4918 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4919 bool IsStringLocation, Range StringRange,
4920 ArrayRef<FixItHint> Fixit = None);
4922 } // end anonymous namespace
4924 SourceRange CheckFormatHandler::getFormatStringRange() {
4925 return OrigFormatExpr->getSourceRange();
4928 CharSourceRange CheckFormatHandler::
4929 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4930 SourceLocation Start = getLocationOfByte(startSpecifier);
4931 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4933 // Advance the end SourceLocation by one due to half-open ranges.
4934 End = End.getLocWithOffset(1);
4936 return CharSourceRange::getCharRange(Start, End);
4939 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4940 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4941 S.getLangOpts(), S.Context.getTargetInfo());
4944 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4945 unsigned specifierLen){
4946 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4947 getLocationOfByte(startSpecifier),
4948 /*IsStringLocation*/true,
4949 getSpecifierRange(startSpecifier, specifierLen));
4952 void CheckFormatHandler::HandleInvalidLengthModifier(
4953 const analyze_format_string::FormatSpecifier &FS,
4954 const analyze_format_string::ConversionSpecifier &CS,
4955 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4956 using namespace analyze_format_string;
4958 const LengthModifier &LM = FS.getLengthModifier();
4959 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4961 // See if we know how to fix this length modifier.
4962 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4964 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4965 getLocationOfByte(LM.getStart()),
4966 /*IsStringLocation*/true,
4967 getSpecifierRange(startSpecifier, specifierLen));
4969 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4970 << FixedLM->toString()
4971 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4975 if (DiagID == diag::warn_format_nonsensical_length)
4976 Hint = FixItHint::CreateRemoval(LMRange);
4978 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4979 getLocationOfByte(LM.getStart()),
4980 /*IsStringLocation*/true,
4981 getSpecifierRange(startSpecifier, specifierLen),
4986 void CheckFormatHandler::HandleNonStandardLengthModifier(
4987 const analyze_format_string::FormatSpecifier &FS,
4988 const char *startSpecifier, unsigned specifierLen) {
4989 using namespace analyze_format_string;
4991 const LengthModifier &LM = FS.getLengthModifier();
4992 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4994 // See if we know how to fix this length modifier.
4995 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4997 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4998 << LM.toString() << 0,
4999 getLocationOfByte(LM.getStart()),
5000 /*IsStringLocation*/true,
5001 getSpecifierRange(startSpecifier, specifierLen));
5003 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5004 << FixedLM->toString()
5005 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5008 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5009 << LM.toString() << 0,
5010 getLocationOfByte(LM.getStart()),
5011 /*IsStringLocation*/true,
5012 getSpecifierRange(startSpecifier, specifierLen));
5016 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5017 const analyze_format_string::ConversionSpecifier &CS,
5018 const char *startSpecifier, unsigned specifierLen) {
5019 using namespace analyze_format_string;
5021 // See if we know how to fix this conversion specifier.
5022 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5024 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5025 << CS.toString() << /*conversion specifier*/1,
5026 getLocationOfByte(CS.getStart()),
5027 /*IsStringLocation*/true,
5028 getSpecifierRange(startSpecifier, specifierLen));
5030 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5031 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5032 << FixedCS->toString()
5033 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5035 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5036 << CS.toString() << /*conversion specifier*/1,
5037 getLocationOfByte(CS.getStart()),
5038 /*IsStringLocation*/true,
5039 getSpecifierRange(startSpecifier, specifierLen));
5043 void CheckFormatHandler::HandlePosition(const char *startPos,
5045 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5046 getLocationOfByte(startPos),
5047 /*IsStringLocation*/true,
5048 getSpecifierRange(startPos, posLen));
5052 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5053 analyze_format_string::PositionContext p) {
5054 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5056 getLocationOfByte(startPos), /*IsStringLocation*/true,
5057 getSpecifierRange(startPos, posLen));
5060 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5062 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5063 getLocationOfByte(startPos),
5064 /*IsStringLocation*/true,
5065 getSpecifierRange(startPos, posLen));
5068 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5069 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5070 // The presence of a null character is likely an error.
5071 EmitFormatDiagnostic(
5072 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5073 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5074 getFormatStringRange());
5078 // Note that this may return NULL if there was an error parsing or building
5079 // one of the argument expressions.
5080 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5081 return Args[FirstDataArg + i];
5084 void CheckFormatHandler::DoneProcessing() {
5085 // Does the number of data arguments exceed the number of
5086 // format conversions in the format string?
5087 if (!HasVAListArg) {
5088 // Find any arguments that weren't covered.
5090 signed notCoveredArg = CoveredArgs.find_first();
5091 if (notCoveredArg >= 0) {
5092 assert((unsigned)notCoveredArg < NumDataArgs);
5093 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5095 UncoveredArg.setAllCovered();
5100 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5101 const Expr *ArgExpr) {
5102 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5108 SourceLocation Loc = ArgExpr->getLocStart();
5110 if (S.getSourceManager().isInSystemMacro(Loc))
5113 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5114 for (auto E : DiagnosticExprs)
5115 PDiag << E->getSourceRange();
5117 CheckFormatHandler::EmitFormatDiagnostic(
5118 S, IsFunctionCall, DiagnosticExprs[0],
5119 PDiag, Loc, /*IsStringLocation*/false,
5120 DiagnosticExprs[0]->getSourceRange());
5124 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5126 const char *startSpec,
5127 unsigned specifierLen,
5128 const char *csStart,
5130 bool keepGoing = true;
5131 if (argIndex < NumDataArgs) {
5132 // Consider the argument coverered, even though the specifier doesn't
5134 CoveredArgs.set(argIndex);
5137 // If argIndex exceeds the number of data arguments we
5138 // don't issue a warning because that is just a cascade of warnings (and
5139 // they may have intended '%%' anyway). We don't want to continue processing
5140 // the format string after this point, however, as we will like just get
5141 // gibberish when trying to match arguments.
5145 StringRef Specifier(csStart, csLen);
5147 // If the specifier in non-printable, it could be the first byte of a UTF-8
5148 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5150 std::string CodePointStr;
5151 if (!llvm::sys::locale::isPrint(*csStart)) {
5152 llvm::UTF32 CodePoint;
5153 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5154 const llvm::UTF8 *E =
5155 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5156 llvm::ConversionResult Result =
5157 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5159 if (Result != llvm::conversionOK) {
5160 unsigned char FirstChar = *csStart;
5161 CodePoint = (llvm::UTF32)FirstChar;
5164 llvm::raw_string_ostream OS(CodePointStr);
5165 if (CodePoint < 256)
5166 OS << "\\x" << llvm::format("%02x", CodePoint);
5167 else if (CodePoint <= 0xFFFF)
5168 OS << "\\u" << llvm::format("%04x", CodePoint);
5170 OS << "\\U" << llvm::format("%08x", CodePoint);
5172 Specifier = CodePointStr;
5175 EmitFormatDiagnostic(
5176 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5177 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5183 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5184 const char *startSpec,
5185 unsigned specifierLen) {
5186 EmitFormatDiagnostic(
5187 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5188 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5192 CheckFormatHandler::CheckNumArgs(
5193 const analyze_format_string::FormatSpecifier &FS,
5194 const analyze_format_string::ConversionSpecifier &CS,
5195 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5197 if (argIndex >= NumDataArgs) {
5198 PartialDiagnostic PDiag = FS.usesPositionalArg()
5199 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5200 << (argIndex+1) << NumDataArgs)
5201 : S.PDiag(diag::warn_printf_insufficient_data_args);
5202 EmitFormatDiagnostic(
5203 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5204 getSpecifierRange(startSpecifier, specifierLen));
5206 // Since more arguments than conversion tokens are given, by extension
5207 // all arguments are covered, so mark this as so.
5208 UncoveredArg.setAllCovered();
5214 template<typename Range>
5215 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5217 bool IsStringLocation,
5219 ArrayRef<FixItHint> FixIt) {
5220 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5221 Loc, IsStringLocation, StringRange, FixIt);
5224 /// \brief If the format string is not within the funcion call, emit a note
5225 /// so that the function call and string are in diagnostic messages.
5227 /// \param InFunctionCall if true, the format string is within the function
5228 /// call and only one diagnostic message will be produced. Otherwise, an
5229 /// extra note will be emitted pointing to location of the format string.
5231 /// \param ArgumentExpr the expression that is passed as the format string
5232 /// argument in the function call. Used for getting locations when two
5233 /// diagnostics are emitted.
5235 /// \param PDiag the callee should already have provided any strings for the
5236 /// diagnostic message. This function only adds locations and fixits
5239 /// \param Loc primary location for diagnostic. If two diagnostics are
5240 /// required, one will be at Loc and a new SourceLocation will be created for
5243 /// \param IsStringLocation if true, Loc points to the format string should be
5244 /// used for the note. Otherwise, Loc points to the argument list and will
5245 /// be used with PDiag.
5247 /// \param StringRange some or all of the string to highlight. This is
5248 /// templated so it can accept either a CharSourceRange or a SourceRange.
5250 /// \param FixIt optional fix it hint for the format string.
5251 template <typename Range>
5252 void CheckFormatHandler::EmitFormatDiagnostic(
5253 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5254 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5255 Range StringRange, ArrayRef<FixItHint> FixIt) {
5256 if (InFunctionCall) {
5257 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5261 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5262 << ArgumentExpr->getSourceRange();
5264 const Sema::SemaDiagnosticBuilder &Note =
5265 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5266 diag::note_format_string_defined);
5268 Note << StringRange;
5273 //===--- CHECK: Printf format string checking ------------------------------===//
5276 class CheckPrintfHandler : public CheckFormatHandler {
5278 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5279 const Expr *origFormatExpr,
5280 const Sema::FormatStringType type, unsigned firstDataArg,
5281 unsigned numDataArgs, bool isObjC, const char *beg,
5282 bool hasVAListArg, ArrayRef<const Expr *> Args,
5283 unsigned formatIdx, bool inFunctionCall,
5284 Sema::VariadicCallType CallType,
5285 llvm::SmallBitVector &CheckedVarArgs,
5286 UncoveredArgHandler &UncoveredArg)
5287 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5288 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5289 inFunctionCall, CallType, CheckedVarArgs,
5292 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5294 /// Returns true if '%@' specifiers are allowed in the format string.
5295 bool allowsObjCArg() const {
5296 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5297 FSType == Sema::FST_OSTrace;
5300 bool HandleInvalidPrintfConversionSpecifier(
5301 const analyze_printf::PrintfSpecifier &FS,
5302 const char *startSpecifier,
5303 unsigned specifierLen) override;
5305 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5306 const char *startSpecifier,
5307 unsigned specifierLen) override;
5308 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5309 const char *StartSpecifier,
5310 unsigned SpecifierLen,
5313 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5314 const char *startSpecifier, unsigned specifierLen);
5315 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5316 const analyze_printf::OptionalAmount &Amt,
5318 const char *startSpecifier, unsigned specifierLen);
5319 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5320 const analyze_printf::OptionalFlag &flag,
5321 const char *startSpecifier, unsigned specifierLen);
5322 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5323 const analyze_printf::OptionalFlag &ignoredFlag,
5324 const analyze_printf::OptionalFlag &flag,
5325 const char *startSpecifier, unsigned specifierLen);
5326 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5329 void HandleEmptyObjCModifierFlag(const char *startFlag,
5330 unsigned flagLen) override;
5332 void HandleInvalidObjCModifierFlag(const char *startFlag,
5333 unsigned flagLen) override;
5335 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5336 const char *flagsEnd,
5337 const char *conversionPosition)
5340 } // end anonymous namespace
5342 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5343 const analyze_printf::PrintfSpecifier &FS,
5344 const char *startSpecifier,
5345 unsigned specifierLen) {
5346 const analyze_printf::PrintfConversionSpecifier &CS =
5347 FS.getConversionSpecifier();
5349 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5350 getLocationOfByte(CS.getStart()),
5351 startSpecifier, specifierLen,
5352 CS.getStart(), CS.getLength());
5355 bool CheckPrintfHandler::HandleAmount(
5356 const analyze_format_string::OptionalAmount &Amt,
5357 unsigned k, const char *startSpecifier,
5358 unsigned specifierLen) {
5359 if (Amt.hasDataArgument()) {
5360 if (!HasVAListArg) {
5361 unsigned argIndex = Amt.getArgIndex();
5362 if (argIndex >= NumDataArgs) {
5363 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5365 getLocationOfByte(Amt.getStart()),
5366 /*IsStringLocation*/true,
5367 getSpecifierRange(startSpecifier, specifierLen));
5368 // Don't do any more checking. We will just emit
5373 // Type check the data argument. It should be an 'int'.
5374 // Although not in conformance with C99, we also allow the argument to be
5375 // an 'unsigned int' as that is a reasonably safe case. GCC also
5376 // doesn't emit a warning for that case.
5377 CoveredArgs.set(argIndex);
5378 const Expr *Arg = getDataArg(argIndex);
5382 QualType T = Arg->getType();
5384 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5385 assert(AT.isValid());
5387 if (!AT.matchesType(S.Context, T)) {
5388 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5389 << k << AT.getRepresentativeTypeName(S.Context)
5390 << T << Arg->getSourceRange(),
5391 getLocationOfByte(Amt.getStart()),
5392 /*IsStringLocation*/true,
5393 getSpecifierRange(startSpecifier, specifierLen));
5394 // Don't do any more checking. We will just emit
5403 void CheckPrintfHandler::HandleInvalidAmount(
5404 const analyze_printf::PrintfSpecifier &FS,
5405 const analyze_printf::OptionalAmount &Amt,
5407 const char *startSpecifier,
5408 unsigned specifierLen) {
5409 const analyze_printf::PrintfConversionSpecifier &CS =
5410 FS.getConversionSpecifier();
5413 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5414 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5415 Amt.getConstantLength()))
5418 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5419 << type << CS.toString(),
5420 getLocationOfByte(Amt.getStart()),
5421 /*IsStringLocation*/true,
5422 getSpecifierRange(startSpecifier, specifierLen),
5426 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5427 const analyze_printf::OptionalFlag &flag,
5428 const char *startSpecifier,
5429 unsigned specifierLen) {
5430 // Warn about pointless flag with a fixit removal.
5431 const analyze_printf::PrintfConversionSpecifier &CS =
5432 FS.getConversionSpecifier();
5433 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5434 << flag.toString() << CS.toString(),
5435 getLocationOfByte(flag.getPosition()),
5436 /*IsStringLocation*/true,
5437 getSpecifierRange(startSpecifier, specifierLen),
5438 FixItHint::CreateRemoval(
5439 getSpecifierRange(flag.getPosition(), 1)));
5442 void CheckPrintfHandler::HandleIgnoredFlag(
5443 const analyze_printf::PrintfSpecifier &FS,
5444 const analyze_printf::OptionalFlag &ignoredFlag,
5445 const analyze_printf::OptionalFlag &flag,
5446 const char *startSpecifier,
5447 unsigned specifierLen) {
5448 // Warn about ignored flag with a fixit removal.
5449 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5450 << ignoredFlag.toString() << flag.toString(),
5451 getLocationOfByte(ignoredFlag.getPosition()),
5452 /*IsStringLocation*/true,
5453 getSpecifierRange(startSpecifier, specifierLen),
5454 FixItHint::CreateRemoval(
5455 getSpecifierRange(ignoredFlag.getPosition(), 1)));
5458 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5459 // bool IsStringLocation, Range StringRange,
5460 // ArrayRef<FixItHint> Fixit = None);
5462 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5464 // Warn about an empty flag.
5465 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5466 getLocationOfByte(startFlag),
5467 /*IsStringLocation*/true,
5468 getSpecifierRange(startFlag, flagLen));
5471 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5473 // Warn about an invalid flag.
5474 auto Range = getSpecifierRange(startFlag, flagLen);
5475 StringRef flag(startFlag, flagLen);
5476 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5477 getLocationOfByte(startFlag),
5478 /*IsStringLocation*/true,
5479 Range, FixItHint::CreateRemoval(Range));
5482 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5483 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5484 // Warn about using '[...]' without a '@' conversion.
5485 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5486 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5487 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5488 getLocationOfByte(conversionPosition),
5489 /*IsStringLocation*/true,
5490 Range, FixItHint::CreateRemoval(Range));
5493 // Determines if the specified is a C++ class or struct containing
5494 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5496 template<typename MemberKind>
5497 static llvm::SmallPtrSet<MemberKind*, 1>
5498 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5499 const RecordType *RT = Ty->getAs<RecordType>();
5500 llvm::SmallPtrSet<MemberKind*, 1> Results;
5504 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5505 if (!RD || !RD->getDefinition())
5508 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5509 Sema::LookupMemberName);
5510 R.suppressDiagnostics();
5512 // We just need to include all members of the right kind turned up by the
5513 // filter, at this point.
5514 if (S.LookupQualifiedName(R, RT->getDecl()))
5515 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5516 NamedDecl *decl = (*I)->getUnderlyingDecl();
5517 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5523 /// Check if we could call '.c_str()' on an object.
5525 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5526 /// allow the call, or if it would be ambiguous).
5527 bool Sema::hasCStrMethod(const Expr *E) {
5528 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5530 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5531 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5533 if ((*MI)->getMinRequiredArguments() == 0)
5538 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5539 // better diagnostic if so. AT is assumed to be valid.
5540 // Returns true when a c_str() conversion method is found.
5541 bool CheckPrintfHandler::checkForCStrMembers(
5542 const analyze_printf::ArgType &AT, const Expr *E) {
5543 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5546 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5548 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5550 const CXXMethodDecl *Method = *MI;
5551 if (Method->getMinRequiredArguments() == 0 &&
5552 AT.matchesType(S.Context, Method->getReturnType())) {
5553 // FIXME: Suggest parens if the expression needs them.
5554 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5555 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5557 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5566 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5568 const char *startSpecifier,
5569 unsigned specifierLen) {
5570 using namespace analyze_format_string;
5571 using namespace analyze_printf;
5572 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5574 if (FS.consumesDataArgument()) {
5577 usesPositionalArgs = FS.usesPositionalArg();
5579 else if (usesPositionalArgs != FS.usesPositionalArg()) {
5580 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5581 startSpecifier, specifierLen);
5586 // First check if the field width, precision, and conversion specifier
5587 // have matching data arguments.
5588 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5589 startSpecifier, specifierLen)) {
5593 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5594 startSpecifier, specifierLen)) {
5598 if (!CS.consumesDataArgument()) {
5599 // FIXME: Technically specifying a precision or field width here
5600 // makes no sense. Worth issuing a warning at some point.
5604 // Consume the argument.
5605 unsigned argIndex = FS.getArgIndex();
5606 if (argIndex < NumDataArgs) {
5607 // The check to see if the argIndex is valid will come later.
5608 // We set the bit here because we may exit early from this
5609 // function if we encounter some other error.
5610 CoveredArgs.set(argIndex);
5613 // FreeBSD kernel extensions.
5614 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5615 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5616 // We need at least two arguments.
5617 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5620 // Claim the second argument.
5621 CoveredArgs.set(argIndex + 1);
5623 // Type check the first argument (int for %b, pointer for %D)
5624 const Expr *Ex = getDataArg(argIndex);
5625 const analyze_printf::ArgType &AT =
5626 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5627 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5628 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5629 EmitFormatDiagnostic(
5630 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5631 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5632 << false << Ex->getSourceRange(),
5633 Ex->getLocStart(), /*IsStringLocation*/false,
5634 getSpecifierRange(startSpecifier, specifierLen));
5636 // Type check the second argument (char * for both %b and %D)
5637 Ex = getDataArg(argIndex + 1);
5638 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5639 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5640 EmitFormatDiagnostic(
5641 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5642 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5643 << false << Ex->getSourceRange(),
5644 Ex->getLocStart(), /*IsStringLocation*/false,
5645 getSpecifierRange(startSpecifier, specifierLen));
5650 // Check for using an Objective-C specific conversion specifier
5651 // in a non-ObjC literal.
5652 if (!allowsObjCArg() && CS.isObjCArg()) {
5653 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5657 // %P can only be used with os_log.
5658 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5659 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5663 // %n is not allowed with os_log.
5664 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5665 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5666 getLocationOfByte(CS.getStart()),
5667 /*IsStringLocation*/ false,
5668 getSpecifierRange(startSpecifier, specifierLen));
5673 // Only scalars are allowed for os_trace.
5674 if (FSType == Sema::FST_OSTrace &&
5675 (CS.getKind() == ConversionSpecifier::PArg ||
5676 CS.getKind() == ConversionSpecifier::sArg ||
5677 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5678 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5682 // Check for use of public/private annotation outside of os_log().
5683 if (FSType != Sema::FST_OSLog) {
5684 if (FS.isPublic().isSet()) {
5685 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5687 getLocationOfByte(FS.isPublic().getPosition()),
5688 /*IsStringLocation*/ false,
5689 getSpecifierRange(startSpecifier, specifierLen));
5691 if (FS.isPrivate().isSet()) {
5692 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5694 getLocationOfByte(FS.isPrivate().getPosition()),
5695 /*IsStringLocation*/ false,
5696 getSpecifierRange(startSpecifier, specifierLen));
5700 // Check for invalid use of field width
5701 if (!FS.hasValidFieldWidth()) {
5702 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5703 startSpecifier, specifierLen);
5706 // Check for invalid use of precision
5707 if (!FS.hasValidPrecision()) {
5708 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5709 startSpecifier, specifierLen);
5712 // Precision is mandatory for %P specifier.
5713 if (CS.getKind() == ConversionSpecifier::PArg &&
5714 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5715 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5716 getLocationOfByte(startSpecifier),
5717 /*IsStringLocation*/ false,
5718 getSpecifierRange(startSpecifier, specifierLen));
5721 // Check each flag does not conflict with any other component.
5722 if (!FS.hasValidThousandsGroupingPrefix())
5723 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5724 if (!FS.hasValidLeadingZeros())
5725 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5726 if (!FS.hasValidPlusPrefix())
5727 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5728 if (!FS.hasValidSpacePrefix())
5729 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5730 if (!FS.hasValidAlternativeForm())
5731 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5732 if (!FS.hasValidLeftJustified())
5733 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5735 // Check that flags are not ignored by another flag
5736 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5737 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5738 startSpecifier, specifierLen);
5739 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5740 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5741 startSpecifier, specifierLen);
5743 // Check the length modifier is valid with the given conversion specifier.
5744 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5745 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5746 diag::warn_format_nonsensical_length);
5747 else if (!FS.hasStandardLengthModifier())
5748 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5749 else if (!FS.hasStandardLengthConversionCombination())
5750 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5751 diag::warn_format_non_standard_conversion_spec);
5753 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5754 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5756 // The remaining checks depend on the data arguments.
5760 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5763 const Expr *Arg = getDataArg(argIndex);
5767 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5770 static bool requiresParensToAddCast(const Expr *E) {
5771 // FIXME: We should have a general way to reason about operator
5772 // precedence and whether parens are actually needed here.
5773 // Take care of a few common cases where they aren't.
5774 const Expr *Inside = E->IgnoreImpCasts();
5775 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5776 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5778 switch (Inside->getStmtClass()) {
5779 case Stmt::ArraySubscriptExprClass:
5780 case Stmt::CallExprClass:
5781 case Stmt::CharacterLiteralClass:
5782 case Stmt::CXXBoolLiteralExprClass:
5783 case Stmt::DeclRefExprClass:
5784 case Stmt::FloatingLiteralClass:
5785 case Stmt::IntegerLiteralClass:
5786 case Stmt::MemberExprClass:
5787 case Stmt::ObjCArrayLiteralClass:
5788 case Stmt::ObjCBoolLiteralExprClass:
5789 case Stmt::ObjCBoxedExprClass:
5790 case Stmt::ObjCDictionaryLiteralClass:
5791 case Stmt::ObjCEncodeExprClass:
5792 case Stmt::ObjCIvarRefExprClass:
5793 case Stmt::ObjCMessageExprClass:
5794 case Stmt::ObjCPropertyRefExprClass:
5795 case Stmt::ObjCStringLiteralClass:
5796 case Stmt::ObjCSubscriptRefExprClass:
5797 case Stmt::ParenExprClass:
5798 case Stmt::StringLiteralClass:
5799 case Stmt::UnaryOperatorClass:
5806 static std::pair<QualType, StringRef>
5807 shouldNotPrintDirectly(const ASTContext &Context,
5808 QualType IntendedTy,
5810 // Use a 'while' to peel off layers of typedefs.
5811 QualType TyTy = IntendedTy;
5812 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5813 StringRef Name = UserTy->getDecl()->getName();
5814 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5815 .Case("NSInteger", Context.LongTy)
5816 .Case("NSUInteger", Context.UnsignedLongTy)
5817 .Case("SInt32", Context.IntTy)
5818 .Case("UInt32", Context.UnsignedIntTy)
5819 .Default(QualType());
5821 if (!CastTy.isNull())
5822 return std::make_pair(CastTy, Name);
5824 TyTy = UserTy->desugar();
5827 // Strip parens if necessary.
5828 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5829 return shouldNotPrintDirectly(Context,
5830 PE->getSubExpr()->getType(),
5833 // If this is a conditional expression, then its result type is constructed
5834 // via usual arithmetic conversions and thus there might be no necessary
5835 // typedef sugar there. Recurse to operands to check for NSInteger &
5836 // Co. usage condition.
5837 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5838 QualType TrueTy, FalseTy;
5839 StringRef TrueName, FalseName;
5841 std::tie(TrueTy, TrueName) =
5842 shouldNotPrintDirectly(Context,
5843 CO->getTrueExpr()->getType(),
5845 std::tie(FalseTy, FalseName) =
5846 shouldNotPrintDirectly(Context,
5847 CO->getFalseExpr()->getType(),
5848 CO->getFalseExpr());
5850 if (TrueTy == FalseTy)
5851 return std::make_pair(TrueTy, TrueName);
5852 else if (TrueTy.isNull())
5853 return std::make_pair(FalseTy, FalseName);
5854 else if (FalseTy.isNull())
5855 return std::make_pair(TrueTy, TrueName);
5858 return std::make_pair(QualType(), StringRef());
5862 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5863 const char *StartSpecifier,
5864 unsigned SpecifierLen,
5866 using namespace analyze_format_string;
5867 using namespace analyze_printf;
5868 // Now type check the data expression that matches the
5869 // format specifier.
5870 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
5874 QualType ExprTy = E->getType();
5875 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5876 ExprTy = TET->getUnderlyingExpr()->getType();
5879 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5881 if (match == analyze_printf::ArgType::Match) {
5885 // Look through argument promotions for our error message's reported type.
5886 // This includes the integral and floating promotions, but excludes array
5887 // and function pointer decay; seeing that an argument intended to be a
5888 // string has type 'char [6]' is probably more confusing than 'char *'.
5889 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5890 if (ICE->getCastKind() == CK_IntegralCast ||
5891 ICE->getCastKind() == CK_FloatingCast) {
5892 E = ICE->getSubExpr();
5893 ExprTy = E->getType();
5895 // Check if we didn't match because of an implicit cast from a 'char'
5896 // or 'short' to an 'int'. This is done because printf is a varargs
5898 if (ICE->getType() == S.Context.IntTy ||
5899 ICE->getType() == S.Context.UnsignedIntTy) {
5900 // All further checking is done on the subexpression.
5901 if (AT.matchesType(S.Context, ExprTy))
5905 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5906 // Special case for 'a', which has type 'int' in C.
5907 // Note, however, that we do /not/ want to treat multibyte constants like
5908 // 'MooV' as characters! This form is deprecated but still exists.
5909 if (ExprTy == S.Context.IntTy)
5910 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5911 ExprTy = S.Context.CharTy;
5914 // Look through enums to their underlying type.
5915 bool IsEnum = false;
5916 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5917 ExprTy = EnumTy->getDecl()->getIntegerType();
5921 // %C in an Objective-C context prints a unichar, not a wchar_t.
5922 // If the argument is an integer of some kind, believe the %C and suggest
5923 // a cast instead of changing the conversion specifier.
5924 QualType IntendedTy = ExprTy;
5925 if (isObjCContext() &&
5926 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5927 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5928 !ExprTy->isCharType()) {
5929 // 'unichar' is defined as a typedef of unsigned short, but we should
5930 // prefer using the typedef if it is visible.
5931 IntendedTy = S.Context.UnsignedShortTy;
5933 // While we are here, check if the value is an IntegerLiteral that happens
5934 // to be within the valid range.
5935 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5936 const llvm::APInt &V = IL->getValue();
5937 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5941 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5942 Sema::LookupOrdinaryName);
5943 if (S.LookupName(Result, S.getCurScope())) {
5944 NamedDecl *ND = Result.getFoundDecl();
5945 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5946 if (TD->getUnderlyingType() == IntendedTy)
5947 IntendedTy = S.Context.getTypedefType(TD);
5952 // Special-case some of Darwin's platform-independence types by suggesting
5953 // casts to primitive types that are known to be large enough.
5954 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5955 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5957 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5958 if (!CastTy.isNull()) {
5959 IntendedTy = CastTy;
5960 ShouldNotPrintDirectly = true;
5964 // We may be able to offer a FixItHint if it is a supported type.
5965 PrintfSpecifier fixedFS = FS;
5967 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
5970 // Get the fix string from the fixed format specifier
5971 SmallString<16> buf;
5972 llvm::raw_svector_ostream os(buf);
5973 fixedFS.toString(os);
5975 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5977 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5978 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5979 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5980 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5982 // In this case, the specifier is wrong and should be changed to match
5984 EmitFormatDiagnostic(S.PDiag(diag)
5985 << AT.getRepresentativeTypeName(S.Context)
5986 << IntendedTy << IsEnum << E->getSourceRange(),
5988 /*IsStringLocation*/ false, SpecRange,
5989 FixItHint::CreateReplacement(SpecRange, os.str()));
5991 // The canonical type for formatting this value is different from the
5992 // actual type of the expression. (This occurs, for example, with Darwin's
5993 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5994 // should be printed as 'long' for 64-bit compatibility.)
5995 // Rather than emitting a normal format/argument mismatch, we want to
5996 // add a cast to the recommended type (and correct the format string
5998 SmallString<16> CastBuf;
5999 llvm::raw_svector_ostream CastFix(CastBuf);
6001 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6004 SmallVector<FixItHint,4> Hints;
6005 if (!AT.matchesType(S.Context, IntendedTy))
6006 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6008 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6009 // If there's already a cast present, just replace it.
6010 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6011 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6013 } else if (!requiresParensToAddCast(E)) {
6014 // If the expression has high enough precedence,
6015 // just write the C-style cast.
6016 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6019 // Otherwise, add parens around the expression as well as the cast.
6021 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6024 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6025 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6028 if (ShouldNotPrintDirectly) {
6029 // The expression has a type that should not be printed directly.
6030 // We extract the name from the typedef because we don't want to show
6031 // the underlying type in the diagnostic.
6033 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6034 Name = TypedefTy->getDecl()->getName();
6037 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6038 << Name << IntendedTy << IsEnum
6039 << E->getSourceRange(),
6040 E->getLocStart(), /*IsStringLocation=*/false,
6043 // In this case, the expression could be printed using a different
6044 // specifier, but we've decided that the specifier is probably correct
6045 // and we should cast instead. Just use the normal warning message.
6046 EmitFormatDiagnostic(
6047 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6048 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6049 << E->getSourceRange(),
6050 E->getLocStart(), /*IsStringLocation*/false,
6055 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6057 // Since the warning for passing non-POD types to variadic functions
6058 // was deferred until now, we emit a warning for non-POD
6060 switch (S.isValidVarArgType(ExprTy)) {
6061 case Sema::VAK_Valid:
6062 case Sema::VAK_ValidInCXX11: {
6063 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6064 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6065 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6068 EmitFormatDiagnostic(
6069 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6070 << IsEnum << CSR << E->getSourceRange(),
6071 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6074 case Sema::VAK_Undefined:
6075 case Sema::VAK_MSVCUndefined:
6076 EmitFormatDiagnostic(
6077 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6078 << S.getLangOpts().CPlusPlus11
6081 << AT.getRepresentativeTypeName(S.Context)
6083 << E->getSourceRange(),
6084 E->getLocStart(), /*IsStringLocation*/false, CSR);
6085 checkForCStrMembers(AT, E);
6088 case Sema::VAK_Invalid:
6089 if (ExprTy->isObjCObjectType())
6090 EmitFormatDiagnostic(
6091 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6092 << S.getLangOpts().CPlusPlus11
6095 << AT.getRepresentativeTypeName(S.Context)
6097 << E->getSourceRange(),
6098 E->getLocStart(), /*IsStringLocation*/false, CSR);
6100 // FIXME: If this is an initializer list, suggest removing the braces
6101 // or inserting a cast to the target type.
6102 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6103 << isa<InitListExpr>(E) << ExprTy << CallType
6104 << AT.getRepresentativeTypeName(S.Context)
6105 << E->getSourceRange();
6109 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6110 "format string specifier index out of range");
6111 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6117 //===--- CHECK: Scanf format string checking ------------------------------===//
6120 class CheckScanfHandler : public CheckFormatHandler {
6122 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6123 const Expr *origFormatExpr, Sema::FormatStringType type,
6124 unsigned firstDataArg, unsigned numDataArgs,
6125 const char *beg, bool hasVAListArg,
6126 ArrayRef<const Expr *> Args, unsigned formatIdx,
6127 bool inFunctionCall, Sema::VariadicCallType CallType,
6128 llvm::SmallBitVector &CheckedVarArgs,
6129 UncoveredArgHandler &UncoveredArg)
6130 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6131 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6132 inFunctionCall, CallType, CheckedVarArgs,
6135 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6136 const char *startSpecifier,
6137 unsigned specifierLen) override;
6139 bool HandleInvalidScanfConversionSpecifier(
6140 const analyze_scanf::ScanfSpecifier &FS,
6141 const char *startSpecifier,
6142 unsigned specifierLen) override;
6144 void HandleIncompleteScanList(const char *start, const char *end) override;
6146 } // end anonymous namespace
6148 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6150 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6151 getLocationOfByte(end), /*IsStringLocation*/true,
6152 getSpecifierRange(start, end - start));
6155 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6156 const analyze_scanf::ScanfSpecifier &FS,
6157 const char *startSpecifier,
6158 unsigned specifierLen) {
6160 const analyze_scanf::ScanfConversionSpecifier &CS =
6161 FS.getConversionSpecifier();
6163 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6164 getLocationOfByte(CS.getStart()),
6165 startSpecifier, specifierLen,
6166 CS.getStart(), CS.getLength());
6169 bool CheckScanfHandler::HandleScanfSpecifier(
6170 const analyze_scanf::ScanfSpecifier &FS,
6171 const char *startSpecifier,
6172 unsigned specifierLen) {
6173 using namespace analyze_scanf;
6174 using namespace analyze_format_string;
6176 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6178 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6179 // be used to decide if we are using positional arguments consistently.
6180 if (FS.consumesDataArgument()) {
6183 usesPositionalArgs = FS.usesPositionalArg();
6185 else if (usesPositionalArgs != FS.usesPositionalArg()) {
6186 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6187 startSpecifier, specifierLen);
6192 // Check if the field with is non-zero.
6193 const OptionalAmount &Amt = FS.getFieldWidth();
6194 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6195 if (Amt.getConstantAmount() == 0) {
6196 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6197 Amt.getConstantLength());
6198 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6199 getLocationOfByte(Amt.getStart()),
6200 /*IsStringLocation*/true, R,
6201 FixItHint::CreateRemoval(R));
6205 if (!FS.consumesDataArgument()) {
6206 // FIXME: Technically specifying a precision or field width here
6207 // makes no sense. Worth issuing a warning at some point.
6211 // Consume the argument.
6212 unsigned argIndex = FS.getArgIndex();
6213 if (argIndex < NumDataArgs) {
6214 // The check to see if the argIndex is valid will come later.
6215 // We set the bit here because we may exit early from this
6216 // function if we encounter some other error.
6217 CoveredArgs.set(argIndex);
6220 // Check the length modifier is valid with the given conversion specifier.
6221 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6222 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6223 diag::warn_format_nonsensical_length);
6224 else if (!FS.hasStandardLengthModifier())
6225 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6226 else if (!FS.hasStandardLengthConversionCombination())
6227 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6228 diag::warn_format_non_standard_conversion_spec);
6230 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6231 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6233 // The remaining checks depend on the data arguments.
6237 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6240 // Check that the argument type matches the format specifier.
6241 const Expr *Ex = getDataArg(argIndex);
6245 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6247 if (!AT.isValid()) {
6251 analyze_format_string::ArgType::MatchKind match =
6252 AT.matchesType(S.Context, Ex->getType());
6253 if (match == analyze_format_string::ArgType::Match) {
6257 ScanfSpecifier fixedFS = FS;
6258 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6259 S.getLangOpts(), S.Context);
6261 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6262 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6263 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6267 // Get the fix string from the fixed format specifier.
6268 SmallString<128> buf;
6269 llvm::raw_svector_ostream os(buf);
6270 fixedFS.toString(os);
6272 EmitFormatDiagnostic(
6273 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6274 << Ex->getType() << false << Ex->getSourceRange(),
6276 /*IsStringLocation*/ false,
6277 getSpecifierRange(startSpecifier, specifierLen),
6278 FixItHint::CreateReplacement(
6279 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6281 EmitFormatDiagnostic(S.PDiag(diag)
6282 << AT.getRepresentativeTypeName(S.Context)
6283 << Ex->getType() << false << Ex->getSourceRange(),
6285 /*IsStringLocation*/ false,
6286 getSpecifierRange(startSpecifier, specifierLen));
6292 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6293 const Expr *OrigFormatExpr,
6294 ArrayRef<const Expr *> Args,
6295 bool HasVAListArg, unsigned format_idx,
6296 unsigned firstDataArg,
6297 Sema::FormatStringType Type,
6298 bool inFunctionCall,
6299 Sema::VariadicCallType CallType,
6300 llvm::SmallBitVector &CheckedVarArgs,
6301 UncoveredArgHandler &UncoveredArg) {
6302 // CHECK: is the format string a wide literal?
6303 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6304 CheckFormatHandler::EmitFormatDiagnostic(
6305 S, inFunctionCall, Args[format_idx],
6306 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6307 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6311 // Str - The format string. NOTE: this is NOT null-terminated!
6312 StringRef StrRef = FExpr->getString();
6313 const char *Str = StrRef.data();
6314 // Account for cases where the string literal is truncated in a declaration.
6315 const ConstantArrayType *T =
6316 S.Context.getAsConstantArrayType(FExpr->getType());
6317 assert(T && "String literal not of constant array type!");
6318 size_t TypeSize = T->getSize().getZExtValue();
6319 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6320 const unsigned numDataArgs = Args.size() - firstDataArg;
6322 // Emit a warning if the string literal is truncated and does not contain an
6323 // embedded null character.
6324 if (TypeSize <= StrRef.size() &&
6325 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6326 CheckFormatHandler::EmitFormatDiagnostic(
6327 S, inFunctionCall, Args[format_idx],
6328 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6329 FExpr->getLocStart(),
6330 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6334 // CHECK: empty format string?
6335 if (StrLen == 0 && numDataArgs > 0) {
6336 CheckFormatHandler::EmitFormatDiagnostic(
6337 S, inFunctionCall, Args[format_idx],
6338 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6339 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6343 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6344 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6345 Type == Sema::FST_OSTrace) {
6346 CheckPrintfHandler H(
6347 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6348 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6349 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6350 CheckedVarArgs, UncoveredArg);
6352 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6354 S.Context.getTargetInfo(),
6355 Type == Sema::FST_FreeBSDKPrintf))
6357 } else if (Type == Sema::FST_Scanf) {
6358 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6359 numDataArgs, Str, HasVAListArg, Args, format_idx,
6360 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6362 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6364 S.Context.getTargetInfo()))
6366 } // TODO: handle other formats
6369 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6370 // Str - The format string. NOTE: this is NOT null-terminated!
6371 StringRef StrRef = FExpr->getString();
6372 const char *Str = StrRef.data();
6373 // Account for cases where the string literal is truncated in a declaration.
6374 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6375 assert(T && "String literal not of constant array type!");
6376 size_t TypeSize = T->getSize().getZExtValue();
6377 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6378 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6380 Context.getTargetInfo());
6383 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6385 // Returns the related absolute value function that is larger, of 0 if one
6387 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6388 switch (AbsFunction) {
6392 case Builtin::BI__builtin_abs:
6393 return Builtin::BI__builtin_labs;
6394 case Builtin::BI__builtin_labs:
6395 return Builtin::BI__builtin_llabs;
6396 case Builtin::BI__builtin_llabs:
6399 case Builtin::BI__builtin_fabsf:
6400 return Builtin::BI__builtin_fabs;
6401 case Builtin::BI__builtin_fabs:
6402 return Builtin::BI__builtin_fabsl;
6403 case Builtin::BI__builtin_fabsl:
6406 case Builtin::BI__builtin_cabsf:
6407 return Builtin::BI__builtin_cabs;
6408 case Builtin::BI__builtin_cabs:
6409 return Builtin::BI__builtin_cabsl;
6410 case Builtin::BI__builtin_cabsl:
6413 case Builtin::BIabs:
6414 return Builtin::BIlabs;
6415 case Builtin::BIlabs:
6416 return Builtin::BIllabs;
6417 case Builtin::BIllabs:
6420 case Builtin::BIfabsf:
6421 return Builtin::BIfabs;
6422 case Builtin::BIfabs:
6423 return Builtin::BIfabsl;
6424 case Builtin::BIfabsl:
6427 case Builtin::BIcabsf:
6428 return Builtin::BIcabs;
6429 case Builtin::BIcabs:
6430 return Builtin::BIcabsl;
6431 case Builtin::BIcabsl:
6436 // Returns the argument type of the absolute value function.
6437 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6442 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6443 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6444 if (Error != ASTContext::GE_None)
6447 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6451 if (FT->getNumParams() != 1)
6454 return FT->getParamType(0);
6457 // Returns the best absolute value function, or zero, based on type and
6458 // current absolute value function.
6459 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6460 unsigned AbsFunctionKind) {
6461 unsigned BestKind = 0;
6462 uint64_t ArgSize = Context.getTypeSize(ArgType);
6463 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6464 Kind = getLargerAbsoluteValueFunction(Kind)) {
6465 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6466 if (Context.getTypeSize(ParamType) >= ArgSize) {
6469 else if (Context.hasSameType(ParamType, ArgType)) {
6478 enum AbsoluteValueKind {
6484 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6485 if (T->isIntegralOrEnumerationType())
6487 if (T->isRealFloatingType())
6488 return AVK_Floating;
6489 if (T->isAnyComplexType())
6492 llvm_unreachable("Type not integer, floating, or complex");
6495 // Changes the absolute value function to a different type. Preserves whether
6496 // the function is a builtin.
6497 static unsigned changeAbsFunction(unsigned AbsKind,
6498 AbsoluteValueKind ValueKind) {
6499 switch (ValueKind) {
6504 case Builtin::BI__builtin_fabsf:
6505 case Builtin::BI__builtin_fabs:
6506 case Builtin::BI__builtin_fabsl:
6507 case Builtin::BI__builtin_cabsf:
6508 case Builtin::BI__builtin_cabs:
6509 case Builtin::BI__builtin_cabsl:
6510 return Builtin::BI__builtin_abs;
6511 case Builtin::BIfabsf:
6512 case Builtin::BIfabs:
6513 case Builtin::BIfabsl:
6514 case Builtin::BIcabsf:
6515 case Builtin::BIcabs:
6516 case Builtin::BIcabsl:
6517 return Builtin::BIabs;
6523 case Builtin::BI__builtin_abs:
6524 case Builtin::BI__builtin_labs:
6525 case Builtin::BI__builtin_llabs:
6526 case Builtin::BI__builtin_cabsf:
6527 case Builtin::BI__builtin_cabs:
6528 case Builtin::BI__builtin_cabsl:
6529 return Builtin::BI__builtin_fabsf;
6530 case Builtin::BIabs:
6531 case Builtin::BIlabs:
6532 case Builtin::BIllabs:
6533 case Builtin::BIcabsf:
6534 case Builtin::BIcabs:
6535 case Builtin::BIcabsl:
6536 return Builtin::BIfabsf;
6542 case Builtin::BI__builtin_abs:
6543 case Builtin::BI__builtin_labs:
6544 case Builtin::BI__builtin_llabs:
6545 case Builtin::BI__builtin_fabsf:
6546 case Builtin::BI__builtin_fabs:
6547 case Builtin::BI__builtin_fabsl:
6548 return Builtin::BI__builtin_cabsf;
6549 case Builtin::BIabs:
6550 case Builtin::BIlabs:
6551 case Builtin::BIllabs:
6552 case Builtin::BIfabsf:
6553 case Builtin::BIfabs:
6554 case Builtin::BIfabsl:
6555 return Builtin::BIcabsf;
6558 llvm_unreachable("Unable to convert function");
6561 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6562 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6566 switch (FDecl->getBuiltinID()) {
6569 case Builtin::BI__builtin_abs:
6570 case Builtin::BI__builtin_fabs:
6571 case Builtin::BI__builtin_fabsf:
6572 case Builtin::BI__builtin_fabsl:
6573 case Builtin::BI__builtin_labs:
6574 case Builtin::BI__builtin_llabs:
6575 case Builtin::BI__builtin_cabs:
6576 case Builtin::BI__builtin_cabsf:
6577 case Builtin::BI__builtin_cabsl:
6578 case Builtin::BIabs:
6579 case Builtin::BIlabs:
6580 case Builtin::BIllabs:
6581 case Builtin::BIfabs:
6582 case Builtin::BIfabsf:
6583 case Builtin::BIfabsl:
6584 case Builtin::BIcabs:
6585 case Builtin::BIcabsf:
6586 case Builtin::BIcabsl:
6587 return FDecl->getBuiltinID();
6589 llvm_unreachable("Unknown Builtin type");
6592 // If the replacement is valid, emit a note with replacement function.
6593 // Additionally, suggest including the proper header if not already included.
6594 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6595 unsigned AbsKind, QualType ArgType) {
6596 bool EmitHeaderHint = true;
6597 const char *HeaderName = nullptr;
6598 const char *FunctionName = nullptr;
6599 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6600 FunctionName = "std::abs";
6601 if (ArgType->isIntegralOrEnumerationType()) {
6602 HeaderName = "cstdlib";
6603 } else if (ArgType->isRealFloatingType()) {
6604 HeaderName = "cmath";
6606 llvm_unreachable("Invalid Type");
6609 // Lookup all std::abs
6610 if (NamespaceDecl *Std = S.getStdNamespace()) {
6611 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6612 R.suppressDiagnostics();
6613 S.LookupQualifiedName(R, Std);
6615 for (const auto *I : R) {
6616 const FunctionDecl *FDecl = nullptr;
6617 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6618 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6620 FDecl = dyn_cast<FunctionDecl>(I);
6625 // Found std::abs(), check that they are the right ones.
6626 if (FDecl->getNumParams() != 1)
6629 // Check that the parameter type can handle the argument.
6630 QualType ParamType = FDecl->getParamDecl(0)->getType();
6631 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6632 S.Context.getTypeSize(ArgType) <=
6633 S.Context.getTypeSize(ParamType)) {
6634 // Found a function, don't need the header hint.
6635 EmitHeaderHint = false;
6641 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6642 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6645 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6646 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6647 R.suppressDiagnostics();
6648 S.LookupName(R, S.getCurScope());
6650 if (R.isSingleResult()) {
6651 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6652 if (FD && FD->getBuiltinID() == AbsKind) {
6653 EmitHeaderHint = false;
6657 } else if (!R.empty()) {
6663 S.Diag(Loc, diag::note_replace_abs_function)
6664 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6669 if (!EmitHeaderHint)
6672 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6676 template <std::size_t StrLen>
6677 static bool IsStdFunction(const FunctionDecl *FDecl,
6678 const char (&Str)[StrLen]) {
6681 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
6683 if (!FDecl->isInStdNamespace())
6689 // Warn when using the wrong abs() function.
6690 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6691 const FunctionDecl *FDecl) {
6692 if (Call->getNumArgs() != 1)
6695 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6696 bool IsStdAbs = IsStdFunction(FDecl, "abs");
6697 if (AbsKind == 0 && !IsStdAbs)
6700 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6701 QualType ParamType = Call->getArg(0)->getType();
6703 // Unsigned types cannot be negative. Suggest removing the absolute value
6705 if (ArgType->isUnsignedIntegerType()) {
6706 const char *FunctionName =
6707 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6708 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6709 Diag(Call->getExprLoc(), diag::note_remove_abs)
6711 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6715 // Taking the absolute value of a pointer is very suspicious, they probably
6716 // wanted to index into an array, dereference a pointer, call a function, etc.
6717 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6718 unsigned DiagType = 0;
6719 if (ArgType->isFunctionType())
6721 else if (ArgType->isArrayType())
6724 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6728 // std::abs has overloads which prevent most of the absolute value problems
6733 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6734 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6736 // The argument and parameter are the same kind. Check if they are the right
6738 if (ArgValueKind == ParamValueKind) {
6739 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6742 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6743 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6744 << FDecl << ArgType << ParamType;
6746 if (NewAbsKind == 0)
6749 emitReplacement(*this, Call->getExprLoc(),
6750 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6754 // ArgValueKind != ParamValueKind
6755 // The wrong type of absolute value function was used. Attempt to find the
6757 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6758 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6759 if (NewAbsKind == 0)
6762 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6763 << FDecl << ParamValueKind << ArgValueKind;
6765 emitReplacement(*this, Call->getExprLoc(),
6766 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6769 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
6770 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6771 const FunctionDecl *FDecl) {
6772 if (!Call || !FDecl) return;
6774 // Ignore template specializations and macros.
6775 if (!ActiveTemplateInstantiations.empty()) return;
6776 if (Call->getExprLoc().isMacroID()) return;
6778 // Only care about the one template argument, two function parameter std::max
6779 if (Call->getNumArgs() != 2) return;
6780 if (!IsStdFunction(FDecl, "max")) return;
6781 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6782 if (!ArgList) return;
6783 if (ArgList->size() != 1) return;
6785 // Check that template type argument is unsigned integer.
6786 const auto& TA = ArgList->get(0);
6787 if (TA.getKind() != TemplateArgument::Type) return;
6788 QualType ArgType = TA.getAsType();
6789 if (!ArgType->isUnsignedIntegerType()) return;
6791 // See if either argument is a literal zero.
6792 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6793 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6794 if (!MTE) return false;
6795 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6796 if (!Num) return false;
6797 if (Num->getValue() != 0) return false;
6801 const Expr *FirstArg = Call->getArg(0);
6802 const Expr *SecondArg = Call->getArg(1);
6803 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6804 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6806 // Only warn when exactly one argument is zero.
6807 if (IsFirstArgZero == IsSecondArgZero) return;
6809 SourceRange FirstRange = FirstArg->getSourceRange();
6810 SourceRange SecondRange = SecondArg->getSourceRange();
6812 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
6814 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
6815 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
6817 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
6818 SourceRange RemovalRange;
6819 if (IsFirstArgZero) {
6820 RemovalRange = SourceRange(FirstRange.getBegin(),
6821 SecondRange.getBegin().getLocWithOffset(-1));
6823 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
6824 SecondRange.getEnd());
6827 Diag(Call->getExprLoc(), diag::note_remove_max_call)
6828 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
6829 << FixItHint::CreateRemoval(RemovalRange);
6832 //===--- CHECK: Standard memory functions ---------------------------------===//
6834 /// \brief Takes the expression passed to the size_t parameter of functions
6835 /// such as memcmp, strncat, etc and warns if it's a comparison.
6837 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6838 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6839 IdentifierInfo *FnName,
6840 SourceLocation FnLoc,
6841 SourceLocation RParenLoc) {
6842 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6846 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6847 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6850 SourceRange SizeRange = Size->getSourceRange();
6851 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6852 << SizeRange << FnName;
6853 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6854 << FnName << FixItHint::CreateInsertion(
6855 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6856 << FixItHint::CreateRemoval(RParenLoc);
6857 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6858 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6859 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6865 /// \brief Determine whether the given type is or contains a dynamic class type
6866 /// (e.g., whether it has a vtable).
6867 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6868 bool &IsContained) {
6869 // Look through array types while ignoring qualifiers.
6870 const Type *Ty = T->getBaseElementTypeUnsafe();
6871 IsContained = false;
6873 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6874 RD = RD ? RD->getDefinition() : nullptr;
6875 if (!RD || RD->isInvalidDecl())
6878 if (RD->isDynamicClass())
6881 // Check all the fields. If any bases were dynamic, the class is dynamic.
6882 // It's impossible for a class to transitively contain itself by value, so
6883 // infinite recursion is impossible.
6884 for (auto *FD : RD->fields()) {
6886 if (const CXXRecordDecl *ContainedRD =
6887 getContainedDynamicClass(FD->getType(), SubContained)) {
6896 /// \brief If E is a sizeof expression, returns its argument expression,
6897 /// otherwise returns NULL.
6898 static const Expr *getSizeOfExprArg(const Expr *E) {
6899 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6900 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6901 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6902 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
6907 /// \brief If E is a sizeof expression, returns its argument type.
6908 static QualType getSizeOfArgType(const Expr *E) {
6909 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6910 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6911 if (SizeOf->getKind() == clang::UETT_SizeOf)
6912 return SizeOf->getTypeOfArgument();
6917 /// \brief Check for dangerous or invalid arguments to memset().
6919 /// This issues warnings on known problematic, dangerous or unspecified
6920 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6923 /// \param Call The call expression to diagnose.
6924 void Sema::CheckMemaccessArguments(const CallExpr *Call,
6926 IdentifierInfo *FnName) {
6929 // It is possible to have a non-standard definition of memset. Validate
6930 // we have enough arguments, and if not, abort further checking.
6931 unsigned ExpectedNumArgs =
6932 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
6933 if (Call->getNumArgs() < ExpectedNumArgs)
6936 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
6937 BId == Builtin::BIstrndup ? 1 : 2);
6939 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
6940 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
6942 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6943 Call->getLocStart(), Call->getRParenLoc()))
6946 // We have special checking when the length is a sizeof expression.
6947 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6948 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6949 llvm::FoldingSetNodeID SizeOfArgID;
6951 // Although widely used, 'bzero' is not a standard function. Be more strict
6952 // with the argument types before allowing diagnostics and only allow the
6953 // form bzero(ptr, sizeof(...)).
6954 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6955 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6958 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6959 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
6960 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
6962 QualType DestTy = Dest->getType();
6964 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
6965 PointeeTy = DestPtrTy->getPointeeType();
6967 // Never warn about void type pointers. This can be used to suppress
6969 if (PointeeTy->isVoidType())
6972 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6973 // actually comparing the expressions for equality. Because computing the
6974 // expression IDs can be expensive, we only do this if the diagnostic is
6977 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6978 SizeOfArg->getExprLoc())) {
6979 // We only compute IDs for expressions if the warning is enabled, and
6980 // cache the sizeof arg's ID.
6981 if (SizeOfArgID == llvm::FoldingSetNodeID())
6982 SizeOfArg->Profile(SizeOfArgID, Context, true);
6983 llvm::FoldingSetNodeID DestID;
6984 Dest->Profile(DestID, Context, true);
6985 if (DestID == SizeOfArgID) {
6986 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6987 // over sizeof(src) as well.
6988 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
6989 StringRef ReadableName = FnName->getName();
6991 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
6992 if (UnaryOp->getOpcode() == UO_AddrOf)
6993 ActionIdx = 1; // If its an address-of operator, just remove it.
6994 if (!PointeeTy->isIncompleteType() &&
6995 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
6996 ActionIdx = 2; // If the pointee's size is sizeof(char),
6997 // suggest an explicit length.
6999 // If the function is defined as a builtin macro, do not show macro
7001 SourceLocation SL = SizeOfArg->getExprLoc();
7002 SourceRange DSR = Dest->getSourceRange();
7003 SourceRange SSR = SizeOfArg->getSourceRange();
7004 SourceManager &SM = getSourceManager();
7006 if (SM.isMacroArgExpansion(SL)) {
7007 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7008 SL = SM.getSpellingLoc(SL);
7009 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7010 SM.getSpellingLoc(DSR.getEnd()));
7011 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7012 SM.getSpellingLoc(SSR.getEnd()));
7015 DiagRuntimeBehavior(SL, SizeOfArg,
7016 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7022 DiagRuntimeBehavior(SL, SizeOfArg,
7023 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7031 // Also check for cases where the sizeof argument is the exact same
7032 // type as the memory argument, and where it points to a user-defined
7034 if (SizeOfArgTy != QualType()) {
7035 if (PointeeTy->isRecordType() &&
7036 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7037 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7038 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7039 << FnName << SizeOfArgTy << ArgIdx
7040 << PointeeTy << Dest->getSourceRange()
7041 << LenExpr->getSourceRange());
7045 } else if (DestTy->isArrayType()) {
7049 if (PointeeTy == QualType())
7052 // Always complain about dynamic classes.
7054 if (const CXXRecordDecl *ContainedRD =
7055 getContainedDynamicClass(PointeeTy, IsContained)) {
7057 unsigned OperationType = 0;
7058 // "overwritten" if we're warning about the destination for any call
7059 // but memcmp; otherwise a verb appropriate to the call.
7060 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7061 if (BId == Builtin::BImemcpy)
7063 else if(BId == Builtin::BImemmove)
7065 else if (BId == Builtin::BImemcmp)
7069 DiagRuntimeBehavior(
7070 Dest->getExprLoc(), Dest,
7071 PDiag(diag::warn_dyn_class_memaccess)
7072 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7073 << FnName << IsContained << ContainedRD << OperationType
7074 << Call->getCallee()->getSourceRange());
7075 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7076 BId != Builtin::BImemset)
7077 DiagRuntimeBehavior(
7078 Dest->getExprLoc(), Dest,
7079 PDiag(diag::warn_arc_object_memaccess)
7080 << ArgIdx << FnName << PointeeTy
7081 << Call->getCallee()->getSourceRange());
7085 DiagRuntimeBehavior(
7086 Dest->getExprLoc(), Dest,
7087 PDiag(diag::note_bad_memaccess_silence)
7088 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7093 // A little helper routine: ignore addition and subtraction of integer literals.
7094 // This intentionally does not ignore all integer constant expressions because
7095 // we don't want to remove sizeof().
7096 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7097 Ex = Ex->IgnoreParenCasts();
7100 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7101 if (!BO || !BO->isAdditiveOp())
7104 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7105 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7107 if (isa<IntegerLiteral>(RHS))
7109 else if (isa<IntegerLiteral>(LHS))
7118 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7119 ASTContext &Context) {
7120 // Only handle constant-sized or VLAs, but not flexible members.
7121 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7122 // Only issue the FIXIT for arrays of size > 1.
7123 if (CAT->getSize().getSExtValue() <= 1)
7125 } else if (!Ty->isVariableArrayType()) {
7131 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7132 // be the size of the source, instead of the destination.
7133 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7134 IdentifierInfo *FnName) {
7136 // Don't crash if the user has the wrong number of arguments
7137 unsigned NumArgs = Call->getNumArgs();
7138 if ((NumArgs != 3) && (NumArgs != 4))
7141 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7142 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7143 const Expr *CompareWithSrc = nullptr;
7145 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7146 Call->getLocStart(), Call->getRParenLoc()))
7149 // Look for 'strlcpy(dst, x, sizeof(x))'
7150 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7151 CompareWithSrc = Ex;
7153 // Look for 'strlcpy(dst, x, strlen(x))'
7154 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7155 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7156 SizeCall->getNumArgs() == 1)
7157 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7161 if (!CompareWithSrc)
7164 // Determine if the argument to sizeof/strlen is equal to the source
7165 // argument. In principle there's all kinds of things you could do
7166 // here, for instance creating an == expression and evaluating it with
7167 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7168 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7172 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7173 if (!CompareWithSrcDRE ||
7174 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7177 const Expr *OriginalSizeArg = Call->getArg(2);
7178 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7179 << OriginalSizeArg->getSourceRange() << FnName;
7181 // Output a FIXIT hint if the destination is an array (rather than a
7182 // pointer to an array). This could be enhanced to handle some
7183 // pointers if we know the actual size, like if DstArg is 'array+2'
7184 // we could say 'sizeof(array)-2'.
7185 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7186 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7189 SmallString<128> sizeString;
7190 llvm::raw_svector_ostream OS(sizeString);
7192 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7195 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7196 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7200 /// Check if two expressions refer to the same declaration.
7201 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7202 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7203 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7204 return D1->getDecl() == D2->getDecl();
7208 static const Expr *getStrlenExprArg(const Expr *E) {
7209 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7210 const FunctionDecl *FD = CE->getDirectCallee();
7211 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7213 return CE->getArg(0)->IgnoreParenCasts();
7218 // Warn on anti-patterns as the 'size' argument to strncat.
7219 // The correct size argument should look like following:
7220 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7221 void Sema::CheckStrncatArguments(const CallExpr *CE,
7222 IdentifierInfo *FnName) {
7223 // Don't crash if the user has the wrong number of arguments.
7224 if (CE->getNumArgs() < 3)
7226 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7227 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7228 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7230 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7231 CE->getRParenLoc()))
7234 // Identify common expressions, which are wrongly used as the size argument
7235 // to strncat and may lead to buffer overflows.
7236 unsigned PatternType = 0;
7237 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7239 if (referToTheSameDecl(SizeOfArg, DstArg))
7242 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7244 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7245 if (BE->getOpcode() == BO_Sub) {
7246 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7247 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7248 // - sizeof(dst) - strlen(dst)
7249 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7250 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7252 // - sizeof(src) - (anything)
7253 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7258 if (PatternType == 0)
7261 // Generate the diagnostic.
7262 SourceLocation SL = LenArg->getLocStart();
7263 SourceRange SR = LenArg->getSourceRange();
7264 SourceManager &SM = getSourceManager();
7266 // If the function is defined as a builtin macro, do not show macro expansion.
7267 if (SM.isMacroArgExpansion(SL)) {
7268 SL = SM.getSpellingLoc(SL);
7269 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7270 SM.getSpellingLoc(SR.getEnd()));
7273 // Check if the destination is an array (rather than a pointer to an array).
7274 QualType DstTy = DstArg->getType();
7275 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7277 if (!isKnownSizeArray) {
7278 if (PatternType == 1)
7279 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7281 Diag(SL, diag::warn_strncat_src_size) << SR;
7285 if (PatternType == 1)
7286 Diag(SL, diag::warn_strncat_large_size) << SR;
7288 Diag(SL, diag::warn_strncat_src_size) << SR;
7290 SmallString<128> sizeString;
7291 llvm::raw_svector_ostream OS(sizeString);
7293 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7296 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7299 Diag(SL, diag::note_strncat_wrong_size)
7300 << FixItHint::CreateReplacement(SR, OS.str());
7303 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7305 static const Expr *EvalVal(const Expr *E,
7306 SmallVectorImpl<const DeclRefExpr *> &refVars,
7307 const Decl *ParentDecl);
7308 static const Expr *EvalAddr(const Expr *E,
7309 SmallVectorImpl<const DeclRefExpr *> &refVars,
7310 const Decl *ParentDecl);
7312 /// CheckReturnStackAddr - Check if a return statement returns the address
7313 /// of a stack variable.
7315 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7316 SourceLocation ReturnLoc) {
7318 const Expr *stackE = nullptr;
7319 SmallVector<const DeclRefExpr *, 8> refVars;
7321 // Perform checking for returned stack addresses, local blocks,
7322 // label addresses or references to temporaries.
7323 if (lhsType->isPointerType() ||
7324 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7325 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7326 } else if (lhsType->isReferenceType()) {
7327 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7331 return; // Nothing suspicious was found.
7333 // Parameters are initalized in the calling scope, so taking the address
7334 // of a parameter reference doesn't need a warning.
7335 for (auto *DRE : refVars)
7336 if (isa<ParmVarDecl>(DRE->getDecl()))
7339 SourceLocation diagLoc;
7340 SourceRange diagRange;
7341 if (refVars.empty()) {
7342 diagLoc = stackE->getLocStart();
7343 diagRange = stackE->getSourceRange();
7345 // We followed through a reference variable. 'stackE' contains the
7346 // problematic expression but we will warn at the return statement pointing
7347 // at the reference variable. We will later display the "trail" of
7348 // reference variables using notes.
7349 diagLoc = refVars[0]->getLocStart();
7350 diagRange = refVars[0]->getSourceRange();
7353 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7354 // address of local var
7355 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7356 << DR->getDecl()->getDeclName() << diagRange;
7357 } else if (isa<BlockExpr>(stackE)) { // local block.
7358 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7359 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7360 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7361 } else { // local temporary.
7362 // If there is an LValue->RValue conversion, then the value of the
7363 // reference type is used, not the reference.
7364 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7365 if (ICE->getCastKind() == CK_LValueToRValue) {
7369 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7370 << lhsType->isReferenceType() << diagRange;
7373 // Display the "trail" of reference variables that we followed until we
7374 // found the problematic expression using notes.
7375 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7376 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7377 // If this var binds to another reference var, show the range of the next
7378 // var, otherwise the var binds to the problematic expression, in which case
7379 // show the range of the expression.
7380 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7381 : stackE->getSourceRange();
7382 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7383 << VD->getDeclName() << range;
7387 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7388 /// check if the expression in a return statement evaluates to an address
7389 /// to a location on the stack, a local block, an address of a label, or a
7390 /// reference to local temporary. The recursion is used to traverse the
7391 /// AST of the return expression, with recursion backtracking when we
7392 /// encounter a subexpression that (1) clearly does not lead to one of the
7393 /// above problematic expressions (2) is something we cannot determine leads to
7394 /// a problematic expression based on such local checking.
7396 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
7397 /// the expression that they point to. Such variables are added to the
7398 /// 'refVars' vector so that we know what the reference variable "trail" was.
7400 /// EvalAddr processes expressions that are pointers that are used as
7401 /// references (and not L-values). EvalVal handles all other values.
7402 /// At the base case of the recursion is a check for the above problematic
7405 /// This implementation handles:
7407 /// * pointer-to-pointer casts
7408 /// * implicit conversions from array references to pointers
7409 /// * taking the address of fields
7410 /// * arbitrary interplay between "&" and "*" operators
7411 /// * pointer arithmetic from an address of a stack variable
7412 /// * taking the address of an array element where the array is on the stack
7413 static const Expr *EvalAddr(const Expr *E,
7414 SmallVectorImpl<const DeclRefExpr *> &refVars,
7415 const Decl *ParentDecl) {
7416 if (E->isTypeDependent())
7419 // We should only be called for evaluating pointer expressions.
7420 assert((E->getType()->isAnyPointerType() ||
7421 E->getType()->isBlockPointerType() ||
7422 E->getType()->isObjCQualifiedIdType()) &&
7423 "EvalAddr only works on pointers");
7425 E = E->IgnoreParens();
7427 // Our "symbolic interpreter" is just a dispatch off the currently
7428 // viewed AST node. We then recursively traverse the AST by calling
7429 // EvalAddr and EvalVal appropriately.
7430 switch (E->getStmtClass()) {
7431 case Stmt::DeclRefExprClass: {
7432 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7434 // If we leave the immediate function, the lifetime isn't about to end.
7435 if (DR->refersToEnclosingVariableOrCapture())
7438 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7439 // If this is a reference variable, follow through to the expression that
7441 if (V->hasLocalStorage() &&
7442 V->getType()->isReferenceType() && V->hasInit()) {
7443 // Add the reference variable to the "trail".
7444 refVars.push_back(DR);
7445 return EvalAddr(V->getInit(), refVars, ParentDecl);
7451 case Stmt::UnaryOperatorClass: {
7452 // The only unary operator that make sense to handle here
7453 // is AddrOf. All others don't make sense as pointers.
7454 const UnaryOperator *U = cast<UnaryOperator>(E);
7456 if (U->getOpcode() == UO_AddrOf)
7457 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7461 case Stmt::BinaryOperatorClass: {
7462 // Handle pointer arithmetic. All other binary operators are not valid
7464 const BinaryOperator *B = cast<BinaryOperator>(E);
7465 BinaryOperatorKind op = B->getOpcode();
7467 if (op != BO_Add && op != BO_Sub)
7470 const Expr *Base = B->getLHS();
7472 // Determine which argument is the real pointer base. It could be
7473 // the RHS argument instead of the LHS.
7474 if (!Base->getType()->isPointerType())
7477 assert(Base->getType()->isPointerType());
7478 return EvalAddr(Base, refVars, ParentDecl);
7481 // For conditional operators we need to see if either the LHS or RHS are
7482 // valid DeclRefExpr*s. If one of them is valid, we return it.
7483 case Stmt::ConditionalOperatorClass: {
7484 const ConditionalOperator *C = cast<ConditionalOperator>(E);
7486 // Handle the GNU extension for missing LHS.
7487 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7488 if (const Expr *LHSExpr = C->getLHS()) {
7489 // In C++, we can have a throw-expression, which has 'void' type.
7490 if (!LHSExpr->getType()->isVoidType())
7491 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7495 // In C++, we can have a throw-expression, which has 'void' type.
7496 if (C->getRHS()->getType()->isVoidType())
7499 return EvalAddr(C->getRHS(), refVars, ParentDecl);
7502 case Stmt::BlockExprClass:
7503 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7504 return E; // local block.
7507 case Stmt::AddrLabelExprClass:
7508 return E; // address of label.
7510 case Stmt::ExprWithCleanupsClass:
7511 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7514 // For casts, we need to handle conversions from arrays to
7515 // pointer values, and pointer-to-pointer conversions.
7516 case Stmt::ImplicitCastExprClass:
7517 case Stmt::CStyleCastExprClass:
7518 case Stmt::CXXFunctionalCastExprClass:
7519 case Stmt::ObjCBridgedCastExprClass:
7520 case Stmt::CXXStaticCastExprClass:
7521 case Stmt::CXXDynamicCastExprClass:
7522 case Stmt::CXXConstCastExprClass:
7523 case Stmt::CXXReinterpretCastExprClass: {
7524 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7525 switch (cast<CastExpr>(E)->getCastKind()) {
7526 case CK_LValueToRValue:
7528 case CK_BaseToDerived:
7529 case CK_DerivedToBase:
7530 case CK_UncheckedDerivedToBase:
7532 case CK_CPointerToObjCPointerCast:
7533 case CK_BlockPointerToObjCPointerCast:
7534 case CK_AnyPointerToBlockPointerCast:
7535 return EvalAddr(SubExpr, refVars, ParentDecl);
7537 case CK_ArrayToPointerDecay:
7538 return EvalVal(SubExpr, refVars, ParentDecl);
7541 if (SubExpr->getType()->isAnyPointerType() ||
7542 SubExpr->getType()->isBlockPointerType() ||
7543 SubExpr->getType()->isObjCQualifiedIdType())
7544 return EvalAddr(SubExpr, refVars, ParentDecl);
7553 case Stmt::MaterializeTemporaryExprClass:
7554 if (const Expr *Result =
7555 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7556 refVars, ParentDecl))
7560 // Everything else: we simply don't reason about them.
7566 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
7567 /// See the comments for EvalAddr for more details.
7568 static const Expr *EvalVal(const Expr *E,
7569 SmallVectorImpl<const DeclRefExpr *> &refVars,
7570 const Decl *ParentDecl) {
7572 // We should only be called for evaluating non-pointer expressions, or
7573 // expressions with a pointer type that are not used as references but
7575 // are l-values (e.g., DeclRefExpr with a pointer type).
7577 // Our "symbolic interpreter" is just a dispatch off the currently
7578 // viewed AST node. We then recursively traverse the AST by calling
7579 // EvalAddr and EvalVal appropriately.
7581 E = E->IgnoreParens();
7582 switch (E->getStmtClass()) {
7583 case Stmt::ImplicitCastExprClass: {
7584 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7585 if (IE->getValueKind() == VK_LValue) {
7586 E = IE->getSubExpr();
7592 case Stmt::ExprWithCleanupsClass:
7593 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7596 case Stmt::DeclRefExprClass: {
7597 // When we hit a DeclRefExpr we are looking at code that refers to a
7598 // variable's name. If it's not a reference variable we check if it has
7599 // local storage within the function, and if so, return the expression.
7600 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7602 // If we leave the immediate function, the lifetime isn't about to end.
7603 if (DR->refersToEnclosingVariableOrCapture())
7606 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7607 // Check if it refers to itself, e.g. "int& i = i;".
7608 if (V == ParentDecl)
7611 if (V->hasLocalStorage()) {
7612 if (!V->getType()->isReferenceType())
7615 // Reference variable, follow through to the expression that
7618 // Add the reference variable to the "trail".
7619 refVars.push_back(DR);
7620 return EvalVal(V->getInit(), refVars, V);
7628 case Stmt::UnaryOperatorClass: {
7629 // The only unary operator that make sense to handle here
7630 // is Deref. All others don't resolve to a "name." This includes
7631 // handling all sorts of rvalues passed to a unary operator.
7632 const UnaryOperator *U = cast<UnaryOperator>(E);
7634 if (U->getOpcode() == UO_Deref)
7635 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7640 case Stmt::ArraySubscriptExprClass: {
7641 // Array subscripts are potential references to data on the stack. We
7642 // retrieve the DeclRefExpr* for the array variable if it indeed
7643 // has local storage.
7644 const auto *ASE = cast<ArraySubscriptExpr>(E);
7645 if (ASE->isTypeDependent())
7647 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7650 case Stmt::OMPArraySectionExprClass: {
7651 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7655 case Stmt::ConditionalOperatorClass: {
7656 // For conditional operators we need to see if either the LHS or RHS are
7657 // non-NULL Expr's. If one is non-NULL, we return it.
7658 const ConditionalOperator *C = cast<ConditionalOperator>(E);
7660 // Handle the GNU extension for missing LHS.
7661 if (const Expr *LHSExpr = C->getLHS()) {
7662 // In C++, we can have a throw-expression, which has 'void' type.
7663 if (!LHSExpr->getType()->isVoidType())
7664 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7668 // In C++, we can have a throw-expression, which has 'void' type.
7669 if (C->getRHS()->getType()->isVoidType())
7672 return EvalVal(C->getRHS(), refVars, ParentDecl);
7675 // Accesses to members are potential references to data on the stack.
7676 case Stmt::MemberExprClass: {
7677 const MemberExpr *M = cast<MemberExpr>(E);
7679 // Check for indirect access. We only want direct field accesses.
7683 // Check whether the member type is itself a reference, in which case
7684 // we're not going to refer to the member, but to what the member refers
7686 if (M->getMemberDecl()->getType()->isReferenceType())
7689 return EvalVal(M->getBase(), refVars, ParentDecl);
7692 case Stmt::MaterializeTemporaryExprClass:
7693 if (const Expr *Result =
7694 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7695 refVars, ParentDecl))
7700 // Check that we don't return or take the address of a reference to a
7701 // temporary. This is only useful in C++.
7702 if (!E->isTypeDependent() && E->isRValue())
7705 // Everything else: we simply don't reason about them.
7712 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7713 SourceLocation ReturnLoc,
7715 const AttrVec *Attrs,
7716 const FunctionDecl *FD) {
7717 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7719 // Check if the return value is null but should not be.
7720 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7721 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7722 CheckNonNullExpr(*this, RetValExp))
7723 Diag(ReturnLoc, diag::warn_null_ret)
7724 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7726 // C++11 [basic.stc.dynamic.allocation]p4:
7727 // If an allocation function declared with a non-throwing
7728 // exception-specification fails to allocate storage, it shall return
7729 // a null pointer. Any other allocation function that fails to allocate
7730 // storage shall indicate failure only by throwing an exception [...]
7732 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7733 if (Op == OO_New || Op == OO_Array_New) {
7734 const FunctionProtoType *Proto
7735 = FD->getType()->castAs<FunctionProtoType>();
7736 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7737 CheckNonNullExpr(*this, RetValExp))
7738 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7739 << FD << getLangOpts().CPlusPlus11;
7744 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7746 /// Check for comparisons of floating point operands using != and ==.
7747 /// Issue a warning if these are no self-comparisons, as they are not likely
7748 /// to do what the programmer intended.
7749 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7750 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7751 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7753 // Special case: check for x == x (which is OK).
7754 // Do not emit warnings for such cases.
7755 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7756 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7757 if (DRL->getDecl() == DRR->getDecl())
7760 // Special case: check for comparisons against literals that can be exactly
7761 // represented by APFloat. In such cases, do not emit a warning. This
7762 // is a heuristic: often comparison against such literals are used to
7763 // detect if a value in a variable has not changed. This clearly can
7764 // lead to false negatives.
7765 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7769 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7773 // Check for comparisons with builtin types.
7774 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7775 if (CL->getBuiltinCallee())
7778 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7779 if (CR->getBuiltinCallee())
7782 // Emit the diagnostic.
7783 Diag(Loc, diag::warn_floatingpoint_eq)
7784 << LHS->getSourceRange() << RHS->getSourceRange();
7787 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7788 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7792 /// Structure recording the 'active' range of an integer-valued
7795 /// The number of bits active in the int.
7798 /// True if the int is known not to have negative values.
7801 IntRange(unsigned Width, bool NonNegative)
7802 : Width(Width), NonNegative(NonNegative)
7805 /// Returns the range of the bool type.
7806 static IntRange forBoolType() {
7807 return IntRange(1, true);
7810 /// Returns the range of an opaque value of the given integral type.
7811 static IntRange forValueOfType(ASTContext &C, QualType T) {
7812 return forValueOfCanonicalType(C,
7813 T->getCanonicalTypeInternal().getTypePtr());
7816 /// Returns the range of an opaque value of a canonical integral type.
7817 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7818 assert(T->isCanonicalUnqualified());
7820 if (const VectorType *VT = dyn_cast<VectorType>(T))
7821 T = VT->getElementType().getTypePtr();
7822 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7823 T = CT->getElementType().getTypePtr();
7824 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7825 T = AT->getValueType().getTypePtr();
7827 // For enum types, use the known bit width of the enumerators.
7828 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7829 EnumDecl *Enum = ET->getDecl();
7830 if (!Enum->isCompleteDefinition())
7831 return IntRange(C.getIntWidth(QualType(T, 0)), false);
7833 unsigned NumPositive = Enum->getNumPositiveBits();
7834 unsigned NumNegative = Enum->getNumNegativeBits();
7836 if (NumNegative == 0)
7837 return IntRange(NumPositive, true/*NonNegative*/);
7839 return IntRange(std::max(NumPositive + 1, NumNegative),
7840 false/*NonNegative*/);
7843 const BuiltinType *BT = cast<BuiltinType>(T);
7844 assert(BT->isInteger());
7846 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7849 /// Returns the "target" range of a canonical integral type, i.e.
7850 /// the range of values expressible in the type.
7852 /// This matches forValueOfCanonicalType except that enums have the
7853 /// full range of their type, not the range of their enumerators.
7854 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7855 assert(T->isCanonicalUnqualified());
7857 if (const VectorType *VT = dyn_cast<VectorType>(T))
7858 T = VT->getElementType().getTypePtr();
7859 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7860 T = CT->getElementType().getTypePtr();
7861 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7862 T = AT->getValueType().getTypePtr();
7863 if (const EnumType *ET = dyn_cast<EnumType>(T))
7864 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7866 const BuiltinType *BT = cast<BuiltinType>(T);
7867 assert(BT->isInteger());
7869 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7872 /// Returns the supremum of two ranges: i.e. their conservative merge.
7873 static IntRange join(IntRange L, IntRange R) {
7874 return IntRange(std::max(L.Width, R.Width),
7875 L.NonNegative && R.NonNegative);
7878 /// Returns the infinum of two ranges: i.e. their aggressive merge.
7879 static IntRange meet(IntRange L, IntRange R) {
7880 return IntRange(std::min(L.Width, R.Width),
7881 L.NonNegative || R.NonNegative);
7885 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
7886 if (value.isSigned() && value.isNegative())
7887 return IntRange(value.getMinSignedBits(), false);
7889 if (value.getBitWidth() > MaxWidth)
7890 value = value.trunc(MaxWidth);
7892 // isNonNegative() just checks the sign bit without considering
7894 return IntRange(value.getActiveBits(), true);
7897 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7898 unsigned MaxWidth) {
7900 return GetValueRange(C, result.getInt(), MaxWidth);
7902 if (result.isVector()) {
7903 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7904 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7905 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7906 R = IntRange::join(R, El);
7911 if (result.isComplexInt()) {
7912 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7913 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7914 return IntRange::join(R, I);
7917 // This can happen with lossless casts to intptr_t of "based" lvalues.
7918 // Assume it might use arbitrary bits.
7919 // FIXME: The only reason we need to pass the type in here is to get
7920 // the sign right on this one case. It would be nice if APValue
7922 assert(result.isLValue() || result.isAddrLabelDiff());
7923 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
7926 QualType GetExprType(const Expr *E) {
7927 QualType Ty = E->getType();
7928 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7929 Ty = AtomicRHS->getValueType();
7933 /// Pseudo-evaluate the given integer expression, estimating the
7934 /// range of values it might take.
7936 /// \param MaxWidth - the width to which the value will be truncated
7937 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
7938 E = E->IgnoreParens();
7940 // Try a full evaluation first.
7941 Expr::EvalResult result;
7942 if (E->EvaluateAsRValue(result, C))
7943 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
7945 // I think we only want to look through implicit casts here; if the
7946 // user has an explicit widening cast, we should treat the value as
7947 // being of the new, wider type.
7948 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7949 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7950 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7952 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7954 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7955 CE->getCastKind() == CK_BooleanToSignedIntegral;
7957 // Assume that non-integer casts can span the full range of the type.
7959 return OutputTypeRange;
7962 = GetExprRange(C, CE->getSubExpr(),
7963 std::min(MaxWidth, OutputTypeRange.Width));
7965 // Bail out if the subexpr's range is as wide as the cast type.
7966 if (SubRange.Width >= OutputTypeRange.Width)
7967 return OutputTypeRange;
7969 // Otherwise, we take the smaller width, and we're non-negative if
7970 // either the output type or the subexpr is.
7971 return IntRange(SubRange.Width,
7972 SubRange.NonNegative || OutputTypeRange.NonNegative);
7975 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7976 // If we can fold the condition, just take that operand.
7978 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7979 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7980 : CO->getFalseExpr(),
7983 // Otherwise, conservatively merge.
7984 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7985 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7986 return IntRange::join(L, R);
7989 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
7990 switch (BO->getOpcode()) {
7992 // Boolean-valued operations are single-bit and positive.
8001 return IntRange::forBoolType();
8003 // The type of the assignments is the type of the LHS, so the RHS
8004 // is not necessarily the same type.
8013 return IntRange::forValueOfType(C, GetExprType(E));
8015 // Simple assignments just pass through the RHS, which will have
8016 // been coerced to the LHS type.
8019 return GetExprRange(C, BO->getRHS(), MaxWidth);
8021 // Operations with opaque sources are black-listed.
8024 return IntRange::forValueOfType(C, GetExprType(E));
8026 // Bitwise-and uses the *infinum* of the two source ranges.
8029 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8030 GetExprRange(C, BO->getRHS(), MaxWidth));
8032 // Left shift gets black-listed based on a judgement call.
8034 // ...except that we want to treat '1 << (blah)' as logically
8035 // positive. It's an important idiom.
8036 if (IntegerLiteral *I
8037 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8038 if (I->getValue() == 1) {
8039 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8040 return IntRange(R.Width, /*NonNegative*/ true);
8046 return IntRange::forValueOfType(C, GetExprType(E));
8048 // Right shift by a constant can narrow its left argument.
8050 case BO_ShrAssign: {
8051 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8053 // If the shift amount is a positive constant, drop the width by
8056 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8057 shift.isNonNegative()) {
8058 unsigned zext = shift.getZExtValue();
8059 if (zext >= L.Width)
8060 L.Width = (L.NonNegative ? 0 : 1);
8068 // Comma acts as its right operand.
8070 return GetExprRange(C, BO->getRHS(), MaxWidth);
8072 // Black-list pointer subtractions.
8074 if (BO->getLHS()->getType()->isPointerType())
8075 return IntRange::forValueOfType(C, GetExprType(E));
8078 // The width of a division result is mostly determined by the size
8081 // Don't 'pre-truncate' the operands.
8082 unsigned opWidth = C.getIntWidth(GetExprType(E));
8083 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8085 // If the divisor is constant, use that.
8086 llvm::APSInt divisor;
8087 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8088 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8089 if (log2 >= L.Width)
8090 L.Width = (L.NonNegative ? 0 : 1);
8092 L.Width = std::min(L.Width - log2, MaxWidth);
8096 // Otherwise, just use the LHS's width.
8097 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8098 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8101 // The result of a remainder can't be larger than the result of
8104 // Don't 'pre-truncate' the operands.
8105 unsigned opWidth = C.getIntWidth(GetExprType(E));
8106 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8107 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8109 IntRange meet = IntRange::meet(L, R);
8110 meet.Width = std::min(meet.Width, MaxWidth);
8114 // The default behavior is okay for these.
8122 // The default case is to treat the operation as if it were closed
8123 // on the narrowest type that encompasses both operands.
8124 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8125 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8126 return IntRange::join(L, R);
8129 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8130 switch (UO->getOpcode()) {
8131 // Boolean-valued operations are white-listed.
8133 return IntRange::forBoolType();
8135 // Operations with opaque sources are black-listed.
8137 case UO_AddrOf: // should be impossible
8138 return IntRange::forValueOfType(C, GetExprType(E));
8141 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8145 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8146 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8148 if (const auto *BitField = E->getSourceBitField())
8149 return IntRange(BitField->getBitWidthValue(C),
8150 BitField->getType()->isUnsignedIntegerOrEnumerationType());
8152 return IntRange::forValueOfType(C, GetExprType(E));
8155 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8156 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8159 /// Checks whether the given value, which currently has the given
8160 /// source semantics, has the same value when coerced through the
8161 /// target semantics.
8162 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8163 const llvm::fltSemantics &Src,
8164 const llvm::fltSemantics &Tgt) {
8165 llvm::APFloat truncated = value;
8168 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8169 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8171 return truncated.bitwiseIsEqual(value);
8174 /// Checks whether the given value, which currently has the given
8175 /// source semantics, has the same value when coerced through the
8176 /// target semantics.
8178 /// The value might be a vector of floats (or a complex number).
8179 bool IsSameFloatAfterCast(const APValue &value,
8180 const llvm::fltSemantics &Src,
8181 const llvm::fltSemantics &Tgt) {
8182 if (value.isFloat())
8183 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8185 if (value.isVector()) {
8186 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8187 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8192 assert(value.isComplexFloat());
8193 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8194 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8197 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8199 bool IsZero(Sema &S, Expr *E) {
8200 // Suppress cases where we are comparing against an enum constant.
8201 if (const DeclRefExpr *DR =
8202 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8203 if (isa<EnumConstantDecl>(DR->getDecl()))
8206 // Suppress cases where the '0' value is expanded from a macro.
8207 if (E->getLocStart().isMacroID())
8211 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8214 bool HasEnumType(Expr *E) {
8215 // Strip off implicit integral promotions.
8216 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8217 if (ICE->getCastKind() != CK_IntegralCast &&
8218 ICE->getCastKind() != CK_NoOp)
8220 E = ICE->getSubExpr();
8223 return E->getType()->isEnumeralType();
8226 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
8227 // Disable warning in template instantiations.
8228 if (!S.ActiveTemplateInstantiations.empty())
8231 BinaryOperatorKind op = E->getOpcode();
8232 if (E->isValueDependent())
8235 if (op == BO_LT && IsZero(S, E->getRHS())) {
8236 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8237 << "< 0" << "false" << HasEnumType(E->getLHS())
8238 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8239 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
8240 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8241 << ">= 0" << "true" << HasEnumType(E->getLHS())
8242 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8243 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
8244 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8245 << "0 >" << "false" << HasEnumType(E->getRHS())
8246 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8247 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
8248 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8249 << "0 <=" << "true" << HasEnumType(E->getRHS())
8250 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8254 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8255 Expr *Other, const llvm::APSInt &Value,
8257 // Disable warning in template instantiations.
8258 if (!S.ActiveTemplateInstantiations.empty())
8261 // TODO: Investigate using GetExprRange() to get tighter bounds
8262 // on the bit ranges.
8263 QualType OtherT = Other->getType();
8264 if (const auto *AT = OtherT->getAs<AtomicType>())
8265 OtherT = AT->getValueType();
8266 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8267 unsigned OtherWidth = OtherRange.Width;
8269 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8271 // 0 values are handled later by CheckTrivialUnsignedComparison().
8272 if ((Value == 0) && (!OtherIsBooleanType))
8275 BinaryOperatorKind op = E->getOpcode();
8278 // Used for diagnostic printout.
8280 LiteralConstant = 0,
8283 } LiteralOrBoolConstant = LiteralConstant;
8285 if (!OtherIsBooleanType) {
8286 QualType ConstantT = Constant->getType();
8287 QualType CommonT = E->getLHS()->getType();
8289 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8291 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8292 "comparison with non-integer type");
8294 bool ConstantSigned = ConstantT->isSignedIntegerType();
8295 bool CommonSigned = CommonT->isSignedIntegerType();
8297 bool EqualityOnly = false;
8300 // The common type is signed, therefore no signed to unsigned conversion.
8301 if (!OtherRange.NonNegative) {
8302 // Check that the constant is representable in type OtherT.
8303 if (ConstantSigned) {
8304 if (OtherWidth >= Value.getMinSignedBits())
8306 } else { // !ConstantSigned
8307 if (OtherWidth >= Value.getActiveBits() + 1)
8310 } else { // !OtherSigned
8311 // Check that the constant is representable in type OtherT.
8312 // Negative values are out of range.
8313 if (ConstantSigned) {
8314 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8316 } else { // !ConstantSigned
8317 if (OtherWidth >= Value.getActiveBits())
8321 } else { // !CommonSigned
8322 if (OtherRange.NonNegative) {
8323 if (OtherWidth >= Value.getActiveBits())
8325 } else { // OtherSigned
8326 assert(!ConstantSigned &&
8327 "Two signed types converted to unsigned types.");
8328 // Check to see if the constant is representable in OtherT.
8329 if (OtherWidth > Value.getActiveBits())
8331 // Check to see if the constant is equivalent to a negative value
8333 if (S.Context.getIntWidth(ConstantT) ==
8334 S.Context.getIntWidth(CommonT) &&
8335 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8337 // The constant value rests between values that OtherT can represent
8338 // after conversion. Relational comparison still works, but equality
8339 // comparisons will be tautological.
8340 EqualityOnly = true;
8344 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8346 if (op == BO_EQ || op == BO_NE) {
8347 IsTrue = op == BO_NE;
8348 } else if (EqualityOnly) {
8350 } else if (RhsConstant) {
8351 if (op == BO_GT || op == BO_GE)
8352 IsTrue = !PositiveConstant;
8353 else // op == BO_LT || op == BO_LE
8354 IsTrue = PositiveConstant;
8356 if (op == BO_LT || op == BO_LE)
8357 IsTrue = !PositiveConstant;
8358 else // op == BO_GT || op == BO_GE
8359 IsTrue = PositiveConstant;
8362 // Other isKnownToHaveBooleanValue
8363 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8364 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8365 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8367 static const struct LinkedConditions {
8368 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8369 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8370 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8371 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8372 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8373 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8376 // Constant on LHS. | Constant on RHS. |
8377 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8378 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8379 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8380 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8381 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8382 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8383 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8386 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8388 enum ConstantValue ConstVal = Zero;
8389 if (Value.isUnsigned() || Value.isNonNegative()) {
8391 LiteralOrBoolConstant =
8392 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8394 } else if (Value == 1) {
8395 LiteralOrBoolConstant =
8396 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8399 LiteralOrBoolConstant = LiteralConstant;
8406 CompareBoolWithConstantResult CmpRes;
8410 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8413 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8416 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8419 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8422 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8425 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8432 if (CmpRes == AFals) {
8434 } else if (CmpRes == ATrue) {
8441 // If this is a comparison to an enum constant, include that
8442 // constant in the diagnostic.
8443 const EnumConstantDecl *ED = nullptr;
8444 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8445 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8447 SmallString<64> PrettySourceValue;
8448 llvm::raw_svector_ostream OS(PrettySourceValue);
8450 OS << '\'' << *ED << "' (" << Value << ")";
8454 S.DiagRuntimeBehavior(
8455 E->getOperatorLoc(), E,
8456 S.PDiag(diag::warn_out_of_range_compare)
8457 << OS.str() << LiteralOrBoolConstant
8458 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8459 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8462 /// Analyze the operands of the given comparison. Implements the
8463 /// fallback case from AnalyzeComparison.
8464 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8465 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8466 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8469 /// \brief Implements -Wsign-compare.
8471 /// \param E the binary operator to check for warnings
8472 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8473 // The type the comparison is being performed in.
8474 QualType T = E->getLHS()->getType();
8476 // Only analyze comparison operators where both sides have been converted to
8478 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8479 return AnalyzeImpConvsInComparison(S, E);
8481 // Don't analyze value-dependent comparisons directly.
8482 if (E->isValueDependent())
8483 return AnalyzeImpConvsInComparison(S, E);
8485 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8486 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8488 bool IsComparisonConstant = false;
8490 // Check whether an integer constant comparison results in a value
8491 // of 'true' or 'false'.
8492 if (T->isIntegralType(S.Context)) {
8493 llvm::APSInt RHSValue;
8494 bool IsRHSIntegralLiteral =
8495 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8496 llvm::APSInt LHSValue;
8497 bool IsLHSIntegralLiteral =
8498 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8499 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8500 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8501 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8502 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8504 IsComparisonConstant =
8505 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8506 } else if (!T->hasUnsignedIntegerRepresentation())
8507 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8509 // We don't do anything special if this isn't an unsigned integral
8510 // comparison: we're only interested in integral comparisons, and
8511 // signed comparisons only happen in cases we don't care to warn about.
8513 // We also don't care about value-dependent expressions or expressions
8514 // whose result is a constant.
8515 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8516 return AnalyzeImpConvsInComparison(S, E);
8518 // Check to see if one of the (unmodified) operands is of different
8520 Expr *signedOperand, *unsignedOperand;
8521 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8522 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8523 "unsigned comparison between two signed integer expressions?");
8524 signedOperand = LHS;
8525 unsignedOperand = RHS;
8526 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8527 signedOperand = RHS;
8528 unsignedOperand = LHS;
8530 CheckTrivialUnsignedComparison(S, E);
8531 return AnalyzeImpConvsInComparison(S, E);
8534 // Otherwise, calculate the effective range of the signed operand.
8535 IntRange signedRange = GetExprRange(S.Context, signedOperand);
8537 // Go ahead and analyze implicit conversions in the operands. Note
8538 // that we skip the implicit conversions on both sides.
8539 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8540 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8542 // If the signed range is non-negative, -Wsign-compare won't fire,
8543 // but we should still check for comparisons which are always true
8545 if (signedRange.NonNegative)
8546 return CheckTrivialUnsignedComparison(S, E);
8548 // For (in)equality comparisons, if the unsigned operand is a
8549 // constant which cannot collide with a overflowed signed operand,
8550 // then reinterpreting the signed operand as unsigned will not
8551 // change the result of the comparison.
8552 if (E->isEqualityOp()) {
8553 unsigned comparisonWidth = S.Context.getIntWidth(T);
8554 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8556 // We should never be unable to prove that the unsigned operand is
8558 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8560 if (unsignedRange.Width < comparisonWidth)
8564 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8565 S.PDiag(diag::warn_mixed_sign_comparison)
8566 << LHS->getType() << RHS->getType()
8567 << LHS->getSourceRange() << RHS->getSourceRange());
8570 /// Analyzes an attempt to assign the given value to a bitfield.
8572 /// Returns true if there was something fishy about the attempt.
8573 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8574 SourceLocation InitLoc) {
8575 assert(Bitfield->isBitField());
8576 if (Bitfield->isInvalidDecl())
8579 // White-list bool bitfields.
8580 QualType BitfieldType = Bitfield->getType();
8581 if (BitfieldType->isBooleanType())
8584 if (BitfieldType->isEnumeralType()) {
8585 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8586 // If the underlying enum type was not explicitly specified as an unsigned
8587 // type and the enum contain only positive values, MSVC++ will cause an
8588 // inconsistency by storing this as a signed type.
8589 if (S.getLangOpts().CPlusPlus11 &&
8590 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8591 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8592 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8593 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8594 << BitfieldEnumDecl->getNameAsString();
8598 if (Bitfield->getType()->isBooleanType())
8601 // Ignore value- or type-dependent expressions.
8602 if (Bitfield->getBitWidth()->isValueDependent() ||
8603 Bitfield->getBitWidth()->isTypeDependent() ||
8604 Init->isValueDependent() ||
8605 Init->isTypeDependent())
8608 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8611 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
8614 unsigned OriginalWidth = Value.getBitWidth();
8615 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8617 if (!Value.isSigned() || Value.isNegative())
8618 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8619 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8620 OriginalWidth = Value.getMinSignedBits();
8622 if (OriginalWidth <= FieldWidth)
8625 // Compute the value which the bitfield will contain.
8626 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8627 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
8629 // Check whether the stored value is equal to the original value.
8630 TruncatedValue = TruncatedValue.extend(OriginalWidth);
8631 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8634 // Special-case bitfields of width 1: booleans are naturally 0/1, and
8635 // therefore don't strictly fit into a signed bitfield of width 1.
8636 if (FieldWidth == 1 && Value == 1)
8639 std::string PrettyValue = Value.toString(10);
8640 std::string PrettyTrunc = TruncatedValue.toString(10);
8642 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8643 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8644 << Init->getSourceRange();
8649 /// Analyze the given simple or compound assignment for warning-worthy
8651 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8652 // Just recurse on the LHS.
8653 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8655 // We want to recurse on the RHS as normal unless we're assigning to
8657 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8658 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8659 E->getOperatorLoc())) {
8660 // Recurse, ignoring any implicit conversions on the RHS.
8661 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8662 E->getOperatorLoc());
8666 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8669 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
8670 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8671 SourceLocation CContext, unsigned diag,
8672 bool pruneControlFlow = false) {
8673 if (pruneControlFlow) {
8674 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8676 << SourceType << T << E->getSourceRange()
8677 << SourceRange(CContext));
8680 S.Diag(E->getExprLoc(), diag)
8681 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8684 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
8685 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8686 unsigned diag, bool pruneControlFlow = false) {
8687 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8691 /// Diagnose an implicit cast from a floating point value to an integer value.
8692 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8694 SourceLocation CContext) {
8695 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8696 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8698 Expr *InnerE = E->IgnoreParenImpCasts();
8699 // We also want to warn on, e.g., "int i = -1.234"
8700 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8701 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8702 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8704 const bool IsLiteral =
8705 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8707 llvm::APFloat Value(0.0);
8709 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8711 return DiagnoseImpCast(S, E, T, CContext,
8712 diag::warn_impcast_float_integer, PruneWarnings);
8715 bool isExact = false;
8717 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8718 T->hasUnsignedIntegerRepresentation());
8719 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8720 &isExact) == llvm::APFloat::opOK &&
8722 if (IsLiteral) return;
8723 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8727 unsigned DiagID = 0;
8729 // Warn on floating point literal to integer.
8730 DiagID = diag::warn_impcast_literal_float_to_integer;
8731 } else if (IntegerValue == 0) {
8732 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8733 return DiagnoseImpCast(S, E, T, CContext,
8734 diag::warn_impcast_float_integer, PruneWarnings);
8736 // Warn on non-zero to zero conversion.
8737 DiagID = diag::warn_impcast_float_to_integer_zero;
8739 if (IntegerValue.isUnsigned()) {
8740 if (!IntegerValue.isMaxValue()) {
8741 return DiagnoseImpCast(S, E, T, CContext,
8742 diag::warn_impcast_float_integer, PruneWarnings);
8744 } else { // IntegerValue.isSigned()
8745 if (!IntegerValue.isMaxSignedValue() &&
8746 !IntegerValue.isMinSignedValue()) {
8747 return DiagnoseImpCast(S, E, T, CContext,
8748 diag::warn_impcast_float_integer, PruneWarnings);
8751 // Warn on evaluatable floating point expression to integer conversion.
8752 DiagID = diag::warn_impcast_float_to_integer;
8755 // FIXME: Force the precision of the source value down so we don't print
8756 // digits which are usually useless (we don't really care here if we
8757 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8758 // would automatically print the shortest representation, but it's a bit
8759 // tricky to implement.
8760 SmallString<16> PrettySourceValue;
8761 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8762 precision = (precision * 59 + 195) / 196;
8763 Value.toString(PrettySourceValue, precision);
8765 SmallString<16> PrettyTargetValue;
8767 PrettyTargetValue = Value.isZero() ? "false" : "true";
8769 IntegerValue.toString(PrettyTargetValue);
8771 if (PruneWarnings) {
8772 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8774 << E->getType() << T.getUnqualifiedType()
8775 << PrettySourceValue << PrettyTargetValue
8776 << E->getSourceRange() << SourceRange(CContext));
8778 S.Diag(E->getExprLoc(), DiagID)
8779 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8780 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8784 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8785 if (!Range.Width) return "0";
8787 llvm::APSInt ValueInRange = Value;
8788 ValueInRange.setIsSigned(!Range.NonNegative);
8789 ValueInRange = ValueInRange.trunc(Range.Width);
8790 return ValueInRange.toString(10);
8793 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
8794 if (!isa<ImplicitCastExpr>(Ex))
8797 Expr *InnerE = Ex->IgnoreParenImpCasts();
8798 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8799 const Type *Source =
8800 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8801 if (Target->isDependentType())
8804 const BuiltinType *FloatCandidateBT =
8805 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8806 const Type *BoolCandidateType = ToBool ? Target : Source;
8808 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8809 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8812 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8813 SourceLocation CC) {
8814 unsigned NumArgs = TheCall->getNumArgs();
8815 for (unsigned i = 0; i < NumArgs; ++i) {
8816 Expr *CurrA = TheCall->getArg(i);
8817 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8820 bool IsSwapped = ((i > 0) &&
8821 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8822 IsSwapped |= ((i < (NumArgs - 1)) &&
8823 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8825 // Warn on this floating-point to bool conversion.
8826 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8827 CurrA->getType(), CC,
8828 diag::warn_impcast_floating_point_to_bool);
8833 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
8834 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8838 // Don't warn on functions which have return type nullptr_t.
8839 if (isa<CallExpr>(E))
8842 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8843 const Expr::NullPointerConstantKind NullKind =
8844 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8845 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8848 // Return if target type is a safe conversion.
8849 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8850 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8853 SourceLocation Loc = E->getSourceRange().getBegin();
8855 // Venture through the macro stacks to get to the source of macro arguments.
8856 // The new location is a better location than the complete location that was
8858 while (S.SourceMgr.isMacroArgExpansion(Loc))
8859 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8861 while (S.SourceMgr.isMacroArgExpansion(CC))
8862 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8864 // __null is usually wrapped in a macro. Go up a macro if that is the case.
8865 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8866 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8867 Loc, S.SourceMgr, S.getLangOpts());
8868 if (MacroName == "NULL")
8869 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
8872 // Only warn if the null and context location are in the same macro expansion.
8873 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8876 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8877 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8878 << FixItHint::CreateReplacement(Loc,
8879 S.getFixItZeroLiteralForType(T, Loc));
8882 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8883 ObjCArrayLiteral *ArrayLiteral);
8884 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8885 ObjCDictionaryLiteral *DictionaryLiteral);
8887 /// Check a single element within a collection literal against the
8888 /// target element type.
8889 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8890 Expr *Element, unsigned ElementKind) {
8891 // Skip a bitcast to 'id' or qualified 'id'.
8892 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8893 if (ICE->getCastKind() == CK_BitCast &&
8894 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8895 Element = ICE->getSubExpr();
8898 QualType ElementType = Element->getType();
8899 ExprResult ElementResult(Element);
8900 if (ElementType->getAs<ObjCObjectPointerType>() &&
8901 S.CheckSingleAssignmentConstraints(TargetElementType,
8904 != Sema::Compatible) {
8905 S.Diag(Element->getLocStart(),
8906 diag::warn_objc_collection_literal_element)
8907 << ElementType << ElementKind << TargetElementType
8908 << Element->getSourceRange();
8911 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8912 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8913 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8914 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8917 /// Check an Objective-C array literal being converted to the given
8919 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8920 ObjCArrayLiteral *ArrayLiteral) {
8924 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8928 if (TargetObjCPtr->isUnspecialized() ||
8929 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8930 != S.NSArrayDecl->getCanonicalDecl())
8933 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8934 if (TypeArgs.size() != 1)
8937 QualType TargetElementType = TypeArgs[0];
8938 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8939 checkObjCCollectionLiteralElement(S, TargetElementType,
8940 ArrayLiteral->getElement(I),
8945 /// Check an Objective-C dictionary literal being converted to the given
8947 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8948 ObjCDictionaryLiteral *DictionaryLiteral) {
8949 if (!S.NSDictionaryDecl)
8952 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8956 if (TargetObjCPtr->isUnspecialized() ||
8957 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8958 != S.NSDictionaryDecl->getCanonicalDecl())
8961 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8962 if (TypeArgs.size() != 2)
8965 QualType TargetKeyType = TypeArgs[0];
8966 QualType TargetObjectType = TypeArgs[1];
8967 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8968 auto Element = DictionaryLiteral->getKeyValueElement(I);
8969 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8970 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8974 // Helper function to filter out cases for constant width constant conversion.
8975 // Don't warn on char array initialization or for non-decimal values.
8976 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8977 SourceLocation CC) {
8978 // If initializing from a constant, and the constant starts with '0',
8979 // then it is a binary, octal, or hexadecimal. Allow these constants
8980 // to fill all the bits, even if there is a sign change.
8981 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8982 const char FirstLiteralCharacter =
8983 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8984 if (FirstLiteralCharacter == '0')
8988 // If the CC location points to a '{', and the type is char, then assume
8989 // assume it is an array initialization.
8990 if (CC.isValid() && T->isCharType()) {
8991 const char FirstContextCharacter =
8992 S.getSourceManager().getCharacterData(CC)[0];
8993 if (FirstContextCharacter == '{')
9000 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
9001 SourceLocation CC, bool *ICContext = nullptr) {
9002 if (E->isTypeDependent() || E->isValueDependent()) return;
9004 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9005 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9006 if (Source == Target) return;
9007 if (Target->isDependentType()) return;
9009 // If the conversion context location is invalid don't complain. We also
9010 // don't want to emit a warning if the issue occurs from the expansion of
9011 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9012 // delay this check as long as possible. Once we detect we are in that
9013 // scenario, we just return.
9017 // Diagnose implicit casts to bool.
9018 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9019 if (isa<StringLiteral>(E))
9020 // Warn on string literal to bool. Checks for string literals in logical
9021 // and expressions, for instance, assert(0 && "error here"), are
9022 // prevented by a check in AnalyzeImplicitConversions().
9023 return DiagnoseImpCast(S, E, T, CC,
9024 diag::warn_impcast_string_literal_to_bool);
9025 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9026 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9027 // This covers the literal expressions that evaluate to Objective-C
9029 return DiagnoseImpCast(S, E, T, CC,
9030 diag::warn_impcast_objective_c_literal_to_bool);
9032 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9033 // Warn on pointer to bool conversion that is always true.
9034 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9039 // Check implicit casts from Objective-C collection literals to specialized
9040 // collection types, e.g., NSArray<NSString *> *.
9041 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9042 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9043 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9044 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9046 // Strip vector types.
9047 if (isa<VectorType>(Source)) {
9048 if (!isa<VectorType>(Target)) {
9049 if (S.SourceMgr.isInSystemMacro(CC))
9051 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9054 // If the vector cast is cast between two vectors of the same size, it is
9055 // a bitcast, not a conversion.
9056 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9059 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9060 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9062 if (auto VecTy = dyn_cast<VectorType>(Target))
9063 Target = VecTy->getElementType().getTypePtr();
9065 // Strip complex types.
9066 if (isa<ComplexType>(Source)) {
9067 if (!isa<ComplexType>(Target)) {
9068 if (S.SourceMgr.isInSystemMacro(CC))
9071 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
9074 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9075 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9078 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9079 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9081 // If the source is floating point...
9082 if (SourceBT && SourceBT->isFloatingPoint()) {
9083 // ...and the target is floating point...
9084 if (TargetBT && TargetBT->isFloatingPoint()) {
9085 // ...then warn if we're dropping FP rank.
9087 // Builtin FP kinds are ordered by increasing FP rank.
9088 if (SourceBT->getKind() > TargetBT->getKind()) {
9089 // Don't warn about float constants that are precisely
9090 // representable in the target type.
9091 Expr::EvalResult result;
9092 if (E->EvaluateAsRValue(result, S.Context)) {
9093 // Value might be a float, a float vector, or a float complex.
9094 if (IsSameFloatAfterCast(result.Val,
9095 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9096 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9100 if (S.SourceMgr.isInSystemMacro(CC))
9103 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9105 // ... or possibly if we're increasing rank, too
9106 else if (TargetBT->getKind() > SourceBT->getKind()) {
9107 if (S.SourceMgr.isInSystemMacro(CC))
9110 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9115 // If the target is integral, always warn.
9116 if (TargetBT && TargetBT->isInteger()) {
9117 if (S.SourceMgr.isInSystemMacro(CC))
9120 DiagnoseFloatingImpCast(S, E, T, CC);
9123 // Detect the case where a call result is converted from floating-point to
9124 // to bool, and the final argument to the call is converted from bool, to
9125 // discover this typo:
9127 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9129 // FIXME: This is an incredibly special case; is there some more general
9130 // way to detect this class of misplaced-parentheses bug?
9131 if (Target->isBooleanType() && isa<CallExpr>(E)) {
9132 // Check last argument of function call to see if it is an
9133 // implicit cast from a type matching the type the result
9134 // is being cast to.
9135 CallExpr *CEx = cast<CallExpr>(E);
9136 if (unsigned NumArgs = CEx->getNumArgs()) {
9137 Expr *LastA = CEx->getArg(NumArgs - 1);
9138 Expr *InnerE = LastA->IgnoreParenImpCasts();
9139 if (isa<ImplicitCastExpr>(LastA) &&
9140 InnerE->getType()->isBooleanType()) {
9141 // Warn on this floating-point to bool conversion
9142 DiagnoseImpCast(S, E, T, CC,
9143 diag::warn_impcast_floating_point_to_bool);
9150 DiagnoseNullConversion(S, E, T, CC);
9152 S.DiscardMisalignedMemberAddress(Target, E);
9154 if (!Source->isIntegerType() || !Target->isIntegerType())
9157 // TODO: remove this early return once the false positives for constant->bool
9158 // in templates, macros, etc, are reduced or removed.
9159 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9162 IntRange SourceRange = GetExprRange(S.Context, E);
9163 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9165 if (SourceRange.Width > TargetRange.Width) {
9166 // If the source is a constant, use a default-on diagnostic.
9167 // TODO: this should happen for bitfield stores, too.
9168 llvm::APSInt Value(32);
9169 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9170 if (S.SourceMgr.isInSystemMacro(CC))
9173 std::string PrettySourceValue = Value.toString(10);
9174 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9176 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9177 S.PDiag(diag::warn_impcast_integer_precision_constant)
9178 << PrettySourceValue << PrettyTargetValue
9179 << E->getType() << T << E->getSourceRange()
9180 << clang::SourceRange(CC));
9184 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9185 if (S.SourceMgr.isInSystemMacro(CC))
9188 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9189 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9190 /* pruneControlFlow */ true);
9191 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9194 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9195 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9196 // Warn when doing a signed to signed conversion, warn if the positive
9197 // source value is exactly the width of the target type, which will
9198 // cause a negative value to be stored.
9201 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9202 !S.SourceMgr.isInSystemMacro(CC)) {
9203 if (isSameWidthConstantConversion(S, E, T, CC)) {
9204 std::string PrettySourceValue = Value.toString(10);
9205 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9207 S.DiagRuntimeBehavior(
9209 S.PDiag(diag::warn_impcast_integer_precision_constant)
9210 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9211 << E->getSourceRange() << clang::SourceRange(CC));
9216 // Fall through for non-constants to give a sign conversion warning.
9219 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9220 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9221 SourceRange.Width == TargetRange.Width)) {
9222 if (S.SourceMgr.isInSystemMacro(CC))
9225 unsigned DiagID = diag::warn_impcast_integer_sign;
9227 // Traditionally, gcc has warned about this under -Wsign-compare.
9228 // We also want to warn about it in -Wconversion.
9229 // So if -Wconversion is off, use a completely identical diagnostic
9230 // in the sign-compare group.
9231 // The conditional-checking code will
9233 DiagID = diag::warn_impcast_integer_sign_conditional;
9237 return DiagnoseImpCast(S, E, T, CC, DiagID);
9240 // Diagnose conversions between different enumeration types.
9241 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9242 // type, to give us better diagnostics.
9243 QualType SourceType = E->getType();
9244 if (!S.getLangOpts().CPlusPlus) {
9245 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9246 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9247 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9248 SourceType = S.Context.getTypeDeclType(Enum);
9249 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9253 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9254 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9255 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9256 TargetEnum->getDecl()->hasNameForLinkage() &&
9257 SourceEnum != TargetEnum) {
9258 if (S.SourceMgr.isInSystemMacro(CC))
9261 return DiagnoseImpCast(S, E, SourceType, T, CC,
9262 diag::warn_impcast_different_enum_types);
9266 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9267 SourceLocation CC, QualType T);
9269 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9270 SourceLocation CC, bool &ICContext) {
9271 E = E->IgnoreParenImpCasts();
9273 if (isa<ConditionalOperator>(E))
9274 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9276 AnalyzeImplicitConversions(S, E, CC);
9277 if (E->getType() != T)
9278 return CheckImplicitConversion(S, E, T, CC, &ICContext);
9281 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9282 SourceLocation CC, QualType T) {
9283 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9285 bool Suspicious = false;
9286 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9287 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9289 // If -Wconversion would have warned about either of the candidates
9290 // for a signedness conversion to the context type...
9291 if (!Suspicious) return;
9293 // ...but it's currently ignored...
9294 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9297 // ...then check whether it would have warned about either of the
9298 // candidates for a signedness conversion to the condition type.
9299 if (E->getType() == T) return;
9302 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9303 E->getType(), CC, &Suspicious);
9305 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9306 E->getType(), CC, &Suspicious);
9309 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9310 /// Input argument E is a logical expression.
9311 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9312 if (S.getLangOpts().Bool)
9314 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9317 /// AnalyzeImplicitConversions - Find and report any interesting
9318 /// implicit conversions in the given expression. There are a couple
9319 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9320 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9321 QualType T = OrigE->getType();
9322 Expr *E = OrigE->IgnoreParenImpCasts();
9324 if (E->isTypeDependent() || E->isValueDependent())
9327 // For conditional operators, we analyze the arguments as if they
9328 // were being fed directly into the output.
9329 if (isa<ConditionalOperator>(E)) {
9330 ConditionalOperator *CO = cast<ConditionalOperator>(E);
9331 CheckConditionalOperator(S, CO, CC, T);
9335 // Check implicit argument conversions for function calls.
9336 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9337 CheckImplicitArgumentConversions(S, Call, CC);
9339 // Go ahead and check any implicit conversions we might have skipped.
9340 // The non-canonical typecheck is just an optimization;
9341 // CheckImplicitConversion will filter out dead implicit conversions.
9342 if (E->getType() != T)
9343 CheckImplicitConversion(S, E, T, CC);
9345 // Now continue drilling into this expression.
9347 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9348 // The bound subexpressions in a PseudoObjectExpr are not reachable
9349 // as transitive children.
9350 // FIXME: Use a more uniform representation for this.
9351 for (auto *SE : POE->semantics())
9352 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9353 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9356 // Skip past explicit casts.
9357 if (isa<ExplicitCastExpr>(E)) {
9358 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9359 return AnalyzeImplicitConversions(S, E, CC);
9362 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9363 // Do a somewhat different check with comparison operators.
9364 if (BO->isComparisonOp())
9365 return AnalyzeComparison(S, BO);
9367 // And with simple assignments.
9368 if (BO->getOpcode() == BO_Assign)
9369 return AnalyzeAssignment(S, BO);
9372 // These break the otherwise-useful invariant below. Fortunately,
9373 // we don't really need to recurse into them, because any internal
9374 // expressions should have been analyzed already when they were
9375 // built into statements.
9376 if (isa<StmtExpr>(E)) return;
9378 // Don't descend into unevaluated contexts.
9379 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9381 // Now just recurse over the expression's children.
9382 CC = E->getExprLoc();
9383 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9384 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9385 for (Stmt *SubStmt : E->children()) {
9386 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9390 if (IsLogicalAndOperator &&
9391 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9392 // Ignore checking string literals that are in logical and operators.
9393 // This is a common pattern for asserts.
9395 AnalyzeImplicitConversions(S, ChildExpr, CC);
9398 if (BO && BO->isLogicalOp()) {
9399 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9400 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9401 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9403 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9404 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9405 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9408 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9409 if (U->getOpcode() == UO_LNot)
9410 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9413 } // end anonymous namespace
9415 /// Diagnose integer type and any valid implicit convertion to it.
9416 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9417 // Taking into account implicit conversions,
9418 // allow any integer.
9419 if (!E->getType()->isIntegerType()) {
9420 S.Diag(E->getLocStart(),
9421 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9424 // Potentially emit standard warnings for implicit conversions if enabled
9425 // using -Wconversion.
9426 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9430 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9431 // Returns true when emitting a warning about taking the address of a reference.
9432 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9433 const PartialDiagnostic &PD) {
9434 E = E->IgnoreParenImpCasts();
9436 const FunctionDecl *FD = nullptr;
9438 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9439 if (!DRE->getDecl()->getType()->isReferenceType())
9441 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9442 if (!M->getMemberDecl()->getType()->isReferenceType())
9444 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9445 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9447 FD = Call->getDirectCallee();
9452 SemaRef.Diag(E->getExprLoc(), PD);
9454 // If possible, point to location of function.
9456 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9462 // Returns true if the SourceLocation is expanded from any macro body.
9463 // Returns false if the SourceLocation is invalid, is from not in a macro
9464 // expansion, or is from expanded from a top-level macro argument.
9465 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9466 if (Loc.isInvalid())
9469 while (Loc.isMacroID()) {
9470 if (SM.isMacroBodyExpansion(Loc))
9472 Loc = SM.getImmediateMacroCallerLoc(Loc);
9478 /// \brief Diagnose pointers that are always non-null.
9479 /// \param E the expression containing the pointer
9480 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9481 /// compared to a null pointer
9482 /// \param IsEqual True when the comparison is equal to a null pointer
9483 /// \param Range Extra SourceRange to highlight in the diagnostic
9484 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9485 Expr::NullPointerConstantKind NullKind,
9486 bool IsEqual, SourceRange Range) {
9490 // Don't warn inside macros.
9491 if (E->getExprLoc().isMacroID()) {
9492 const SourceManager &SM = getSourceManager();
9493 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9494 IsInAnyMacroBody(SM, Range.getBegin()))
9497 E = E->IgnoreImpCasts();
9499 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9501 if (isa<CXXThisExpr>(E)) {
9502 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9503 : diag::warn_this_bool_conversion;
9504 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9508 bool IsAddressOf = false;
9510 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9511 if (UO->getOpcode() != UO_AddrOf)
9514 E = UO->getSubExpr();
9518 unsigned DiagID = IsCompare
9519 ? diag::warn_address_of_reference_null_compare
9520 : diag::warn_address_of_reference_bool_conversion;
9521 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9523 if (CheckForReference(*this, E, PD)) {
9528 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9529 bool IsParam = isa<NonNullAttr>(NonnullAttr);
9531 llvm::raw_string_ostream S(Str);
9532 E->printPretty(S, nullptr, getPrintingPolicy());
9533 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9534 : diag::warn_cast_nonnull_to_bool;
9535 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9536 << E->getSourceRange() << Range << IsEqual;
9537 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9540 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9541 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9542 if (auto *Callee = Call->getDirectCallee()) {
9543 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9544 ComplainAboutNonnullParamOrCall(A);
9550 // Expect to find a single Decl. Skip anything more complicated.
9551 ValueDecl *D = nullptr;
9552 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9554 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9555 D = M->getMemberDecl();
9558 // Weak Decls can be null.
9559 if (!D || D->isWeak())
9562 // Check for parameter decl with nonnull attribute
9563 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9564 if (getCurFunction() &&
9565 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9566 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9567 ComplainAboutNonnullParamOrCall(A);
9571 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9572 auto ParamIter = llvm::find(FD->parameters(), PV);
9573 assert(ParamIter != FD->param_end());
9574 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9576 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9577 if (!NonNull->args_size()) {
9578 ComplainAboutNonnullParamOrCall(NonNull);
9582 for (unsigned ArgNo : NonNull->args()) {
9583 if (ArgNo == ParamNo) {
9584 ComplainAboutNonnullParamOrCall(NonNull);
9593 QualType T = D->getType();
9594 const bool IsArray = T->isArrayType();
9595 const bool IsFunction = T->isFunctionType();
9597 // Address of function is used to silence the function warning.
9598 if (IsAddressOf && IsFunction) {
9603 if (!IsAddressOf && !IsFunction && !IsArray)
9606 // Pretty print the expression for the diagnostic.
9608 llvm::raw_string_ostream S(Str);
9609 E->printPretty(S, nullptr, getPrintingPolicy());
9611 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9612 : diag::warn_impcast_pointer_to_bool;
9619 DiagType = AddressOf;
9620 else if (IsFunction)
9621 DiagType = FunctionPointer;
9623 DiagType = ArrayPointer;
9625 llvm_unreachable("Could not determine diagnostic.");
9626 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9627 << Range << IsEqual;
9632 // Suggest '&' to silence the function warning.
9633 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9634 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9636 // Check to see if '()' fixit should be emitted.
9637 QualType ReturnType;
9638 UnresolvedSet<4> NonTemplateOverloads;
9639 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9640 if (ReturnType.isNull())
9644 // There are two cases here. If there is null constant, the only suggest
9645 // for a pointer return type. If the null is 0, then suggest if the return
9646 // type is a pointer or an integer type.
9647 if (!ReturnType->isPointerType()) {
9648 if (NullKind == Expr::NPCK_ZeroExpression ||
9649 NullKind == Expr::NPCK_ZeroLiteral) {
9650 if (!ReturnType->isIntegerType())
9656 } else { // !IsCompare
9657 // For function to bool, only suggest if the function pointer has bool
9659 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9662 Diag(E->getExprLoc(), diag::note_function_to_function_call)
9663 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9666 /// Diagnoses "dangerous" implicit conversions within the given
9667 /// expression (which is a full expression). Implements -Wconversion
9668 /// and -Wsign-compare.
9670 /// \param CC the "context" location of the implicit conversion, i.e.
9671 /// the most location of the syntactic entity requiring the implicit
9673 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9674 // Don't diagnose in unevaluated contexts.
9675 if (isUnevaluatedContext())
9678 // Don't diagnose for value- or type-dependent expressions.
9679 if (E->isTypeDependent() || E->isValueDependent())
9682 // Check for array bounds violations in cases where the check isn't triggered
9683 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9684 // ArraySubscriptExpr is on the RHS of a variable initialization.
9685 CheckArrayAccess(E);
9687 // This is not the right CC for (e.g.) a variable initialization.
9688 AnalyzeImplicitConversions(*this, E, CC);
9691 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9692 /// Input argument E is a logical expression.
9693 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9694 ::CheckBoolLikeConversion(*this, E, CC);
9697 /// Diagnose when expression is an integer constant expression and its evaluation
9698 /// results in integer overflow
9699 void Sema::CheckForIntOverflow (Expr *E) {
9700 // Use a work list to deal with nested struct initializers.
9701 SmallVector<Expr *, 2> Exprs(1, E);
9704 Expr *E = Exprs.pop_back_val();
9706 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9707 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9711 if (auto InitList = dyn_cast<InitListExpr>(E))
9712 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9713 } while (!Exprs.empty());
9717 /// \brief Visitor for expressions which looks for unsequenced operations on the
9719 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9720 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9722 /// \brief A tree of sequenced regions within an expression. Two regions are
9723 /// unsequenced if one is an ancestor or a descendent of the other. When we
9724 /// finish processing an expression with sequencing, such as a comma
9725 /// expression, we fold its tree nodes into its parent, since they are
9726 /// unsequenced with respect to nodes we will visit later.
9727 class SequenceTree {
9729 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9730 unsigned Parent : 31;
9731 unsigned Merged : 1;
9733 SmallVector<Value, 8> Values;
9736 /// \brief A region within an expression which may be sequenced with respect
9737 /// to some other region.
9739 explicit Seq(unsigned N) : Index(N) {}
9741 friend class SequenceTree;
9746 SequenceTree() { Values.push_back(Value(0)); }
9747 Seq root() const { return Seq(0); }
9749 /// \brief Create a new sequence of operations, which is an unsequenced
9750 /// subset of \p Parent. This sequence of operations is sequenced with
9751 /// respect to other children of \p Parent.
9752 Seq allocate(Seq Parent) {
9753 Values.push_back(Value(Parent.Index));
9754 return Seq(Values.size() - 1);
9757 /// \brief Merge a sequence of operations into its parent.
9759 Values[S.Index].Merged = true;
9762 /// \brief Determine whether two operations are unsequenced. This operation
9763 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9764 /// should have been merged into its parent as appropriate.
9765 bool isUnsequenced(Seq Cur, Seq Old) {
9766 unsigned C = representative(Cur.Index);
9767 unsigned Target = representative(Old.Index);
9768 while (C >= Target) {
9771 C = Values[C].Parent;
9777 /// \brief Pick a representative for a sequence.
9778 unsigned representative(unsigned K) {
9779 if (Values[K].Merged)
9780 // Perform path compression as we go.
9781 return Values[K].Parent = representative(Values[K].Parent);
9786 /// An object for which we can track unsequenced uses.
9787 typedef NamedDecl *Object;
9789 /// Different flavors of object usage which we track. We only track the
9790 /// least-sequenced usage of each kind.
9792 /// A read of an object. Multiple unsequenced reads are OK.
9794 /// A modification of an object which is sequenced before the value
9795 /// computation of the expression, such as ++n in C++.
9797 /// A modification of an object which is not sequenced before the value
9798 /// computation of the expression, such as n++.
9801 UK_Count = UK_ModAsSideEffect + 1
9805 Usage() : Use(nullptr), Seq() {}
9807 SequenceTree::Seq Seq;
9811 UsageInfo() : Diagnosed(false) {}
9812 Usage Uses[UK_Count];
9813 /// Have we issued a diagnostic for this variable already?
9816 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9819 /// Sequenced regions within the expression.
9821 /// Declaration modifications and references which we have seen.
9822 UsageInfoMap UsageMap;
9823 /// The region we are currently within.
9824 SequenceTree::Seq Region;
9825 /// Filled in with declarations which were modified as a side-effect
9826 /// (that is, post-increment operations).
9827 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9828 /// Expressions to check later. We defer checking these to reduce
9830 SmallVectorImpl<Expr *> &WorkList;
9832 /// RAII object wrapping the visitation of a sequenced subexpression of an
9833 /// expression. At the end of this process, the side-effects of the evaluation
9834 /// become sequenced with respect to the value computation of the result, so
9835 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9837 struct SequencedSubexpression {
9838 SequencedSubexpression(SequenceChecker &Self)
9839 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9840 Self.ModAsSideEffect = &ModAsSideEffect;
9842 ~SequencedSubexpression() {
9843 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9844 UsageInfo &U = Self.UsageMap[M.first];
9845 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9846 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9847 SideEffectUsage = M.second;
9849 Self.ModAsSideEffect = OldModAsSideEffect;
9852 SequenceChecker &Self;
9853 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9854 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9857 /// RAII object wrapping the visitation of a subexpression which we might
9858 /// choose to evaluate as a constant. If any subexpression is evaluated and
9859 /// found to be non-constant, this allows us to suppress the evaluation of
9860 /// the outer expression.
9861 class EvaluationTracker {
9863 EvaluationTracker(SequenceChecker &Self)
9864 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9865 Self.EvalTracker = this;
9867 ~EvaluationTracker() {
9868 Self.EvalTracker = Prev;
9870 Prev->EvalOK &= EvalOK;
9873 bool evaluate(const Expr *E, bool &Result) {
9874 if (!EvalOK || E->isValueDependent())
9876 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9881 SequenceChecker &Self;
9882 EvaluationTracker *Prev;
9886 /// \brief Find the object which is produced by the specified expression,
9888 Object getObject(Expr *E, bool Mod) const {
9889 E = E->IgnoreParenCasts();
9890 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9891 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9892 return getObject(UO->getSubExpr(), Mod);
9893 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9894 if (BO->getOpcode() == BO_Comma)
9895 return getObject(BO->getRHS(), Mod);
9896 if (Mod && BO->isAssignmentOp())
9897 return getObject(BO->getLHS(), Mod);
9898 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9899 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9900 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9901 return ME->getMemberDecl();
9902 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9903 // FIXME: If this is a reference, map through to its value.
9904 return DRE->getDecl();
9908 /// \brief Note that an object was modified or used by an expression.
9909 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9910 Usage &U = UI.Uses[UK];
9911 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9912 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9913 ModAsSideEffect->push_back(std::make_pair(O, U));
9918 /// \brief Check whether a modification or use conflicts with a prior usage.
9919 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9924 const Usage &U = UI.Uses[OtherKind];
9925 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9929 Expr *ModOrUse = Ref;
9930 if (OtherKind == UK_Use)
9931 std::swap(Mod, ModOrUse);
9933 SemaRef.Diag(Mod->getExprLoc(),
9934 IsModMod ? diag::warn_unsequenced_mod_mod
9935 : diag::warn_unsequenced_mod_use)
9936 << O << SourceRange(ModOrUse->getExprLoc());
9937 UI.Diagnosed = true;
9940 void notePreUse(Object O, Expr *Use) {
9941 UsageInfo &U = UsageMap[O];
9942 // Uses conflict with other modifications.
9943 checkUsage(O, U, Use, UK_ModAsValue, false);
9945 void notePostUse(Object O, Expr *Use) {
9946 UsageInfo &U = UsageMap[O];
9947 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9948 addUsage(U, O, Use, UK_Use);
9951 void notePreMod(Object O, Expr *Mod) {
9952 UsageInfo &U = UsageMap[O];
9953 // Modifications conflict with other modifications and with uses.
9954 checkUsage(O, U, Mod, UK_ModAsValue, true);
9955 checkUsage(O, U, Mod, UK_Use, false);
9957 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9958 UsageInfo &U = UsageMap[O];
9959 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9960 addUsage(U, O, Use, UK);
9964 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
9965 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9966 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9970 void VisitStmt(Stmt *S) {
9971 // Skip all statements which aren't expressions for now.
9974 void VisitExpr(Expr *E) {
9975 // By default, just recurse to evaluated subexpressions.
9979 void VisitCastExpr(CastExpr *E) {
9980 Object O = Object();
9981 if (E->getCastKind() == CK_LValueToRValue)
9982 O = getObject(E->getSubExpr(), false);
9991 void VisitBinComma(BinaryOperator *BO) {
9992 // C++11 [expr.comma]p1:
9993 // Every value computation and side effect associated with the left
9994 // expression is sequenced before every value computation and side
9995 // effect associated with the right expression.
9996 SequenceTree::Seq LHS = Tree.allocate(Region);
9997 SequenceTree::Seq RHS = Tree.allocate(Region);
9998 SequenceTree::Seq OldRegion = Region;
10001 SequencedSubexpression SeqLHS(*this);
10003 Visit(BO->getLHS());
10007 Visit(BO->getRHS());
10009 Region = OldRegion;
10011 // Forget that LHS and RHS are sequenced. They are both unsequenced
10012 // with respect to other stuff.
10017 void VisitBinAssign(BinaryOperator *BO) {
10018 // The modification is sequenced after the value computation of the LHS
10019 // and RHS, so check it before inspecting the operands and update the
10021 Object O = getObject(BO->getLHS(), true);
10023 return VisitExpr(BO);
10027 // C++11 [expr.ass]p7:
10028 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10031 // Therefore, for a compound assignment operator, O is considered used
10032 // everywhere except within the evaluation of E1 itself.
10033 if (isa<CompoundAssignOperator>(BO))
10036 Visit(BO->getLHS());
10038 if (isa<CompoundAssignOperator>(BO))
10039 notePostUse(O, BO);
10041 Visit(BO->getRHS());
10043 // C++11 [expr.ass]p1:
10044 // the assignment is sequenced [...] before the value computation of the
10045 // assignment expression.
10046 // C11 6.5.16/3 has no such rule.
10047 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10048 : UK_ModAsSideEffect);
10051 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10052 VisitBinAssign(CAO);
10055 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10056 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10057 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10058 Object O = getObject(UO->getSubExpr(), true);
10060 return VisitExpr(UO);
10063 Visit(UO->getSubExpr());
10064 // C++11 [expr.pre.incr]p1:
10065 // the expression ++x is equivalent to x+=1
10066 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10067 : UK_ModAsSideEffect);
10070 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10071 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10072 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10073 Object O = getObject(UO->getSubExpr(), true);
10075 return VisitExpr(UO);
10078 Visit(UO->getSubExpr());
10079 notePostMod(O, UO, UK_ModAsSideEffect);
10082 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10083 void VisitBinLOr(BinaryOperator *BO) {
10084 // The side-effects of the LHS of an '&&' are sequenced before the
10085 // value computation of the RHS, and hence before the value computation
10086 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10087 // as if they were unconditionally sequenced.
10088 EvaluationTracker Eval(*this);
10090 SequencedSubexpression Sequenced(*this);
10091 Visit(BO->getLHS());
10095 if (Eval.evaluate(BO->getLHS(), Result)) {
10097 Visit(BO->getRHS());
10099 // Check for unsequenced operations in the RHS, treating it as an
10100 // entirely separate evaluation.
10102 // FIXME: If there are operations in the RHS which are unsequenced
10103 // with respect to operations outside the RHS, and those operations
10104 // are unconditionally evaluated, diagnose them.
10105 WorkList.push_back(BO->getRHS());
10108 void VisitBinLAnd(BinaryOperator *BO) {
10109 EvaluationTracker Eval(*this);
10111 SequencedSubexpression Sequenced(*this);
10112 Visit(BO->getLHS());
10116 if (Eval.evaluate(BO->getLHS(), Result)) {
10118 Visit(BO->getRHS());
10120 WorkList.push_back(BO->getRHS());
10124 // Only visit the condition, unless we can be sure which subexpression will
10126 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10127 EvaluationTracker Eval(*this);
10129 SequencedSubexpression Sequenced(*this);
10130 Visit(CO->getCond());
10134 if (Eval.evaluate(CO->getCond(), Result))
10135 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10137 WorkList.push_back(CO->getTrueExpr());
10138 WorkList.push_back(CO->getFalseExpr());
10142 void VisitCallExpr(CallExpr *CE) {
10143 // C++11 [intro.execution]p15:
10144 // When calling a function [...], every value computation and side effect
10145 // associated with any argument expression, or with the postfix expression
10146 // designating the called function, is sequenced before execution of every
10147 // expression or statement in the body of the function [and thus before
10148 // the value computation of its result].
10149 SequencedSubexpression Sequenced(*this);
10150 Base::VisitCallExpr(CE);
10152 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10155 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10156 // This is a call, so all subexpressions are sequenced before the result.
10157 SequencedSubexpression Sequenced(*this);
10159 if (!CCE->isListInitialization())
10160 return VisitExpr(CCE);
10162 // In C++11, list initializations are sequenced.
10163 SmallVector<SequenceTree::Seq, 32> Elts;
10164 SequenceTree::Seq Parent = Region;
10165 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10166 E = CCE->arg_end();
10168 Region = Tree.allocate(Parent);
10169 Elts.push_back(Region);
10173 // Forget that the initializers are sequenced.
10175 for (unsigned I = 0; I < Elts.size(); ++I)
10176 Tree.merge(Elts[I]);
10179 void VisitInitListExpr(InitListExpr *ILE) {
10180 if (!SemaRef.getLangOpts().CPlusPlus11)
10181 return VisitExpr(ILE);
10183 // In C++11, list initializations are sequenced.
10184 SmallVector<SequenceTree::Seq, 32> Elts;
10185 SequenceTree::Seq Parent = Region;
10186 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10187 Expr *E = ILE->getInit(I);
10189 Region = Tree.allocate(Parent);
10190 Elts.push_back(Region);
10194 // Forget that the initializers are sequenced.
10196 for (unsigned I = 0; I < Elts.size(); ++I)
10197 Tree.merge(Elts[I]);
10200 } // end anonymous namespace
10202 void Sema::CheckUnsequencedOperations(Expr *E) {
10203 SmallVector<Expr *, 8> WorkList;
10204 WorkList.push_back(E);
10205 while (!WorkList.empty()) {
10206 Expr *Item = WorkList.pop_back_val();
10207 SequenceChecker(*this, Item, WorkList);
10211 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10212 bool IsConstexpr) {
10213 CheckImplicitConversions(E, CheckLoc);
10214 if (!E->isInstantiationDependent())
10215 CheckUnsequencedOperations(E);
10216 if (!IsConstexpr && !E->isValueDependent())
10217 CheckForIntOverflow(E);
10218 DiagnoseMisalignedMembers();
10221 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10222 FieldDecl *BitField,
10224 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10227 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10228 SourceLocation Loc) {
10229 if (!PType->isVariablyModifiedType())
10231 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10232 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10235 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10236 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10239 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10240 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10244 const ArrayType *AT = S.Context.getAsArrayType(PType);
10248 if (AT->getSizeModifier() != ArrayType::Star) {
10249 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10253 S.Diag(Loc, diag::err_array_star_in_function_definition);
10256 /// CheckParmsForFunctionDef - Check that the parameters of the given
10257 /// function are appropriate for the definition of a function. This
10258 /// takes care of any checks that cannot be performed on the
10259 /// declaration itself, e.g., that the types of each of the function
10260 /// parameters are complete.
10261 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10262 bool CheckParameterNames) {
10263 bool HasInvalidParm = false;
10264 for (ParmVarDecl *Param : Parameters) {
10265 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10266 // function declarator that is part of a function definition of
10267 // that function shall not have incomplete type.
10269 // This is also C++ [dcl.fct]p6.
10270 if (!Param->isInvalidDecl() &&
10271 RequireCompleteType(Param->getLocation(), Param->getType(),
10272 diag::err_typecheck_decl_incomplete_type)) {
10273 Param->setInvalidDecl();
10274 HasInvalidParm = true;
10277 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10278 // declaration of each parameter shall include an identifier.
10279 if (CheckParameterNames &&
10280 Param->getIdentifier() == nullptr &&
10281 !Param->isImplicit() &&
10282 !getLangOpts().CPlusPlus)
10283 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10286 // If the function declarator is not part of a definition of that
10287 // function, parameters may have incomplete type and may use the [*]
10288 // notation in their sequences of declarator specifiers to specify
10289 // variable length array types.
10290 QualType PType = Param->getOriginalType();
10291 // FIXME: This diagnostic should point the '[*]' if source-location
10292 // information is added for it.
10293 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10295 // MSVC destroys objects passed by value in the callee. Therefore a
10296 // function definition which takes such a parameter must be able to call the
10297 // object's destructor. However, we don't perform any direct access check
10299 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10301 .areArgsDestroyedLeftToRightInCallee()) {
10302 if (!Param->isInvalidDecl()) {
10303 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10304 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10305 if (!ClassDecl->isInvalidDecl() &&
10306 !ClassDecl->hasIrrelevantDestructor() &&
10307 !ClassDecl->isDependentContext()) {
10308 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10309 MarkFunctionReferenced(Param->getLocation(), Destructor);
10310 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10316 // Parameters with the pass_object_size attribute only need to be marked
10317 // constant at function definitions. Because we lack information about
10318 // whether we're on a declaration or definition when we're instantiating the
10319 // attribute, we need to check for constness here.
10320 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10321 if (!Param->getType().isConstQualified())
10322 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10323 << Attr->getSpelling() << 1;
10326 return HasInvalidParm;
10329 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10331 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10332 ASTContext &Context) {
10333 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10334 return Context.getDeclAlign(DRE->getDecl());
10336 if (const auto *ME = dyn_cast<MemberExpr>(E))
10337 return Context.getDeclAlign(ME->getMemberDecl());
10342 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10343 /// pointer cast increases the alignment requirements.
10344 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10345 // This is actually a lot of work to potentially be doing on every
10346 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10347 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10350 // Ignore dependent types.
10351 if (T->isDependentType() || Op->getType()->isDependentType())
10354 // Require that the destination be a pointer type.
10355 const PointerType *DestPtr = T->getAs<PointerType>();
10356 if (!DestPtr) return;
10358 // If the destination has alignment 1, we're done.
10359 QualType DestPointee = DestPtr->getPointeeType();
10360 if (DestPointee->isIncompleteType()) return;
10361 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10362 if (DestAlign.isOne()) return;
10364 // Require that the source be a pointer type.
10365 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10366 if (!SrcPtr) return;
10367 QualType SrcPointee = SrcPtr->getPointeeType();
10369 // Whitelist casts from cv void*. We already implicitly
10370 // whitelisted casts to cv void*, since they have alignment 1.
10371 // Also whitelist casts involving incomplete types, which implicitly
10372 // includes 'void'.
10373 if (SrcPointee->isIncompleteType()) return;
10375 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10377 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10378 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10379 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10380 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10381 if (UO->getOpcode() == UO_AddrOf)
10382 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10385 if (SrcAlign >= DestAlign) return;
10387 Diag(TRange.getBegin(), diag::warn_cast_align)
10388 << Op->getType() << T
10389 << static_cast<unsigned>(SrcAlign.getQuantity())
10390 << static_cast<unsigned>(DestAlign.getQuantity())
10391 << TRange << Op->getSourceRange();
10394 /// \brief Check whether this array fits the idiom of a size-one tail padded
10395 /// array member of a struct.
10397 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10398 /// commonly used to emulate flexible arrays in C89 code.
10399 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10400 const NamedDecl *ND) {
10401 if (Size != 1 || !ND) return false;
10403 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10404 if (!FD) return false;
10406 // Don't consider sizes resulting from macro expansions or template argument
10407 // substitution to form C89 tail-padded arrays.
10409 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10411 TypeLoc TL = TInfo->getTypeLoc();
10412 // Look through typedefs.
10413 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10414 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10415 TInfo = TDL->getTypeSourceInfo();
10418 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10419 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10420 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10426 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10427 if (!RD) return false;
10428 if (RD->isUnion()) return false;
10429 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10430 if (!CRD->isStandardLayout()) return false;
10433 // See if this is the last field decl in the record.
10434 const Decl *D = FD;
10435 while ((D = D->getNextDeclInContext()))
10436 if (isa<FieldDecl>(D))
10441 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10442 const ArraySubscriptExpr *ASE,
10443 bool AllowOnePastEnd, bool IndexNegated) {
10444 IndexExpr = IndexExpr->IgnoreParenImpCasts();
10445 if (IndexExpr->isValueDependent())
10448 const Type *EffectiveType =
10449 BaseExpr->getType()->getPointeeOrArrayElementType();
10450 BaseExpr = BaseExpr->IgnoreParenCasts();
10451 const ConstantArrayType *ArrayTy =
10452 Context.getAsConstantArrayType(BaseExpr->getType());
10456 llvm::APSInt index;
10457 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10462 const NamedDecl *ND = nullptr;
10463 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10464 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10465 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10466 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10468 if (index.isUnsigned() || !index.isNegative()) {
10469 llvm::APInt size = ArrayTy->getSize();
10470 if (!size.isStrictlyPositive())
10473 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10474 if (BaseType != EffectiveType) {
10475 // Make sure we're comparing apples to apples when comparing index to size
10476 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10477 uint64_t array_typesize = Context.getTypeSize(BaseType);
10478 // Handle ptrarith_typesize being zero, such as when casting to void*
10479 if (!ptrarith_typesize) ptrarith_typesize = 1;
10480 if (ptrarith_typesize != array_typesize) {
10481 // There's a cast to a different size type involved
10482 uint64_t ratio = array_typesize / ptrarith_typesize;
10483 // TODO: Be smarter about handling cases where array_typesize is not a
10484 // multiple of ptrarith_typesize
10485 if (ptrarith_typesize * ratio == array_typesize)
10486 size *= llvm::APInt(size.getBitWidth(), ratio);
10490 if (size.getBitWidth() > index.getBitWidth())
10491 index = index.zext(size.getBitWidth());
10492 else if (size.getBitWidth() < index.getBitWidth())
10493 size = size.zext(index.getBitWidth());
10495 // For array subscripting the index must be less than size, but for pointer
10496 // arithmetic also allow the index (offset) to be equal to size since
10497 // computing the next address after the end of the array is legal and
10498 // commonly done e.g. in C++ iterators and range-based for loops.
10499 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10502 // Also don't warn for arrays of size 1 which are members of some
10503 // structure. These are often used to approximate flexible arrays in C89
10505 if (IsTailPaddedMemberArray(*this, size, ND))
10508 // Suppress the warning if the subscript expression (as identified by the
10509 // ']' location) and the index expression are both from macro expansions
10510 // within a system header.
10512 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10513 ASE->getRBracketLoc());
10514 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10515 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10516 IndexExpr->getLocStart());
10517 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10522 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10524 DiagID = diag::warn_array_index_exceeds_bounds;
10526 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10527 PDiag(DiagID) << index.toString(10, true)
10528 << size.toString(10, true)
10529 << (unsigned)size.getLimitedValue(~0U)
10530 << IndexExpr->getSourceRange());
10532 unsigned DiagID = diag::warn_array_index_precedes_bounds;
10534 DiagID = diag::warn_ptr_arith_precedes_bounds;
10535 if (index.isNegative()) index = -index;
10538 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10539 PDiag(DiagID) << index.toString(10, true)
10540 << IndexExpr->getSourceRange());
10544 // Try harder to find a NamedDecl to point at in the note.
10545 while (const ArraySubscriptExpr *ASE =
10546 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10547 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10548 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10549 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10550 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10551 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10555 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10556 PDiag(diag::note_array_index_out_of_bounds)
10557 << ND->getDeclName());
10560 void Sema::CheckArrayAccess(const Expr *expr) {
10561 int AllowOnePastEnd = 0;
10563 expr = expr->IgnoreParenImpCasts();
10564 switch (expr->getStmtClass()) {
10565 case Stmt::ArraySubscriptExprClass: {
10566 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10567 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10568 AllowOnePastEnd > 0);
10571 case Stmt::OMPArraySectionExprClass: {
10572 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10573 if (ASE->getLowerBound())
10574 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10575 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10578 case Stmt::UnaryOperatorClass: {
10579 // Only unwrap the * and & unary operators
10580 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10581 expr = UO->getSubExpr();
10582 switch (UO->getOpcode()) {
10594 case Stmt::ConditionalOperatorClass: {
10595 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10596 if (const Expr *lhs = cond->getLHS())
10597 CheckArrayAccess(lhs);
10598 if (const Expr *rhs = cond->getRHS())
10599 CheckArrayAccess(rhs);
10608 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10611 struct RetainCycleOwner {
10612 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10615 SourceLocation Loc;
10618 void setLocsFrom(Expr *e) {
10619 Loc = e->getExprLoc();
10620 Range = e->getSourceRange();
10623 } // end anonymous namespace
10625 /// Consider whether capturing the given variable can possibly lead to
10626 /// a retain cycle.
10627 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10628 // In ARC, it's captured strongly iff the variable has __strong
10629 // lifetime. In MRR, it's captured strongly if the variable is
10630 // __block and has an appropriate type.
10631 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10634 owner.Variable = var;
10636 owner.setLocsFrom(ref);
10640 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10642 e = e->IgnoreParens();
10643 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10644 switch (cast->getCastKind()) {
10646 case CK_LValueBitCast:
10647 case CK_LValueToRValue:
10648 case CK_ARCReclaimReturnedObject:
10649 e = cast->getSubExpr();
10657 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10658 ObjCIvarDecl *ivar = ref->getDecl();
10659 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10662 // Try to find a retain cycle in the base.
10663 if (!findRetainCycleOwner(S, ref->getBase(), owner))
10666 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10667 owner.Indirect = true;
10671 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10672 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10673 if (!var) return false;
10674 return considerVariable(var, ref, owner);
10677 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10678 if (member->isArrow()) return false;
10680 // Don't count this as an indirect ownership.
10681 e = member->getBase();
10685 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10686 // Only pay attention to pseudo-objects on property references.
10687 ObjCPropertyRefExpr *pre
10688 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10690 if (!pre) return false;
10691 if (pre->isImplicitProperty()) return false;
10692 ObjCPropertyDecl *property = pre->getExplicitProperty();
10693 if (!property->isRetaining() &&
10694 !(property->getPropertyIvarDecl() &&
10695 property->getPropertyIvarDecl()->getType()
10696 .getObjCLifetime() == Qualifiers::OCL_Strong))
10699 owner.Indirect = true;
10700 if (pre->isSuperReceiver()) {
10701 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10702 if (!owner.Variable)
10704 owner.Loc = pre->getLocation();
10705 owner.Range = pre->getSourceRange();
10708 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10709 ->getSourceExpr());
10720 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10721 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10722 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10723 Context(Context), Variable(variable), Capturer(nullptr),
10724 VarWillBeReased(false) {}
10725 ASTContext &Context;
10728 bool VarWillBeReased;
10730 void VisitDeclRefExpr(DeclRefExpr *ref) {
10731 if (ref->getDecl() == Variable && !Capturer)
10735 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10736 if (Capturer) return;
10737 Visit(ref->getBase());
10738 if (Capturer && ref->isFreeIvar())
10742 void VisitBlockExpr(BlockExpr *block) {
10743 // Look inside nested blocks
10744 if (block->getBlockDecl()->capturesVariable(Variable))
10745 Visit(block->getBlockDecl()->getBody());
10748 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10749 if (Capturer) return;
10750 if (OVE->getSourceExpr())
10751 Visit(OVE->getSourceExpr());
10753 void VisitBinaryOperator(BinaryOperator *BinOp) {
10754 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10756 Expr *LHS = BinOp->getLHS();
10757 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10758 if (DRE->getDecl() != Variable)
10760 if (Expr *RHS = BinOp->getRHS()) {
10761 RHS = RHS->IgnoreParenCasts();
10762 llvm::APSInt Value;
10764 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10769 } // end anonymous namespace
10771 /// Check whether the given argument is a block which captures a
10773 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10774 assert(owner.Variable && owner.Loc.isValid());
10776 e = e->IgnoreParenCasts();
10778 // Look through [^{...} copy] and Block_copy(^{...}).
10779 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10780 Selector Cmd = ME->getSelector();
10781 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10782 e = ME->getInstanceReceiver();
10785 e = e->IgnoreParenCasts();
10787 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10788 if (CE->getNumArgs() == 1) {
10789 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
10791 const IdentifierInfo *FnI = Fn->getIdentifier();
10792 if (FnI && FnI->isStr("_Block_copy")) {
10793 e = CE->getArg(0)->IgnoreParenCasts();
10799 BlockExpr *block = dyn_cast<BlockExpr>(e);
10800 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
10803 FindCaptureVisitor visitor(S.Context, owner.Variable);
10804 visitor.Visit(block->getBlockDecl()->getBody());
10805 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
10808 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10809 RetainCycleOwner &owner) {
10811 assert(owner.Variable && owner.Loc.isValid());
10813 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10814 << owner.Variable << capturer->getSourceRange();
10815 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10816 << owner.Indirect << owner.Range;
10819 /// Check for a keyword selector that starts with the word 'add' or
10821 static bool isSetterLikeSelector(Selector sel) {
10822 if (sel.isUnarySelector()) return false;
10824 StringRef str = sel.getNameForSlot(0);
10825 while (!str.empty() && str.front() == '_') str = str.substr(1);
10826 if (str.startswith("set"))
10827 str = str.substr(3);
10828 else if (str.startswith("add")) {
10829 // Specially whitelist 'addOperationWithBlock:'.
10830 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10832 str = str.substr(3);
10837 if (str.empty()) return true;
10838 return !isLowercase(str.front());
10841 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10842 ObjCMessageExpr *Message) {
10843 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10844 Message->getReceiverInterface(),
10845 NSAPI::ClassId_NSMutableArray);
10846 if (!IsMutableArray) {
10850 Selector Sel = Message->getSelector();
10852 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10853 S.NSAPIObj->getNSArrayMethodKind(Sel);
10858 NSAPI::NSArrayMethodKind MK = *MKOpt;
10861 case NSAPI::NSMutableArr_addObject:
10862 case NSAPI::NSMutableArr_insertObjectAtIndex:
10863 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10865 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10876 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10877 ObjCMessageExpr *Message) {
10878 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10879 Message->getReceiverInterface(),
10880 NSAPI::ClassId_NSMutableDictionary);
10881 if (!IsMutableDictionary) {
10885 Selector Sel = Message->getSelector();
10887 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10888 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10893 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10896 case NSAPI::NSMutableDict_setObjectForKey:
10897 case NSAPI::NSMutableDict_setValueForKey:
10898 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10908 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
10909 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10910 Message->getReceiverInterface(),
10911 NSAPI::ClassId_NSMutableSet);
10913 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10914 Message->getReceiverInterface(),
10915 NSAPI::ClassId_NSMutableOrderedSet);
10916 if (!IsMutableSet && !IsMutableOrderedSet) {
10920 Selector Sel = Message->getSelector();
10922 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10927 NSAPI::NSSetMethodKind MK = *MKOpt;
10930 case NSAPI::NSMutableSet_addObject:
10931 case NSAPI::NSOrderedSet_setObjectAtIndex:
10932 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10933 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10935 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10942 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10943 if (!Message->isInstanceMessage()) {
10947 Optional<int> ArgOpt;
10949 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10950 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10951 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10955 int ArgIndex = *ArgOpt;
10957 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10958 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10959 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10962 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10963 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10964 if (ArgRE->isObjCSelfExpr()) {
10965 Diag(Message->getSourceRange().getBegin(),
10966 diag::warn_objc_circular_container)
10967 << ArgRE->getDecl()->getName() << StringRef("super");
10971 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10973 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10974 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10977 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10978 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10979 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10980 ValueDecl *Decl = ReceiverRE->getDecl();
10981 Diag(Message->getSourceRange().getBegin(),
10982 diag::warn_objc_circular_container)
10983 << Decl->getName() << Decl->getName();
10984 if (!ArgRE->isObjCSelfExpr()) {
10985 Diag(Decl->getLocation(),
10986 diag::note_objc_circular_container_declared_here)
10987 << Decl->getName();
10991 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10992 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10993 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10994 ObjCIvarDecl *Decl = IvarRE->getDecl();
10995 Diag(Message->getSourceRange().getBegin(),
10996 diag::warn_objc_circular_container)
10997 << Decl->getName() << Decl->getName();
10998 Diag(Decl->getLocation(),
10999 diag::note_objc_circular_container_declared_here)
11000 << Decl->getName();
11007 /// Check a message send to see if it's likely to cause a retain cycle.
11008 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11009 // Only check instance methods whose selector looks like a setter.
11010 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11013 // Try to find a variable that the receiver is strongly owned by.
11014 RetainCycleOwner owner;
11015 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11016 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11019 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11020 owner.Variable = getCurMethodDecl()->getSelfDecl();
11021 owner.Loc = msg->getSuperLoc();
11022 owner.Range = msg->getSuperLoc();
11025 // Check whether the receiver is captured by any of the arguments.
11026 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11027 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11028 return diagnoseRetainCycle(*this, capturer, owner);
11031 /// Check a property assign to see if it's likely to cause a retain cycle.
11032 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11033 RetainCycleOwner owner;
11034 if (!findRetainCycleOwner(*this, receiver, owner))
11037 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11038 diagnoseRetainCycle(*this, capturer, owner);
11041 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11042 RetainCycleOwner Owner;
11043 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11046 // Because we don't have an expression for the variable, we have to set the
11047 // location explicitly here.
11048 Owner.Loc = Var->getLocation();
11049 Owner.Range = Var->getSourceRange();
11051 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11052 diagnoseRetainCycle(*this, Capturer, Owner);
11055 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11056 Expr *RHS, bool isProperty) {
11057 // Check if RHS is an Objective-C object literal, which also can get
11058 // immediately zapped in a weak reference. Note that we explicitly
11059 // allow ObjCStringLiterals, since those are designed to never really die.
11060 RHS = RHS->IgnoreParenImpCasts();
11062 // This enum needs to match with the 'select' in
11063 // warn_objc_arc_literal_assign (off-by-1).
11064 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11065 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11068 S.Diag(Loc, diag::warn_arc_literal_assign)
11070 << (isProperty ? 0 : 1)
11071 << RHS->getSourceRange();
11076 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11077 Qualifiers::ObjCLifetime LT,
11078 Expr *RHS, bool isProperty) {
11079 // Strip off any implicit cast added to get to the one ARC-specific.
11080 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11081 if (cast->getCastKind() == CK_ARCConsumeObject) {
11082 S.Diag(Loc, diag::warn_arc_retained_assign)
11083 << (LT == Qualifiers::OCL_ExplicitNone)
11084 << (isProperty ? 0 : 1)
11085 << RHS->getSourceRange();
11088 RHS = cast->getSubExpr();
11091 if (LT == Qualifiers::OCL_Weak &&
11092 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11098 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11099 QualType LHS, Expr *RHS) {
11100 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11102 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11105 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11111 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11112 Expr *LHS, Expr *RHS) {
11114 // PropertyRef on LHS type need be directly obtained from
11115 // its declaration as it has a PseudoType.
11116 ObjCPropertyRefExpr *PRE
11117 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11118 if (PRE && !PRE->isImplicitProperty()) {
11119 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11121 LHSType = PD->getType();
11124 if (LHSType.isNull())
11125 LHSType = LHS->getType();
11127 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11129 if (LT == Qualifiers::OCL_Weak) {
11130 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11131 getCurFunction()->markSafeWeakUse(LHS);
11134 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11137 // FIXME. Check for other life times.
11138 if (LT != Qualifiers::OCL_None)
11142 if (PRE->isImplicitProperty())
11144 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11148 unsigned Attributes = PD->getPropertyAttributes();
11149 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11150 // when 'assign' attribute was not explicitly specified
11151 // by user, ignore it and rely on property type itself
11152 // for lifetime info.
11153 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11154 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11155 LHSType->isObjCRetainableType())
11158 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11159 if (cast->getCastKind() == CK_ARCConsumeObject) {
11160 Diag(Loc, diag::warn_arc_retained_property_assign)
11161 << RHS->getSourceRange();
11164 RHS = cast->getSubExpr();
11167 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11168 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11174 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11177 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11178 SourceLocation StmtLoc,
11179 const NullStmt *Body) {
11180 // Do not warn if the body is a macro that expands to nothing, e.g:
11186 if (Body->hasLeadingEmptyMacro())
11189 // Get line numbers of statement and body.
11190 bool StmtLineInvalid;
11191 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11193 if (StmtLineInvalid)
11196 bool BodyLineInvalid;
11197 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11199 if (BodyLineInvalid)
11202 // Warn if null statement and body are on the same line.
11203 if (StmtLine != BodyLine)
11208 } // end anonymous namespace
11210 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11213 // Since this is a syntactic check, don't emit diagnostic for template
11214 // instantiations, this just adds noise.
11215 if (CurrentInstantiationScope)
11218 // The body should be a null statement.
11219 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11223 // Do the usual checks.
11224 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11227 Diag(NBody->getSemiLoc(), DiagID);
11228 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11231 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11232 const Stmt *PossibleBody) {
11233 assert(!CurrentInstantiationScope); // Ensured by caller
11235 SourceLocation StmtLoc;
11238 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11239 StmtLoc = FS->getRParenLoc();
11240 Body = FS->getBody();
11241 DiagID = diag::warn_empty_for_body;
11242 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11243 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11244 Body = WS->getBody();
11245 DiagID = diag::warn_empty_while_body;
11247 return; // Neither `for' nor `while'.
11249 // The body should be a null statement.
11250 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11254 // Skip expensive checks if diagnostic is disabled.
11255 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11258 // Do the usual checks.
11259 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11262 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11263 // noise level low, emit diagnostics only if for/while is followed by a
11264 // CompoundStmt, e.g.:
11265 // for (int i = 0; i < n; i++);
11269 // or if for/while is followed by a statement with more indentation
11270 // than for/while itself:
11271 // for (int i = 0; i < n; i++);
11273 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11274 if (!ProbableTypo) {
11275 bool BodyColInvalid;
11276 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11277 PossibleBody->getLocStart(),
11279 if (BodyColInvalid)
11282 bool StmtColInvalid;
11283 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11286 if (StmtColInvalid)
11289 if (BodyCol > StmtCol)
11290 ProbableTypo = true;
11293 if (ProbableTypo) {
11294 Diag(NBody->getSemiLoc(), DiagID);
11295 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11299 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11301 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11302 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11303 SourceLocation OpLoc) {
11304 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11307 if (!ActiveTemplateInstantiations.empty())
11310 // Strip parens and casts away.
11311 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11312 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11314 // Check for a call expression
11315 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11316 if (!CE || CE->getNumArgs() != 1)
11319 // Check for a call to std::move
11320 const FunctionDecl *FD = CE->getDirectCallee();
11321 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11322 !FD->getIdentifier()->isStr("move"))
11325 // Get argument from std::move
11326 RHSExpr = CE->getArg(0);
11328 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11329 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11331 // Two DeclRefExpr's, check that the decls are the same.
11332 if (LHSDeclRef && RHSDeclRef) {
11333 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11335 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11336 RHSDeclRef->getDecl()->getCanonicalDecl())
11339 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11340 << LHSExpr->getSourceRange()
11341 << RHSExpr->getSourceRange();
11345 // Member variables require a different approach to check for self moves.
11346 // MemberExpr's are the same if every nested MemberExpr refers to the same
11347 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11348 // the base Expr's are CXXThisExpr's.
11349 const Expr *LHSBase = LHSExpr;
11350 const Expr *RHSBase = RHSExpr;
11351 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11352 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11353 if (!LHSME || !RHSME)
11356 while (LHSME && RHSME) {
11357 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11358 RHSME->getMemberDecl()->getCanonicalDecl())
11361 LHSBase = LHSME->getBase();
11362 RHSBase = RHSME->getBase();
11363 LHSME = dyn_cast<MemberExpr>(LHSBase);
11364 RHSME = dyn_cast<MemberExpr>(RHSBase);
11367 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11368 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11369 if (LHSDeclRef && RHSDeclRef) {
11370 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11372 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11373 RHSDeclRef->getDecl()->getCanonicalDecl())
11376 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11377 << LHSExpr->getSourceRange()
11378 << RHSExpr->getSourceRange();
11382 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11383 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11384 << LHSExpr->getSourceRange()
11385 << RHSExpr->getSourceRange();
11388 //===--- Layout compatibility ----------------------------------------------//
11392 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11394 /// \brief Check if two enumeration types are layout-compatible.
11395 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11396 // C++11 [dcl.enum] p8:
11397 // Two enumeration types are layout-compatible if they have the same
11398 // underlying type.
11399 return ED1->isComplete() && ED2->isComplete() &&
11400 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11403 /// \brief Check if two fields are layout-compatible.
11404 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11405 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11408 if (Field1->isBitField() != Field2->isBitField())
11411 if (Field1->isBitField()) {
11412 // Make sure that the bit-fields are the same length.
11413 unsigned Bits1 = Field1->getBitWidthValue(C);
11414 unsigned Bits2 = Field2->getBitWidthValue(C);
11416 if (Bits1 != Bits2)
11423 /// \brief Check if two standard-layout structs are layout-compatible.
11424 /// (C++11 [class.mem] p17)
11425 bool isLayoutCompatibleStruct(ASTContext &C,
11428 // If both records are C++ classes, check that base classes match.
11429 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11430 // If one of records is a CXXRecordDecl we are in C++ mode,
11431 // thus the other one is a CXXRecordDecl, too.
11432 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11433 // Check number of base classes.
11434 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11437 // Check the base classes.
11438 for (CXXRecordDecl::base_class_const_iterator
11439 Base1 = D1CXX->bases_begin(),
11440 BaseEnd1 = D1CXX->bases_end(),
11441 Base2 = D2CXX->bases_begin();
11443 ++Base1, ++Base2) {
11444 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11447 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11448 // If only RD2 is a C++ class, it should have zero base classes.
11449 if (D2CXX->getNumBases() > 0)
11453 // Check the fields.
11454 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11455 Field2End = RD2->field_end(),
11456 Field1 = RD1->field_begin(),
11457 Field1End = RD1->field_end();
11458 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11459 if (!isLayoutCompatible(C, *Field1, *Field2))
11462 if (Field1 != Field1End || Field2 != Field2End)
11468 /// \brief Check if two standard-layout unions are layout-compatible.
11469 /// (C++11 [class.mem] p18)
11470 bool isLayoutCompatibleUnion(ASTContext &C,
11473 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11474 for (auto *Field2 : RD2->fields())
11475 UnmatchedFields.insert(Field2);
11477 for (auto *Field1 : RD1->fields()) {
11478 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11479 I = UnmatchedFields.begin(),
11480 E = UnmatchedFields.end();
11482 for ( ; I != E; ++I) {
11483 if (isLayoutCompatible(C, Field1, *I)) {
11484 bool Result = UnmatchedFields.erase(*I);
11494 return UnmatchedFields.empty();
11497 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11498 if (RD1->isUnion() != RD2->isUnion())
11501 if (RD1->isUnion())
11502 return isLayoutCompatibleUnion(C, RD1, RD2);
11504 return isLayoutCompatibleStruct(C, RD1, RD2);
11507 /// \brief Check if two types are layout-compatible in C++11 sense.
11508 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11509 if (T1.isNull() || T2.isNull())
11512 // C++11 [basic.types] p11:
11513 // If two types T1 and T2 are the same type, then T1 and T2 are
11514 // layout-compatible types.
11515 if (C.hasSameType(T1, T2))
11518 T1 = T1.getCanonicalType().getUnqualifiedType();
11519 T2 = T2.getCanonicalType().getUnqualifiedType();
11521 const Type::TypeClass TC1 = T1->getTypeClass();
11522 const Type::TypeClass TC2 = T2->getTypeClass();
11527 if (TC1 == Type::Enum) {
11528 return isLayoutCompatible(C,
11529 cast<EnumType>(T1)->getDecl(),
11530 cast<EnumType>(T2)->getDecl());
11531 } else if (TC1 == Type::Record) {
11532 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11535 return isLayoutCompatible(C,
11536 cast<RecordType>(T1)->getDecl(),
11537 cast<RecordType>(T2)->getDecl());
11542 } // end anonymous namespace
11544 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11547 /// \brief Given a type tag expression find the type tag itself.
11549 /// \param TypeExpr Type tag expression, as it appears in user's code.
11551 /// \param VD Declaration of an identifier that appears in a type tag.
11553 /// \param MagicValue Type tag magic value.
11554 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11555 const ValueDecl **VD, uint64_t *MagicValue) {
11560 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11562 switch (TypeExpr->getStmtClass()) {
11563 case Stmt::UnaryOperatorClass: {
11564 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11565 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11566 TypeExpr = UO->getSubExpr();
11572 case Stmt::DeclRefExprClass: {
11573 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11574 *VD = DRE->getDecl();
11578 case Stmt::IntegerLiteralClass: {
11579 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11580 llvm::APInt MagicValueAPInt = IL->getValue();
11581 if (MagicValueAPInt.getActiveBits() <= 64) {
11582 *MagicValue = MagicValueAPInt.getZExtValue();
11588 case Stmt::BinaryConditionalOperatorClass:
11589 case Stmt::ConditionalOperatorClass: {
11590 const AbstractConditionalOperator *ACO =
11591 cast<AbstractConditionalOperator>(TypeExpr);
11593 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11595 TypeExpr = ACO->getTrueExpr();
11597 TypeExpr = ACO->getFalseExpr();
11603 case Stmt::BinaryOperatorClass: {
11604 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11605 if (BO->getOpcode() == BO_Comma) {
11606 TypeExpr = BO->getRHS();
11618 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11620 /// \param TypeExpr Expression that specifies a type tag.
11622 /// \param MagicValues Registered magic values.
11624 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11627 /// \param TypeInfo Information about the corresponding C type.
11629 /// \returns true if the corresponding C type was found.
11630 bool GetMatchingCType(
11631 const IdentifierInfo *ArgumentKind,
11632 const Expr *TypeExpr, const ASTContext &Ctx,
11633 const llvm::DenseMap<Sema::TypeTagMagicValue,
11634 Sema::TypeTagData> *MagicValues,
11635 bool &FoundWrongKind,
11636 Sema::TypeTagData &TypeInfo) {
11637 FoundWrongKind = false;
11639 // Variable declaration that has type_tag_for_datatype attribute.
11640 const ValueDecl *VD = nullptr;
11642 uint64_t MagicValue;
11644 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11648 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11649 if (I->getArgumentKind() != ArgumentKind) {
11650 FoundWrongKind = true;
11653 TypeInfo.Type = I->getMatchingCType();
11654 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11655 TypeInfo.MustBeNull = I->getMustBeNull();
11664 llvm::DenseMap<Sema::TypeTagMagicValue,
11665 Sema::TypeTagData>::const_iterator I =
11666 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11667 if (I == MagicValues->end())
11670 TypeInfo = I->second;
11673 } // end anonymous namespace
11675 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11676 uint64_t MagicValue, QualType Type,
11677 bool LayoutCompatible,
11679 if (!TypeTagForDatatypeMagicValues)
11680 TypeTagForDatatypeMagicValues.reset(
11681 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11683 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11684 (*TypeTagForDatatypeMagicValues)[Magic] =
11685 TypeTagData(Type, LayoutCompatible, MustBeNull);
11689 bool IsSameCharType(QualType T1, QualType T2) {
11690 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11694 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11698 BuiltinType::Kind T1Kind = BT1->getKind();
11699 BuiltinType::Kind T2Kind = BT2->getKind();
11701 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11702 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11703 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11704 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11706 } // end anonymous namespace
11708 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11709 const Expr * const *ExprArgs) {
11710 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11711 bool IsPointerAttr = Attr->getIsPointer();
11713 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11714 bool FoundWrongKind;
11715 TypeTagData TypeInfo;
11716 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11717 TypeTagForDatatypeMagicValues.get(),
11718 FoundWrongKind, TypeInfo)) {
11719 if (FoundWrongKind)
11720 Diag(TypeTagExpr->getExprLoc(),
11721 diag::warn_type_tag_for_datatype_wrong_kind)
11722 << TypeTagExpr->getSourceRange();
11726 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11727 if (IsPointerAttr) {
11728 // Skip implicit cast of pointer to `void *' (as a function argument).
11729 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11730 if (ICE->getType()->isVoidPointerType() &&
11731 ICE->getCastKind() == CK_BitCast)
11732 ArgumentExpr = ICE->getSubExpr();
11734 QualType ArgumentType = ArgumentExpr->getType();
11736 // Passing a `void*' pointer shouldn't trigger a warning.
11737 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11740 if (TypeInfo.MustBeNull) {
11741 // Type tag with matching void type requires a null pointer.
11742 if (!ArgumentExpr->isNullPointerConstant(Context,
11743 Expr::NPC_ValueDependentIsNotNull)) {
11744 Diag(ArgumentExpr->getExprLoc(),
11745 diag::warn_type_safety_null_pointer_required)
11746 << ArgumentKind->getName()
11747 << ArgumentExpr->getSourceRange()
11748 << TypeTagExpr->getSourceRange();
11753 QualType RequiredType = TypeInfo.Type;
11755 RequiredType = Context.getPointerType(RequiredType);
11757 bool mismatch = false;
11758 if (!TypeInfo.LayoutCompatible) {
11759 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11761 // C++11 [basic.fundamental] p1:
11762 // Plain char, signed char, and unsigned char are three distinct types.
11764 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11765 // char' depending on the current char signedness mode.
11767 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11768 RequiredType->getPointeeType())) ||
11769 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11773 mismatch = !isLayoutCompatible(Context,
11774 ArgumentType->getPointeeType(),
11775 RequiredType->getPointeeType());
11777 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11780 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
11781 << ArgumentType << ArgumentKind
11782 << TypeInfo.LayoutCompatible << RequiredType
11783 << ArgumentExpr->getSourceRange()
11784 << TypeTagExpr->getSourceRange();
11787 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11788 CharUnits Alignment) {
11789 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11792 void Sema::DiagnoseMisalignedMembers() {
11793 for (MisalignedMember &m : MisalignedMembers) {
11794 const NamedDecl *ND = m.RD;
11795 if (ND->getName().empty()) {
11796 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11799 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11800 << m.MD << ND << m.E->getSourceRange();
11802 MisalignedMembers.clear();
11805 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11806 E = E->IgnoreParens();
11807 if (!T->isPointerType() && !T->isIntegerType())
11809 if (isa<UnaryOperator>(E) &&
11810 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11811 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11812 if (isa<MemberExpr>(Op)) {
11813 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11814 MisalignedMember(Op));
11815 if (MA != MisalignedMembers.end() &&
11816 (T->isIntegerType() ||
11817 (T->isPointerType() &&
11818 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
11819 MisalignedMembers.erase(MA);
11824 void Sema::RefersToMemberWithReducedAlignment(
11826 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11828 const auto *ME = dyn_cast<MemberExpr>(E);
11832 // For a chain of MemberExpr like "a.b.c.d" this list
11833 // will keep FieldDecl's like [d, c, b].
11834 SmallVector<FieldDecl *, 4> ReverseMemberChain;
11835 const MemberExpr *TopME = nullptr;
11836 bool AnyIsPacked = false;
11838 QualType BaseType = ME->getBase()->getType();
11840 BaseType = BaseType->getPointeeType();
11841 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11843 ValueDecl *MD = ME->getMemberDecl();
11844 auto *FD = dyn_cast<FieldDecl>(MD);
11845 // We do not care about non-data members.
11846 if (!FD || FD->isInvalidDecl())
11850 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11851 ReverseMemberChain.push_back(FD);
11854 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11856 assert(TopME && "We did not compute a topmost MemberExpr!");
11858 // Not the scope of this diagnostic.
11862 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11863 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11864 // TODO: The innermost base of the member expression may be too complicated.
11865 // For now, just disregard these cases. This is left for future
11867 if (!DRE && !isa<CXXThisExpr>(TopBase))
11870 // Alignment expected by the whole expression.
11871 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11873 // No need to do anything else with this case.
11874 if (ExpectedAlignment.isOne())
11877 // Synthesize offset of the whole access.
11879 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11881 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11884 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11885 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11886 ReverseMemberChain.back()->getParent()->getTypeForDecl());
11888 // The base expression of the innermost MemberExpr may give
11889 // stronger guarantees than the class containing the member.
11890 if (DRE && !TopME->isArrow()) {
11891 const ValueDecl *VD = DRE->getDecl();
11892 if (!VD->getType()->isReferenceType())
11893 CompleteObjectAlignment =
11894 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11897 // Check if the synthesized offset fulfills the alignment.
11898 if (Offset % ExpectedAlignment != 0 ||
11899 // It may fulfill the offset it but the effective alignment may still be
11900 // lower than the expected expression alignment.
11901 CompleteObjectAlignment < ExpectedAlignment) {
11902 // If this happens, we want to determine a sensible culprit of this.
11903 // Intuitively, watching the chain of member expressions from right to
11904 // left, we start with the required alignment (as required by the field
11905 // type) but some packed attribute in that chain has reduced the alignment.
11906 // It may happen that another packed structure increases it again. But if
11907 // we are here such increase has not been enough. So pointing the first
11908 // FieldDecl that either is packed or else its RecordDecl is,
11909 // seems reasonable.
11910 FieldDecl *FD = nullptr;
11911 CharUnits Alignment;
11912 for (FieldDecl *FDI : ReverseMemberChain) {
11913 if (FDI->hasAttr<PackedAttr>() ||
11914 FDI->getParent()->hasAttr<PackedAttr>()) {
11916 Alignment = std::min(
11917 Context.getTypeAlignInChars(FD->getType()),
11918 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11922 assert(FD && "We did not find a packed FieldDecl!");
11923 Action(E, FD->getParent(), FD, Alignment);
11927 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11928 using namespace std::placeholders;
11929 RefersToMemberWithReducedAlignment(
11930 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,