1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements extra semantic analysis beyond what is enforced
11 // by the C type system.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "llvm/ADT/SmallBitVector.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/Support/ConvertUTF.h"
39 #include "llvm/Support/raw_ostream.h"
41 using namespace clang;
44 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
46 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
47 PP.getLangOpts(), PP.getTargetInfo());
50 /// Checks that a call expression's argument count is the desired number.
51 /// This is useful when doing custom type-checking. Returns true on error.
52 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
70 /// Check that the first argument to __builtin_annotation is an integer
71 /// and the second argument is a non-wide string literal.
72 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
98 /// Check that the argument to __builtin_addressof is a glvalue, and set the
99 /// result type to the corresponding pointer type.
100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
104 ExprResult Arg(S.Owned(TheCall->getArg(0)));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
109 TheCall->setArg(0, Arg.take());
110 TheCall->setType(ResultType);
115 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
116 ExprResult TheCallResult(Owned(TheCall));
118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
133 ICEArguments &= ~(1 << ArgNo);
137 case Builtin::BI__builtin___CFStringMakeConstantString:
138 assert(TheCall->getNumArgs() == 1 &&
139 "Wrong # arguments to builtin CFStringMakeConstantString");
140 if (CheckObjCString(TheCall->getArg(0)))
143 case Builtin::BI__builtin_stdarg_start:
144 case Builtin::BI__builtin_va_start:
145 if (SemaBuiltinVAStart(TheCall))
148 case Builtin::BI__builtin_isgreater:
149 case Builtin::BI__builtin_isgreaterequal:
150 case Builtin::BI__builtin_isless:
151 case Builtin::BI__builtin_islessequal:
152 case Builtin::BI__builtin_islessgreater:
153 case Builtin::BI__builtin_isunordered:
154 if (SemaBuiltinUnorderedCompare(TheCall))
157 case Builtin::BI__builtin_fpclassify:
158 if (SemaBuiltinFPClassification(TheCall, 6))
161 case Builtin::BI__builtin_isfinite:
162 case Builtin::BI__builtin_isinf:
163 case Builtin::BI__builtin_isinf_sign:
164 case Builtin::BI__builtin_isnan:
165 case Builtin::BI__builtin_isnormal:
166 if (SemaBuiltinFPClassification(TheCall, 1))
169 case Builtin::BI__builtin_shufflevector:
170 return SemaBuiltinShuffleVector(TheCall);
171 // TheCall will be freed by the smart pointer here, but that's fine, since
172 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
173 case Builtin::BI__builtin_prefetch:
174 if (SemaBuiltinPrefetch(TheCall))
177 case Builtin::BI__builtin_object_size:
178 if (SemaBuiltinObjectSize(TheCall))
181 case Builtin::BI__builtin_longjmp:
182 if (SemaBuiltinLongjmp(TheCall))
186 case Builtin::BI__builtin_classify_type:
187 if (checkArgCount(*this, TheCall, 1)) return true;
188 TheCall->setType(Context.IntTy);
190 case Builtin::BI__builtin_constant_p:
191 if (checkArgCount(*this, TheCall, 1)) return true;
192 TheCall->setType(Context.IntTy);
194 case Builtin::BI__sync_fetch_and_add:
195 case Builtin::BI__sync_fetch_and_add_1:
196 case Builtin::BI__sync_fetch_and_add_2:
197 case Builtin::BI__sync_fetch_and_add_4:
198 case Builtin::BI__sync_fetch_and_add_8:
199 case Builtin::BI__sync_fetch_and_add_16:
200 case Builtin::BI__sync_fetch_and_sub:
201 case Builtin::BI__sync_fetch_and_sub_1:
202 case Builtin::BI__sync_fetch_and_sub_2:
203 case Builtin::BI__sync_fetch_and_sub_4:
204 case Builtin::BI__sync_fetch_and_sub_8:
205 case Builtin::BI__sync_fetch_and_sub_16:
206 case Builtin::BI__sync_fetch_and_or:
207 case Builtin::BI__sync_fetch_and_or_1:
208 case Builtin::BI__sync_fetch_and_or_2:
209 case Builtin::BI__sync_fetch_and_or_4:
210 case Builtin::BI__sync_fetch_and_or_8:
211 case Builtin::BI__sync_fetch_and_or_16:
212 case Builtin::BI__sync_fetch_and_and:
213 case Builtin::BI__sync_fetch_and_and_1:
214 case Builtin::BI__sync_fetch_and_and_2:
215 case Builtin::BI__sync_fetch_and_and_4:
216 case Builtin::BI__sync_fetch_and_and_8:
217 case Builtin::BI__sync_fetch_and_and_16:
218 case Builtin::BI__sync_fetch_and_xor:
219 case Builtin::BI__sync_fetch_and_xor_1:
220 case Builtin::BI__sync_fetch_and_xor_2:
221 case Builtin::BI__sync_fetch_and_xor_4:
222 case Builtin::BI__sync_fetch_and_xor_8:
223 case Builtin::BI__sync_fetch_and_xor_16:
224 case Builtin::BI__sync_add_and_fetch:
225 case Builtin::BI__sync_add_and_fetch_1:
226 case Builtin::BI__sync_add_and_fetch_2:
227 case Builtin::BI__sync_add_and_fetch_4:
228 case Builtin::BI__sync_add_and_fetch_8:
229 case Builtin::BI__sync_add_and_fetch_16:
230 case Builtin::BI__sync_sub_and_fetch:
231 case Builtin::BI__sync_sub_and_fetch_1:
232 case Builtin::BI__sync_sub_and_fetch_2:
233 case Builtin::BI__sync_sub_and_fetch_4:
234 case Builtin::BI__sync_sub_and_fetch_8:
235 case Builtin::BI__sync_sub_and_fetch_16:
236 case Builtin::BI__sync_and_and_fetch:
237 case Builtin::BI__sync_and_and_fetch_1:
238 case Builtin::BI__sync_and_and_fetch_2:
239 case Builtin::BI__sync_and_and_fetch_4:
240 case Builtin::BI__sync_and_and_fetch_8:
241 case Builtin::BI__sync_and_and_fetch_16:
242 case Builtin::BI__sync_or_and_fetch:
243 case Builtin::BI__sync_or_and_fetch_1:
244 case Builtin::BI__sync_or_and_fetch_2:
245 case Builtin::BI__sync_or_and_fetch_4:
246 case Builtin::BI__sync_or_and_fetch_8:
247 case Builtin::BI__sync_or_and_fetch_16:
248 case Builtin::BI__sync_xor_and_fetch:
249 case Builtin::BI__sync_xor_and_fetch_1:
250 case Builtin::BI__sync_xor_and_fetch_2:
251 case Builtin::BI__sync_xor_and_fetch_4:
252 case Builtin::BI__sync_xor_and_fetch_8:
253 case Builtin::BI__sync_xor_and_fetch_16:
254 case Builtin::BI__sync_val_compare_and_swap:
255 case Builtin::BI__sync_val_compare_and_swap_1:
256 case Builtin::BI__sync_val_compare_and_swap_2:
257 case Builtin::BI__sync_val_compare_and_swap_4:
258 case Builtin::BI__sync_val_compare_and_swap_8:
259 case Builtin::BI__sync_val_compare_and_swap_16:
260 case Builtin::BI__sync_bool_compare_and_swap:
261 case Builtin::BI__sync_bool_compare_and_swap_1:
262 case Builtin::BI__sync_bool_compare_and_swap_2:
263 case Builtin::BI__sync_bool_compare_and_swap_4:
264 case Builtin::BI__sync_bool_compare_and_swap_8:
265 case Builtin::BI__sync_bool_compare_and_swap_16:
266 case Builtin::BI__sync_lock_test_and_set:
267 case Builtin::BI__sync_lock_test_and_set_1:
268 case Builtin::BI__sync_lock_test_and_set_2:
269 case Builtin::BI__sync_lock_test_and_set_4:
270 case Builtin::BI__sync_lock_test_and_set_8:
271 case Builtin::BI__sync_lock_test_and_set_16:
272 case Builtin::BI__sync_lock_release:
273 case Builtin::BI__sync_lock_release_1:
274 case Builtin::BI__sync_lock_release_2:
275 case Builtin::BI__sync_lock_release_4:
276 case Builtin::BI__sync_lock_release_8:
277 case Builtin::BI__sync_lock_release_16:
278 case Builtin::BI__sync_swap:
279 case Builtin::BI__sync_swap_1:
280 case Builtin::BI__sync_swap_2:
281 case Builtin::BI__sync_swap_4:
282 case Builtin::BI__sync_swap_8:
283 case Builtin::BI__sync_swap_16:
284 return SemaBuiltinAtomicOverloaded(TheCallResult);
285 #define BUILTIN(ID, TYPE, ATTRS)
286 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287 case Builtin::BI##ID: \
288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
289 #include "clang/Basic/Builtins.def"
290 case Builtin::BI__builtin_annotation:
291 if (SemaBuiltinAnnotation(*this, TheCall))
294 case Builtin::BI__builtin_addressof:
295 if (SemaBuiltinAddressof(*this, TheCall))
300 // Since the target specific builtins for each arch overlap, only check those
301 // of the arch we are compiling for.
302 if (BuiltinID >= Builtin::FirstTSBuiltin) {
303 switch (Context.getTargetInfo().getTriple().getArch()) {
304 case llvm::Triple::arm:
305 case llvm::Triple::thumb:
306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
309 case llvm::Triple::aarch64:
310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
313 case llvm::Triple::mips:
314 case llvm::Triple::mipsel:
315 case llvm::Triple::mips64:
316 case llvm::Triple::mips64el:
317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
325 return TheCallResult;
328 // Get the valid immediate range for the specified NEON type code.
329 static unsigned RFT(unsigned t, bool shift = false) {
330 NeonTypeFlags Type(t);
331 int IsQuad = Type.isQuad();
332 switch (Type.getEltType()) {
333 case NeonTypeFlags::Int8:
334 case NeonTypeFlags::Poly8:
335 return shift ? 7 : (8 << IsQuad) - 1;
336 case NeonTypeFlags::Int16:
337 case NeonTypeFlags::Poly16:
338 return shift ? 15 : (4 << IsQuad) - 1;
339 case NeonTypeFlags::Int32:
340 return shift ? 31 : (2 << IsQuad) - 1;
341 case NeonTypeFlags::Int64:
342 case NeonTypeFlags::Poly64:
343 return shift ? 63 : (1 << IsQuad) - 1;
344 case NeonTypeFlags::Float16:
345 assert(!shift && "cannot shift float types!");
346 return (4 << IsQuad) - 1;
347 case NeonTypeFlags::Float32:
348 assert(!shift && "cannot shift float types!");
349 return (2 << IsQuad) - 1;
350 case NeonTypeFlags::Float64:
351 assert(!shift && "cannot shift float types!");
352 return (1 << IsQuad) - 1;
354 llvm_unreachable("Invalid NeonTypeFlag!");
357 /// getNeonEltType - Return the QualType corresponding to the elements of
358 /// the vector type specified by the NeonTypeFlags. This is used to check
359 /// the pointer arguments for Neon load/store intrinsics.
360 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
362 switch (Flags.getEltType()) {
363 case NeonTypeFlags::Int8:
364 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
365 case NeonTypeFlags::Int16:
366 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
367 case NeonTypeFlags::Int32:
368 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
369 case NeonTypeFlags::Int64:
370 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
371 case NeonTypeFlags::Poly8:
372 return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
373 case NeonTypeFlags::Poly16:
374 return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
375 case NeonTypeFlags::Poly64:
376 return Context.UnsignedLongLongTy;
377 case NeonTypeFlags::Float16:
378 return Context.HalfTy;
379 case NeonTypeFlags::Float32:
380 return Context.FloatTy;
381 case NeonTypeFlags::Float64:
382 return Context.DoubleTy;
384 llvm_unreachable("Invalid NeonTypeFlag!");
387 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
395 bool HasConstPtr = false;
397 #define GET_NEON_AARCH64_OVERLOAD_CHECK
398 #include "clang/Basic/arm_neon.inc"
399 #undef GET_NEON_AARCH64_OVERLOAD_CHECK
402 // For NEON intrinsics which are overloaded on vector element type, validate
403 // the immediate which specifies which variant to emit.
404 unsigned ImmArg = TheCall->getNumArgs() - 1;
406 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
409 TV = Result.getLimitedValue(64);
410 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
411 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
412 << TheCall->getArg(ImmArg)->getSourceRange();
415 if (PtrArgNum >= 0) {
416 // Check that pointer arguments have the specified type.
417 Expr *Arg = TheCall->getArg(PtrArgNum);
418 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
419 Arg = ICE->getSubExpr();
420 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
421 QualType RHSTy = RHS.get()->getType();
422 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, true);
424 EltTy = EltTy.withConst();
425 QualType LHSTy = Context.getPointerType(EltTy);
426 AssignConvertType ConvTy;
427 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
430 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
431 RHS.get(), AA_Assigning))
435 // For NEON intrinsics which take an immediate value as part of the
436 // instruction, range check them here.
437 unsigned i = 0, l = 0, u = 0;
441 #define GET_NEON_AARCH64_IMMEDIATE_CHECK
442 #include "clang/Basic/arm_neon.inc"
443 #undef GET_NEON_AARCH64_IMMEDIATE_CHECK
447 // We can't check the value of a dependent argument.
448 if (TheCall->getArg(i)->isTypeDependent() ||
449 TheCall->getArg(i)->isValueDependent())
452 // Check that the immediate argument is actually a constant.
453 if (SemaBuiltinConstantArg(TheCall, i, Result))
456 // Range check against the upper/lower values for this isntruction.
457 unsigned Val = Result.getZExtValue();
458 if (Val < l || Val > (u + l))
459 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
460 << l << u + l << TheCall->getArg(i)->getSourceRange();
465 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
466 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
467 BuiltinID == ARM::BI__builtin_arm_strex) &&
468 "unexpected ARM builtin");
469 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
471 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
473 // Ensure that we have the proper number of arguments.
474 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
477 // Inspect the pointer argument of the atomic builtin. This should always be
478 // a pointer type, whose element is an integral scalar or pointer type.
479 // Because it is a pointer type, we don't have to worry about any implicit
481 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
482 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
483 if (PointerArgRes.isInvalid())
485 PointerArg = PointerArgRes.take();
487 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
489 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
490 << PointerArg->getType() << PointerArg->getSourceRange();
494 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
495 // task is to insert the appropriate casts into the AST. First work out just
496 // what the appropriate type is.
497 QualType ValType = pointerType->getPointeeType();
498 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
502 // Issue a warning if the cast is dodgy.
503 CastKind CastNeeded = CK_NoOp;
504 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
505 CastNeeded = CK_BitCast;
506 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
507 << PointerArg->getType()
508 << Context.getPointerType(AddrType)
509 << AA_Passing << PointerArg->getSourceRange();
512 // Finally, do the cast and replace the argument with the corrected version.
513 AddrType = Context.getPointerType(AddrType);
514 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
515 if (PointerArgRes.isInvalid())
517 PointerArg = PointerArgRes.take();
519 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
521 // In general, we allow ints, floats and pointers to be loaded and stored.
522 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
523 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
524 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
525 << PointerArg->getType() << PointerArg->getSourceRange();
529 // But ARM doesn't have instructions to deal with 128-bit versions.
530 if (Context.getTypeSize(ValType) > 64) {
531 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
532 << PointerArg->getType() << PointerArg->getSourceRange();
536 switch (ValType.getObjCLifetime()) {
537 case Qualifiers::OCL_None:
538 case Qualifiers::OCL_ExplicitNone:
542 case Qualifiers::OCL_Weak:
543 case Qualifiers::OCL_Strong:
544 case Qualifiers::OCL_Autoreleasing:
545 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
546 << ValType << PointerArg->getSourceRange();
552 TheCall->setType(ValType);
556 // Initialize the argument to be stored.
557 ExprResult ValArg = TheCall->getArg(0);
558 InitializedEntity Entity = InitializedEntity::InitializeParameter(
559 Context, ValType, /*consume*/ false);
560 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
561 if (ValArg.isInvalid())
563 TheCall->setArg(0, ValArg.get());
565 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
566 // but the custom checker bypasses all default analysis.
567 TheCall->setType(Context.IntTy);
571 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
574 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
575 BuiltinID == ARM::BI__builtin_arm_strex) {
576 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
582 bool HasConstPtr = false;
584 #define GET_NEON_OVERLOAD_CHECK
585 #include "clang/Basic/arm_neon.inc"
586 #undef GET_NEON_OVERLOAD_CHECK
589 // For NEON intrinsics which are overloaded on vector element type, validate
590 // the immediate which specifies which variant to emit.
591 unsigned ImmArg = TheCall->getNumArgs()-1;
593 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
596 TV = Result.getLimitedValue(64);
597 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
598 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
599 << TheCall->getArg(ImmArg)->getSourceRange();
602 if (PtrArgNum >= 0) {
603 // Check that pointer arguments have the specified type.
604 Expr *Arg = TheCall->getArg(PtrArgNum);
605 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
606 Arg = ICE->getSubExpr();
607 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
608 QualType RHSTy = RHS.get()->getType();
609 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, false);
611 EltTy = EltTy.withConst();
612 QualType LHSTy = Context.getPointerType(EltTy);
613 AssignConvertType ConvTy;
614 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
617 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
618 RHS.get(), AA_Assigning))
622 // For NEON intrinsics which take an immediate value as part of the
623 // instruction, range check them here.
624 unsigned i = 0, l = 0, u = 0;
626 default: return false;
627 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
628 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
629 case ARM::BI__builtin_arm_vcvtr_f:
630 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
631 case ARM::BI__builtin_arm_dmb:
632 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
633 #define GET_NEON_IMMEDIATE_CHECK
634 #include "clang/Basic/arm_neon.inc"
635 #undef GET_NEON_IMMEDIATE_CHECK
638 // We can't check the value of a dependent argument.
639 if (TheCall->getArg(i)->isTypeDependent() ||
640 TheCall->getArg(i)->isValueDependent())
643 // Check that the immediate argument is actually a constant.
644 if (SemaBuiltinConstantArg(TheCall, i, Result))
647 // Range check against the upper/lower values for this isntruction.
648 unsigned Val = Result.getZExtValue();
649 if (Val < l || Val > (u + l))
650 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
651 << l << u+l << TheCall->getArg(i)->getSourceRange();
653 // FIXME: VFP Intrinsics should error if VFP not present.
657 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
658 unsigned i = 0, l = 0, u = 0;
660 default: return false;
661 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
662 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
663 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
664 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
665 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
666 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
667 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
670 // We can't check the value of a dependent argument.
671 if (TheCall->getArg(i)->isTypeDependent() ||
672 TheCall->getArg(i)->isValueDependent())
675 // Check that the immediate argument is actually a constant.
677 if (SemaBuiltinConstantArg(TheCall, i, Result))
680 // Range check against the upper/lower values for this instruction.
681 unsigned Val = Result.getZExtValue();
682 if (Val < l || Val > u)
683 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
684 << l << u << TheCall->getArg(i)->getSourceRange();
689 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
690 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
691 /// Returns true when the format fits the function and the FormatStringInfo has
693 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
694 FormatStringInfo *FSI) {
695 FSI->HasVAListArg = Format->getFirstArg() == 0;
696 FSI->FormatIdx = Format->getFormatIdx() - 1;
697 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
699 // The way the format attribute works in GCC, the implicit this argument
700 // of member functions is counted. However, it doesn't appear in our own
701 // lists, so decrement format_idx in that case.
703 if(FSI->FormatIdx == 0)
706 if (FSI->FirstDataArg != 0)
712 /// Handles the checks for format strings, non-POD arguments to vararg
713 /// functions, and NULL arguments passed to non-NULL parameters.
714 void Sema::checkCall(NamedDecl *FDecl,
715 ArrayRef<const Expr *> Args,
716 unsigned NumProtoArgs,
717 bool IsMemberFunction,
720 VariadicCallType CallType) {
721 // FIXME: We should check as much as we can in the template definition.
722 if (CurContext->isDependentContext())
725 // Printf and scanf checking.
726 llvm::SmallBitVector CheckedVarArgs;
728 for (specific_attr_iterator<FormatAttr>
729 I = FDecl->specific_attr_begin<FormatAttr>(),
730 E = FDecl->specific_attr_end<FormatAttr>();
732 // Only create vector if there are format attributes.
733 CheckedVarArgs.resize(Args.size());
735 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
740 // Refuse POD arguments that weren't caught by the format string
742 if (CallType != VariadicDoesNotApply) {
743 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
744 // Args[ArgIdx] can be null in malformed code.
745 if (const Expr *Arg = Args[ArgIdx]) {
746 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
747 checkVariadicArgument(Arg, CallType);
753 for (specific_attr_iterator<NonNullAttr>
754 I = FDecl->specific_attr_begin<NonNullAttr>(),
755 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
756 CheckNonNullArguments(*I, Args.data(), Loc);
758 // Type safety checking.
759 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
760 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
761 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
763 CheckArgumentWithTypeTag(*i, Args.data());
768 /// CheckConstructorCall - Check a constructor call for correctness and safety
769 /// properties not enforced by the C type system.
770 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
771 ArrayRef<const Expr *> Args,
772 const FunctionProtoType *Proto,
773 SourceLocation Loc) {
774 VariadicCallType CallType =
775 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
776 checkCall(FDecl, Args, Proto->getNumArgs(),
777 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
780 /// CheckFunctionCall - Check a direct function call for various correctness
781 /// and safety properties not strictly enforced by the C type system.
782 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
783 const FunctionProtoType *Proto) {
784 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
785 isa<CXXMethodDecl>(FDecl);
786 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
787 IsMemberOperatorCall;
788 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
789 TheCall->getCallee());
790 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
791 Expr** Args = TheCall->getArgs();
792 unsigned NumArgs = TheCall->getNumArgs();
793 if (IsMemberOperatorCall) {
794 // If this is a call to a member operator, hide the first argument
796 // FIXME: Our choice of AST representation here is less than ideal.
800 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
802 IsMemberFunction, TheCall->getRParenLoc(),
803 TheCall->getCallee()->getSourceRange(), CallType);
805 IdentifierInfo *FnInfo = FDecl->getIdentifier();
806 // None of the checks below are needed for functions that don't have
807 // simple names (e.g., C++ conversion functions).
811 unsigned CMId = FDecl->getMemoryFunctionKind();
815 // Handle memory setting and copying functions.
816 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
817 CheckStrlcpycatArguments(TheCall, FnInfo);
818 else if (CMId == Builtin::BIstrncat)
819 CheckStrncatArguments(TheCall, FnInfo);
821 CheckMemaccessArguments(TheCall, CMId, FnInfo);
826 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
827 ArrayRef<const Expr *> Args) {
828 VariadicCallType CallType =
829 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
831 checkCall(Method, Args, Method->param_size(),
832 /*IsMemberFunction=*/false,
833 lbrac, Method->getSourceRange(), CallType);
838 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
839 const FunctionProtoType *Proto) {
840 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
844 QualType Ty = V->getType();
845 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
848 VariadicCallType CallType;
849 if (!Proto || !Proto->isVariadic()) {
850 CallType = VariadicDoesNotApply;
851 } else if (Ty->isBlockPointerType()) {
852 CallType = VariadicBlock;
853 } else { // Ty->isFunctionPointerType()
854 CallType = VariadicFunction;
856 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
859 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
860 TheCall->getNumArgs()),
861 NumProtoArgs, /*IsMemberFunction=*/false,
862 TheCall->getRParenLoc(),
863 TheCall->getCallee()->getSourceRange(), CallType);
868 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
869 /// such as function pointers returned from functions.
870 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
871 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
872 TheCall->getCallee());
873 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
875 checkCall(/*FDecl=*/0,
876 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
877 TheCall->getNumArgs()),
878 NumProtoArgs, /*IsMemberFunction=*/false,
879 TheCall->getRParenLoc(),
880 TheCall->getCallee()->getSourceRange(), CallType);
885 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
886 AtomicExpr::AtomicOp Op) {
887 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
888 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
890 // All these operations take one of the following forms:
892 // C __c11_atomic_init(A *, C)
894 // C __c11_atomic_load(A *, int)
896 // void __atomic_load(A *, CP, int)
898 // C __c11_atomic_add(A *, M, int)
900 // C __atomic_exchange_n(A *, CP, int)
902 // void __atomic_exchange(A *, C *, CP, int)
904 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
906 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
909 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
910 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
912 // C is an appropriate type,
913 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
914 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
915 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
916 // the int parameters are for orderings.
918 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
919 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
920 && "need to update code for modified C11 atomics");
921 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
922 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
923 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
924 Op == AtomicExpr::AO__atomic_store_n ||
925 Op == AtomicExpr::AO__atomic_exchange_n ||
926 Op == AtomicExpr::AO__atomic_compare_exchange_n;
927 bool IsAddSub = false;
930 case AtomicExpr::AO__c11_atomic_init:
934 case AtomicExpr::AO__c11_atomic_load:
935 case AtomicExpr::AO__atomic_load_n:
939 case AtomicExpr::AO__c11_atomic_store:
940 case AtomicExpr::AO__atomic_load:
941 case AtomicExpr::AO__atomic_store:
942 case AtomicExpr::AO__atomic_store_n:
946 case AtomicExpr::AO__c11_atomic_fetch_add:
947 case AtomicExpr::AO__c11_atomic_fetch_sub:
948 case AtomicExpr::AO__atomic_fetch_add:
949 case AtomicExpr::AO__atomic_fetch_sub:
950 case AtomicExpr::AO__atomic_add_fetch:
951 case AtomicExpr::AO__atomic_sub_fetch:
954 case AtomicExpr::AO__c11_atomic_fetch_and:
955 case AtomicExpr::AO__c11_atomic_fetch_or:
956 case AtomicExpr::AO__c11_atomic_fetch_xor:
957 case AtomicExpr::AO__atomic_fetch_and:
958 case AtomicExpr::AO__atomic_fetch_or:
959 case AtomicExpr::AO__atomic_fetch_xor:
960 case AtomicExpr::AO__atomic_fetch_nand:
961 case AtomicExpr::AO__atomic_and_fetch:
962 case AtomicExpr::AO__atomic_or_fetch:
963 case AtomicExpr::AO__atomic_xor_fetch:
964 case AtomicExpr::AO__atomic_nand_fetch:
968 case AtomicExpr::AO__c11_atomic_exchange:
969 case AtomicExpr::AO__atomic_exchange_n:
973 case AtomicExpr::AO__atomic_exchange:
977 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
978 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
982 case AtomicExpr::AO__atomic_compare_exchange:
983 case AtomicExpr::AO__atomic_compare_exchange_n:
988 // Check we have the right number of arguments.
989 if (TheCall->getNumArgs() < NumArgs[Form]) {
990 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
991 << 0 << NumArgs[Form] << TheCall->getNumArgs()
992 << TheCall->getCallee()->getSourceRange();
994 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
995 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
996 diag::err_typecheck_call_too_many_args)
997 << 0 << NumArgs[Form] << TheCall->getNumArgs()
998 << TheCall->getCallee()->getSourceRange();
1002 // Inspect the first argument of the atomic operation.
1003 Expr *Ptr = TheCall->getArg(0);
1004 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1005 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1007 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1008 << Ptr->getType() << Ptr->getSourceRange();
1012 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1013 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1014 QualType ValType = AtomTy; // 'C'
1016 if (!AtomTy->isAtomicType()) {
1017 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1018 << Ptr->getType() << Ptr->getSourceRange();
1021 if (AtomTy.isConstQualified()) {
1022 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1023 << Ptr->getType() << Ptr->getSourceRange();
1026 ValType = AtomTy->getAs<AtomicType>()->getValueType();
1029 // For an arithmetic operation, the implied arithmetic must be well-formed.
1030 if (Form == Arithmetic) {
1031 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1032 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1033 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1034 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1037 if (!IsAddSub && !ValType->isIntegerType()) {
1038 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1039 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1042 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1043 // For __atomic_*_n operations, the value type must be a scalar integral or
1044 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1045 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1046 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1050 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1051 !AtomTy->isScalarType()) {
1052 // For GNU atomics, require a trivially-copyable type. This is not part of
1053 // the GNU atomics specification, but we enforce it for sanity.
1054 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1055 << Ptr->getType() << Ptr->getSourceRange();
1059 // FIXME: For any builtin other than a load, the ValType must not be
1062 switch (ValType.getObjCLifetime()) {
1063 case Qualifiers::OCL_None:
1064 case Qualifiers::OCL_ExplicitNone:
1068 case Qualifiers::OCL_Weak:
1069 case Qualifiers::OCL_Strong:
1070 case Qualifiers::OCL_Autoreleasing:
1071 // FIXME: Can this happen? By this point, ValType should be known
1072 // to be trivially copyable.
1073 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1074 << ValType << Ptr->getSourceRange();
1078 QualType ResultType = ValType;
1079 if (Form == Copy || Form == GNUXchg || Form == Init)
1080 ResultType = Context.VoidTy;
1081 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1082 ResultType = Context.BoolTy;
1084 // The type of a parameter passed 'by value'. In the GNU atomics, such
1085 // arguments are actually passed as pointers.
1086 QualType ByValType = ValType; // 'CP'
1088 ByValType = Ptr->getType();
1090 // The first argument --- the pointer --- has a fixed type; we
1091 // deduce the types of the rest of the arguments accordingly. Walk
1092 // the remaining arguments, converting them to the deduced value type.
1093 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1095 if (i < NumVals[Form] + 1) {
1098 // The second argument is the non-atomic operand. For arithmetic, this
1099 // is always passed by value, and for a compare_exchange it is always
1100 // passed by address. For the rest, GNU uses by-address and C11 uses
1102 assert(Form != Load);
1103 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1105 else if (Form == Copy || Form == Xchg)
1107 else if (Form == Arithmetic)
1108 Ty = Context.getPointerDiffType();
1110 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1113 // The third argument to compare_exchange / GNU exchange is a
1114 // (pointer to a) desired value.
1118 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1119 Ty = Context.BoolTy;
1123 // The order(s) are always converted to int.
1127 InitializedEntity Entity =
1128 InitializedEntity::InitializeParameter(Context, Ty, false);
1129 ExprResult Arg = TheCall->getArg(i);
1130 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1131 if (Arg.isInvalid())
1133 TheCall->setArg(i, Arg.get());
1136 // Permute the arguments into a 'consistent' order.
1137 SmallVector<Expr*, 5> SubExprs;
1138 SubExprs.push_back(Ptr);
1141 // Note, AtomicExpr::getVal1() has a special case for this atomic.
1142 SubExprs.push_back(TheCall->getArg(1)); // Val1
1145 SubExprs.push_back(TheCall->getArg(1)); // Order
1150 SubExprs.push_back(TheCall->getArg(2)); // Order
1151 SubExprs.push_back(TheCall->getArg(1)); // Val1
1154 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1155 SubExprs.push_back(TheCall->getArg(3)); // Order
1156 SubExprs.push_back(TheCall->getArg(1)); // Val1
1157 SubExprs.push_back(TheCall->getArg(2)); // Val2
1160 SubExprs.push_back(TheCall->getArg(3)); // Order
1161 SubExprs.push_back(TheCall->getArg(1)); // Val1
1162 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1163 SubExprs.push_back(TheCall->getArg(2)); // Val2
1166 SubExprs.push_back(TheCall->getArg(4)); // Order
1167 SubExprs.push_back(TheCall->getArg(1)); // Val1
1168 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1169 SubExprs.push_back(TheCall->getArg(2)); // Val2
1170 SubExprs.push_back(TheCall->getArg(3)); // Weak
1174 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1175 SubExprs, ResultType, Op,
1176 TheCall->getRParenLoc());
1178 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1179 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1180 Context.AtomicUsesUnsupportedLibcall(AE))
1181 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1182 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1188 /// checkBuiltinArgument - Given a call to a builtin function, perform
1189 /// normal type-checking on the given argument, updating the call in
1190 /// place. This is useful when a builtin function requires custom
1191 /// type-checking for some of its arguments but not necessarily all of
1194 /// Returns true on error.
1195 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1196 FunctionDecl *Fn = E->getDirectCallee();
1197 assert(Fn && "builtin call without direct callee!");
1199 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1200 InitializedEntity Entity =
1201 InitializedEntity::InitializeParameter(S.Context, Param);
1203 ExprResult Arg = E->getArg(0);
1204 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1205 if (Arg.isInvalid())
1208 E->setArg(ArgIndex, Arg.take());
1212 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1213 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1214 /// type of its first argument. The main ActOnCallExpr routines have already
1215 /// promoted the types of arguments because all of these calls are prototyped as
1218 /// This function goes through and does final semantic checking for these
1221 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1222 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1223 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1224 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1226 // Ensure that we have at least one argument to do type inference from.
1227 if (TheCall->getNumArgs() < 1) {
1228 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1229 << 0 << 1 << TheCall->getNumArgs()
1230 << TheCall->getCallee()->getSourceRange();
1234 // Inspect the first argument of the atomic builtin. This should always be
1235 // a pointer type, whose element is an integral scalar or pointer type.
1236 // Because it is a pointer type, we don't have to worry about any implicit
1238 // FIXME: We don't allow floating point scalars as input.
1239 Expr *FirstArg = TheCall->getArg(0);
1240 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1241 if (FirstArgResult.isInvalid())
1243 FirstArg = FirstArgResult.take();
1244 TheCall->setArg(0, FirstArg);
1246 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1248 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1249 << FirstArg->getType() << FirstArg->getSourceRange();
1253 QualType ValType = pointerType->getPointeeType();
1254 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1255 !ValType->isBlockPointerType()) {
1256 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1257 << FirstArg->getType() << FirstArg->getSourceRange();
1261 switch (ValType.getObjCLifetime()) {
1262 case Qualifiers::OCL_None:
1263 case Qualifiers::OCL_ExplicitNone:
1267 case Qualifiers::OCL_Weak:
1268 case Qualifiers::OCL_Strong:
1269 case Qualifiers::OCL_Autoreleasing:
1270 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1271 << ValType << FirstArg->getSourceRange();
1275 // Strip any qualifiers off ValType.
1276 ValType = ValType.getUnqualifiedType();
1278 // The majority of builtins return a value, but a few have special return
1279 // types, so allow them to override appropriately below.
1280 QualType ResultType = ValType;
1282 // We need to figure out which concrete builtin this maps onto. For example,
1283 // __sync_fetch_and_add with a 2 byte object turns into
1284 // __sync_fetch_and_add_2.
1285 #define BUILTIN_ROW(x) \
1286 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1287 Builtin::BI##x##_8, Builtin::BI##x##_16 }
1289 static const unsigned BuiltinIndices[][5] = {
1290 BUILTIN_ROW(__sync_fetch_and_add),
1291 BUILTIN_ROW(__sync_fetch_and_sub),
1292 BUILTIN_ROW(__sync_fetch_and_or),
1293 BUILTIN_ROW(__sync_fetch_and_and),
1294 BUILTIN_ROW(__sync_fetch_and_xor),
1296 BUILTIN_ROW(__sync_add_and_fetch),
1297 BUILTIN_ROW(__sync_sub_and_fetch),
1298 BUILTIN_ROW(__sync_and_and_fetch),
1299 BUILTIN_ROW(__sync_or_and_fetch),
1300 BUILTIN_ROW(__sync_xor_and_fetch),
1302 BUILTIN_ROW(__sync_val_compare_and_swap),
1303 BUILTIN_ROW(__sync_bool_compare_and_swap),
1304 BUILTIN_ROW(__sync_lock_test_and_set),
1305 BUILTIN_ROW(__sync_lock_release),
1306 BUILTIN_ROW(__sync_swap)
1310 // Determine the index of the size.
1312 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1313 case 1: SizeIndex = 0; break;
1314 case 2: SizeIndex = 1; break;
1315 case 4: SizeIndex = 2; break;
1316 case 8: SizeIndex = 3; break;
1317 case 16: SizeIndex = 4; break;
1319 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1320 << FirstArg->getType() << FirstArg->getSourceRange();
1324 // Each of these builtins has one pointer argument, followed by some number of
1325 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1326 // that we ignore. Find out which row of BuiltinIndices to read from as well
1327 // as the number of fixed args.
1328 unsigned BuiltinID = FDecl->getBuiltinID();
1329 unsigned BuiltinIndex, NumFixed = 1;
1330 switch (BuiltinID) {
1331 default: llvm_unreachable("Unknown overloaded atomic builtin!");
1332 case Builtin::BI__sync_fetch_and_add:
1333 case Builtin::BI__sync_fetch_and_add_1:
1334 case Builtin::BI__sync_fetch_and_add_2:
1335 case Builtin::BI__sync_fetch_and_add_4:
1336 case Builtin::BI__sync_fetch_and_add_8:
1337 case Builtin::BI__sync_fetch_and_add_16:
1341 case Builtin::BI__sync_fetch_and_sub:
1342 case Builtin::BI__sync_fetch_and_sub_1:
1343 case Builtin::BI__sync_fetch_and_sub_2:
1344 case Builtin::BI__sync_fetch_and_sub_4:
1345 case Builtin::BI__sync_fetch_and_sub_8:
1346 case Builtin::BI__sync_fetch_and_sub_16:
1350 case Builtin::BI__sync_fetch_and_or:
1351 case Builtin::BI__sync_fetch_and_or_1:
1352 case Builtin::BI__sync_fetch_and_or_2:
1353 case Builtin::BI__sync_fetch_and_or_4:
1354 case Builtin::BI__sync_fetch_and_or_8:
1355 case Builtin::BI__sync_fetch_and_or_16:
1359 case Builtin::BI__sync_fetch_and_and:
1360 case Builtin::BI__sync_fetch_and_and_1:
1361 case Builtin::BI__sync_fetch_and_and_2:
1362 case Builtin::BI__sync_fetch_and_and_4:
1363 case Builtin::BI__sync_fetch_and_and_8:
1364 case Builtin::BI__sync_fetch_and_and_16:
1368 case Builtin::BI__sync_fetch_and_xor:
1369 case Builtin::BI__sync_fetch_and_xor_1:
1370 case Builtin::BI__sync_fetch_and_xor_2:
1371 case Builtin::BI__sync_fetch_and_xor_4:
1372 case Builtin::BI__sync_fetch_and_xor_8:
1373 case Builtin::BI__sync_fetch_and_xor_16:
1377 case Builtin::BI__sync_add_and_fetch:
1378 case Builtin::BI__sync_add_and_fetch_1:
1379 case Builtin::BI__sync_add_and_fetch_2:
1380 case Builtin::BI__sync_add_and_fetch_4:
1381 case Builtin::BI__sync_add_and_fetch_8:
1382 case Builtin::BI__sync_add_and_fetch_16:
1386 case Builtin::BI__sync_sub_and_fetch:
1387 case Builtin::BI__sync_sub_and_fetch_1:
1388 case Builtin::BI__sync_sub_and_fetch_2:
1389 case Builtin::BI__sync_sub_and_fetch_4:
1390 case Builtin::BI__sync_sub_and_fetch_8:
1391 case Builtin::BI__sync_sub_and_fetch_16:
1395 case Builtin::BI__sync_and_and_fetch:
1396 case Builtin::BI__sync_and_and_fetch_1:
1397 case Builtin::BI__sync_and_and_fetch_2:
1398 case Builtin::BI__sync_and_and_fetch_4:
1399 case Builtin::BI__sync_and_and_fetch_8:
1400 case Builtin::BI__sync_and_and_fetch_16:
1404 case Builtin::BI__sync_or_and_fetch:
1405 case Builtin::BI__sync_or_and_fetch_1:
1406 case Builtin::BI__sync_or_and_fetch_2:
1407 case Builtin::BI__sync_or_and_fetch_4:
1408 case Builtin::BI__sync_or_and_fetch_8:
1409 case Builtin::BI__sync_or_and_fetch_16:
1413 case Builtin::BI__sync_xor_and_fetch:
1414 case Builtin::BI__sync_xor_and_fetch_1:
1415 case Builtin::BI__sync_xor_and_fetch_2:
1416 case Builtin::BI__sync_xor_and_fetch_4:
1417 case Builtin::BI__sync_xor_and_fetch_8:
1418 case Builtin::BI__sync_xor_and_fetch_16:
1422 case Builtin::BI__sync_val_compare_and_swap:
1423 case Builtin::BI__sync_val_compare_and_swap_1:
1424 case Builtin::BI__sync_val_compare_and_swap_2:
1425 case Builtin::BI__sync_val_compare_and_swap_4:
1426 case Builtin::BI__sync_val_compare_and_swap_8:
1427 case Builtin::BI__sync_val_compare_and_swap_16:
1432 case Builtin::BI__sync_bool_compare_and_swap:
1433 case Builtin::BI__sync_bool_compare_and_swap_1:
1434 case Builtin::BI__sync_bool_compare_and_swap_2:
1435 case Builtin::BI__sync_bool_compare_and_swap_4:
1436 case Builtin::BI__sync_bool_compare_and_swap_8:
1437 case Builtin::BI__sync_bool_compare_and_swap_16:
1440 ResultType = Context.BoolTy;
1443 case Builtin::BI__sync_lock_test_and_set:
1444 case Builtin::BI__sync_lock_test_and_set_1:
1445 case Builtin::BI__sync_lock_test_and_set_2:
1446 case Builtin::BI__sync_lock_test_and_set_4:
1447 case Builtin::BI__sync_lock_test_and_set_8:
1448 case Builtin::BI__sync_lock_test_and_set_16:
1452 case Builtin::BI__sync_lock_release:
1453 case Builtin::BI__sync_lock_release_1:
1454 case Builtin::BI__sync_lock_release_2:
1455 case Builtin::BI__sync_lock_release_4:
1456 case Builtin::BI__sync_lock_release_8:
1457 case Builtin::BI__sync_lock_release_16:
1460 ResultType = Context.VoidTy;
1463 case Builtin::BI__sync_swap:
1464 case Builtin::BI__sync_swap_1:
1465 case Builtin::BI__sync_swap_2:
1466 case Builtin::BI__sync_swap_4:
1467 case Builtin::BI__sync_swap_8:
1468 case Builtin::BI__sync_swap_16:
1473 // Now that we know how many fixed arguments we expect, first check that we
1474 // have at least that many.
1475 if (TheCall->getNumArgs() < 1+NumFixed) {
1476 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1477 << 0 << 1+NumFixed << TheCall->getNumArgs()
1478 << TheCall->getCallee()->getSourceRange();
1482 // Get the decl for the concrete builtin from this, we can tell what the
1483 // concrete integer type we should convert to is.
1484 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1485 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1486 FunctionDecl *NewBuiltinDecl;
1487 if (NewBuiltinID == BuiltinID)
1488 NewBuiltinDecl = FDecl;
1490 // Perform builtin lookup to avoid redeclaring it.
1491 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1492 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1493 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1494 assert(Res.getFoundDecl());
1495 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1496 if (NewBuiltinDecl == 0)
1500 // The first argument --- the pointer --- has a fixed type; we
1501 // deduce the types of the rest of the arguments accordingly. Walk
1502 // the remaining arguments, converting them to the deduced value type.
1503 for (unsigned i = 0; i != NumFixed; ++i) {
1504 ExprResult Arg = TheCall->getArg(i+1);
1506 // GCC does an implicit conversion to the pointer or integer ValType. This
1507 // can fail in some cases (1i -> int**), check for this error case now.
1508 // Initialize the argument.
1509 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1510 ValType, /*consume*/ false);
1511 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1512 if (Arg.isInvalid())
1515 // Okay, we have something that *can* be converted to the right type. Check
1516 // to see if there is a potentially weird extension going on here. This can
1517 // happen when you do an atomic operation on something like an char* and
1518 // pass in 42. The 42 gets converted to char. This is even more strange
1519 // for things like 45.123 -> char, etc.
1520 // FIXME: Do this check.
1521 TheCall->setArg(i+1, Arg.take());
1524 ASTContext& Context = this->getASTContext();
1526 // Create a new DeclRefExpr to refer to the new decl.
1527 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1529 DRE->getQualifierLoc(),
1532 /*enclosing*/ false,
1534 Context.BuiltinFnTy,
1535 DRE->getValueKind());
1537 // Set the callee in the CallExpr.
1538 // FIXME: This loses syntactic information.
1539 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1540 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1541 CK_BuiltinFnToFnPtr);
1542 TheCall->setCallee(PromotedCall.take());
1544 // Change the result type of the call to match the original value type. This
1545 // is arbitrary, but the codegen for these builtins ins design to handle it
1547 TheCall->setType(ResultType);
1549 return TheCallResult;
1552 /// CheckObjCString - Checks that the argument to the builtin
1553 /// CFString constructor is correct
1554 /// Note: It might also make sense to do the UTF-16 conversion here (would
1555 /// simplify the backend).
1556 bool Sema::CheckObjCString(Expr *Arg) {
1557 Arg = Arg->IgnoreParenCasts();
1558 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1560 if (!Literal || !Literal->isAscii()) {
1561 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1562 << Arg->getSourceRange();
1566 if (Literal->containsNonAsciiOrNull()) {
1567 StringRef String = Literal->getString();
1568 unsigned NumBytes = String.size();
1569 SmallVector<UTF16, 128> ToBuf(NumBytes);
1570 const UTF8 *FromPtr = (const UTF8 *)String.data();
1571 UTF16 *ToPtr = &ToBuf[0];
1573 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1574 &ToPtr, ToPtr + NumBytes,
1576 // Check for conversion failure.
1577 if (Result != conversionOK)
1578 Diag(Arg->getLocStart(),
1579 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1584 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1585 /// Emit an error and return true on failure, return false on success.
1586 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1587 Expr *Fn = TheCall->getCallee();
1588 if (TheCall->getNumArgs() > 2) {
1589 Diag(TheCall->getArg(2)->getLocStart(),
1590 diag::err_typecheck_call_too_many_args)
1591 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1592 << Fn->getSourceRange()
1593 << SourceRange(TheCall->getArg(2)->getLocStart(),
1594 (*(TheCall->arg_end()-1))->getLocEnd());
1598 if (TheCall->getNumArgs() < 2) {
1599 return Diag(TheCall->getLocEnd(),
1600 diag::err_typecheck_call_too_few_args_at_least)
1601 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1604 // Type-check the first argument normally.
1605 if (checkBuiltinArgument(*this, TheCall, 0))
1608 // Determine whether the current function is variadic or not.
1609 BlockScopeInfo *CurBlock = getCurBlock();
1612 isVariadic = CurBlock->TheDecl->isVariadic();
1613 else if (FunctionDecl *FD = getCurFunctionDecl())
1614 isVariadic = FD->isVariadic();
1616 isVariadic = getCurMethodDecl()->isVariadic();
1619 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1623 // Verify that the second argument to the builtin is the last argument of the
1624 // current function or method.
1625 bool SecondArgIsLastNamedArgument = false;
1626 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1628 // These are valid if SecondArgIsLastNamedArgument is false after the next
1631 SourceLocation ParamLoc;
1633 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1634 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1635 // FIXME: This isn't correct for methods (results in bogus warning).
1636 // Get the last formal in the current function.
1637 const ParmVarDecl *LastArg;
1639 LastArg = *(CurBlock->TheDecl->param_end()-1);
1640 else if (FunctionDecl *FD = getCurFunctionDecl())
1641 LastArg = *(FD->param_end()-1);
1643 LastArg = *(getCurMethodDecl()->param_end()-1);
1644 SecondArgIsLastNamedArgument = PV == LastArg;
1646 Type = PV->getType();
1647 ParamLoc = PV->getLocation();
1651 if (!SecondArgIsLastNamedArgument)
1652 Diag(TheCall->getArg(1)->getLocStart(),
1653 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1654 else if (Type->isReferenceType()) {
1655 Diag(Arg->getLocStart(),
1656 diag::warn_va_start_of_reference_type_is_undefined);
1657 Diag(ParamLoc, diag::note_parameter_type) << Type;
1660 TheCall->setType(Context.VoidTy);
1664 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1665 /// friends. This is declared to take (...), so we have to check everything.
1666 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1667 if (TheCall->getNumArgs() < 2)
1668 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1669 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1670 if (TheCall->getNumArgs() > 2)
1671 return Diag(TheCall->getArg(2)->getLocStart(),
1672 diag::err_typecheck_call_too_many_args)
1673 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1674 << SourceRange(TheCall->getArg(2)->getLocStart(),
1675 (*(TheCall->arg_end()-1))->getLocEnd());
1677 ExprResult OrigArg0 = TheCall->getArg(0);
1678 ExprResult OrigArg1 = TheCall->getArg(1);
1680 // Do standard promotions between the two arguments, returning their common
1682 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1683 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1686 // Make sure any conversions are pushed back into the call; this is
1687 // type safe since unordered compare builtins are declared as "_Bool
1689 TheCall->setArg(0, OrigArg0.get());
1690 TheCall->setArg(1, OrigArg1.get());
1692 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1695 // If the common type isn't a real floating type, then the arguments were
1696 // invalid for this operation.
1697 if (Res.isNull() || !Res->isRealFloatingType())
1698 return Diag(OrigArg0.get()->getLocStart(),
1699 diag::err_typecheck_call_invalid_ordered_compare)
1700 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1701 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1706 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1707 /// __builtin_isnan and friends. This is declared to take (...), so we have
1708 /// to check everything. We expect the last argument to be a floating point
1710 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1711 if (TheCall->getNumArgs() < NumArgs)
1712 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1713 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1714 if (TheCall->getNumArgs() > NumArgs)
1715 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1716 diag::err_typecheck_call_too_many_args)
1717 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1718 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1719 (*(TheCall->arg_end()-1))->getLocEnd());
1721 Expr *OrigArg = TheCall->getArg(NumArgs-1);
1723 if (OrigArg->isTypeDependent())
1726 // This operation requires a non-_Complex floating-point number.
1727 if (!OrigArg->getType()->isRealFloatingType())
1728 return Diag(OrigArg->getLocStart(),
1729 diag::err_typecheck_call_invalid_unary_fp)
1730 << OrigArg->getType() << OrigArg->getSourceRange();
1732 // If this is an implicit conversion from float -> double, remove it.
1733 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1734 Expr *CastArg = Cast->getSubExpr();
1735 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1736 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1737 "promotion from float to double is the only expected cast here");
1738 Cast->setSubExpr(0);
1739 TheCall->setArg(NumArgs-1, CastArg);
1746 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1747 // This is declared to take (...), so we have to check everything.
1748 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1749 if (TheCall->getNumArgs() < 2)
1750 return ExprError(Diag(TheCall->getLocEnd(),
1751 diag::err_typecheck_call_too_few_args_at_least)
1752 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1753 << TheCall->getSourceRange());
1755 // Determine which of the following types of shufflevector we're checking:
1756 // 1) unary, vector mask: (lhs, mask)
1757 // 2) binary, vector mask: (lhs, rhs, mask)
1758 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1759 QualType resType = TheCall->getArg(0)->getType();
1760 unsigned numElements = 0;
1762 if (!TheCall->getArg(0)->isTypeDependent() &&
1763 !TheCall->getArg(1)->isTypeDependent()) {
1764 QualType LHSType = TheCall->getArg(0)->getType();
1765 QualType RHSType = TheCall->getArg(1)->getType();
1767 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1768 return ExprError(Diag(TheCall->getLocStart(),
1769 diag::err_shufflevector_non_vector)
1770 << SourceRange(TheCall->getArg(0)->getLocStart(),
1771 TheCall->getArg(1)->getLocEnd()));
1773 numElements = LHSType->getAs<VectorType>()->getNumElements();
1774 unsigned numResElements = TheCall->getNumArgs() - 2;
1776 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1777 // with mask. If so, verify that RHS is an integer vector type with the
1778 // same number of elts as lhs.
1779 if (TheCall->getNumArgs() == 2) {
1780 if (!RHSType->hasIntegerRepresentation() ||
1781 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1782 return ExprError(Diag(TheCall->getLocStart(),
1783 diag::err_shufflevector_incompatible_vector)
1784 << SourceRange(TheCall->getArg(1)->getLocStart(),
1785 TheCall->getArg(1)->getLocEnd()));
1786 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1787 return ExprError(Diag(TheCall->getLocStart(),
1788 diag::err_shufflevector_incompatible_vector)
1789 << SourceRange(TheCall->getArg(0)->getLocStart(),
1790 TheCall->getArg(1)->getLocEnd()));
1791 } else if (numElements != numResElements) {
1792 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1793 resType = Context.getVectorType(eltType, numResElements,
1794 VectorType::GenericVector);
1798 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1799 if (TheCall->getArg(i)->isTypeDependent() ||
1800 TheCall->getArg(i)->isValueDependent())
1803 llvm::APSInt Result(32);
1804 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1805 return ExprError(Diag(TheCall->getLocStart(),
1806 diag::err_shufflevector_nonconstant_argument)
1807 << TheCall->getArg(i)->getSourceRange());
1809 // Allow -1 which will be translated to undef in the IR.
1810 if (Result.isSigned() && Result.isAllOnesValue())
1813 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1814 return ExprError(Diag(TheCall->getLocStart(),
1815 diag::err_shufflevector_argument_too_large)
1816 << TheCall->getArg(i)->getSourceRange());
1819 SmallVector<Expr*, 32> exprs;
1821 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1822 exprs.push_back(TheCall->getArg(i));
1823 TheCall->setArg(i, 0);
1826 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
1827 TheCall->getCallee()->getLocStart(),
1828 TheCall->getRParenLoc()));
1831 /// SemaConvertVectorExpr - Handle __builtin_convertvector
1832 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1833 SourceLocation BuiltinLoc,
1834 SourceLocation RParenLoc) {
1835 ExprValueKind VK = VK_RValue;
1836 ExprObjectKind OK = OK_Ordinary;
1837 QualType DstTy = TInfo->getType();
1838 QualType SrcTy = E->getType();
1840 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1841 return ExprError(Diag(BuiltinLoc,
1842 diag::err_convertvector_non_vector)
1843 << E->getSourceRange());
1844 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1845 return ExprError(Diag(BuiltinLoc,
1846 diag::err_convertvector_non_vector_type));
1848 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1849 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1850 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1851 if (SrcElts != DstElts)
1852 return ExprError(Diag(BuiltinLoc,
1853 diag::err_convertvector_incompatible_vector)
1854 << E->getSourceRange());
1857 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1858 BuiltinLoc, RParenLoc));
1862 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1863 // This is declared to take (const void*, ...) and can take two
1864 // optional constant int args.
1865 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1866 unsigned NumArgs = TheCall->getNumArgs();
1869 return Diag(TheCall->getLocEnd(),
1870 diag::err_typecheck_call_too_many_args_at_most)
1871 << 0 /*function call*/ << 3 << NumArgs
1872 << TheCall->getSourceRange();
1874 // Argument 0 is checked for us and the remaining arguments must be
1875 // constant integers.
1876 for (unsigned i = 1; i != NumArgs; ++i) {
1877 Expr *Arg = TheCall->getArg(i);
1879 // We can't check the value of a dependent argument.
1880 if (Arg->isTypeDependent() || Arg->isValueDependent())
1883 llvm::APSInt Result;
1884 if (SemaBuiltinConstantArg(TheCall, i, Result))
1887 // FIXME: gcc issues a warning and rewrites these to 0. These
1888 // seems especially odd for the third argument since the default
1891 if (Result.getLimitedValue() > 1)
1892 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1893 << "0" << "1" << Arg->getSourceRange();
1895 if (Result.getLimitedValue() > 3)
1896 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1897 << "0" << "3" << Arg->getSourceRange();
1904 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1905 /// TheCall is a constant expression.
1906 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1907 llvm::APSInt &Result) {
1908 Expr *Arg = TheCall->getArg(ArgNum);
1909 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1910 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1912 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1914 if (!Arg->isIntegerConstantExpr(Result, Context))
1915 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1916 << FDecl->getDeclName() << Arg->getSourceRange();
1921 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1922 /// int type). This simply type checks that type is one of the defined
1923 /// constants (0-3).
1924 // For compatibility check 0-3, llvm only handles 0 and 2.
1925 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1926 llvm::APSInt Result;
1928 // We can't check the value of a dependent argument.
1929 if (TheCall->getArg(1)->isTypeDependent() ||
1930 TheCall->getArg(1)->isValueDependent())
1933 // Check constant-ness first.
1934 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1937 Expr *Arg = TheCall->getArg(1);
1938 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1939 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1940 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1946 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1947 /// This checks that val is a constant 1.
1948 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1949 Expr *Arg = TheCall->getArg(1);
1950 llvm::APSInt Result;
1952 // TODO: This is less than ideal. Overload this to take a value.
1953 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1957 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1958 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1964 enum StringLiteralCheckType {
1966 SLCT_UncheckedLiteral,
1971 // Determine if an expression is a string literal or constant string.
1972 // If this function returns false on the arguments to a function expecting a
1973 // format string, we will usually need to emit a warning.
1974 // True string literals are then checked by CheckFormatString.
1975 static StringLiteralCheckType
1976 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1977 bool HasVAListArg, unsigned format_idx,
1978 unsigned firstDataArg, Sema::FormatStringType Type,
1979 Sema::VariadicCallType CallType, bool InFunctionCall,
1980 llvm::SmallBitVector &CheckedVarArgs) {
1982 if (E->isTypeDependent() || E->isValueDependent())
1983 return SLCT_NotALiteral;
1985 E = E->IgnoreParenCasts();
1987 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
1988 // Technically -Wformat-nonliteral does not warn about this case.
1989 // The behavior of printf and friends in this case is implementation
1990 // dependent. Ideally if the format string cannot be null then
1991 // it should have a 'nonnull' attribute in the function prototype.
1992 return SLCT_UncheckedLiteral;
1994 switch (E->getStmtClass()) {
1995 case Stmt::BinaryConditionalOperatorClass:
1996 case Stmt::ConditionalOperatorClass: {
1997 // The expression is a literal if both sub-expressions were, and it was
1998 // completely checked only if both sub-expressions were checked.
1999 const AbstractConditionalOperator *C =
2000 cast<AbstractConditionalOperator>(E);
2001 StringLiteralCheckType Left =
2002 checkFormatStringExpr(S, C->getTrueExpr(), Args,
2003 HasVAListArg, format_idx, firstDataArg,
2004 Type, CallType, InFunctionCall, CheckedVarArgs);
2005 if (Left == SLCT_NotALiteral)
2006 return SLCT_NotALiteral;
2007 StringLiteralCheckType Right =
2008 checkFormatStringExpr(S, C->getFalseExpr(), Args,
2009 HasVAListArg, format_idx, firstDataArg,
2010 Type, CallType, InFunctionCall, CheckedVarArgs);
2011 return Left < Right ? Left : Right;
2014 case Stmt::ImplicitCastExprClass: {
2015 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2019 case Stmt::OpaqueValueExprClass:
2020 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2024 return SLCT_NotALiteral;
2026 case Stmt::PredefinedExprClass:
2027 // While __func__, etc., are technically not string literals, they
2028 // cannot contain format specifiers and thus are not a security
2030 return SLCT_UncheckedLiteral;
2032 case Stmt::DeclRefExprClass: {
2033 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2035 // As an exception, do not flag errors for variables binding to
2036 // const string literals.
2037 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2038 bool isConstant = false;
2039 QualType T = DR->getType();
2041 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2042 isConstant = AT->getElementType().isConstant(S.Context);
2043 } else if (const PointerType *PT = T->getAs<PointerType>()) {
2044 isConstant = T.isConstant(S.Context) &&
2045 PT->getPointeeType().isConstant(S.Context);
2046 } else if (T->isObjCObjectPointerType()) {
2047 // In ObjC, there is usually no "const ObjectPointer" type,
2048 // so don't check if the pointee type is constant.
2049 isConstant = T.isConstant(S.Context);
2053 if (const Expr *Init = VD->getAnyInitializer()) {
2054 // Look through initializers like const char c[] = { "foo" }
2055 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2056 if (InitList->isStringLiteralInit())
2057 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2059 return checkFormatStringExpr(S, Init, Args,
2060 HasVAListArg, format_idx,
2061 firstDataArg, Type, CallType,
2062 /*InFunctionCall*/false, CheckedVarArgs);
2066 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2067 // special check to see if the format string is a function parameter
2068 // of the function calling the printf function. If the function
2069 // has an attribute indicating it is a printf-like function, then we
2070 // should suppress warnings concerning non-literals being used in a call
2071 // to a vprintf function. For example:
2074 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2076 // va_start(ap, fmt);
2077 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2081 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2082 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2083 int PVIndex = PV->getFunctionScopeIndex() + 1;
2084 for (specific_attr_iterator<FormatAttr>
2085 i = ND->specific_attr_begin<FormatAttr>(),
2086 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2087 FormatAttr *PVFormat = *i;
2088 // adjust for implicit parameter
2089 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2090 if (MD->isInstance())
2092 // We also check if the formats are compatible.
2093 // We can't pass a 'scanf' string to a 'printf' function.
2094 if (PVIndex == PVFormat->getFormatIdx() &&
2095 Type == S.GetFormatStringType(PVFormat))
2096 return SLCT_UncheckedLiteral;
2103 return SLCT_NotALiteral;
2106 case Stmt::CallExprClass:
2107 case Stmt::CXXMemberCallExprClass: {
2108 const CallExpr *CE = cast<CallExpr>(E);
2109 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2110 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2111 unsigned ArgIndex = FA->getFormatIdx();
2112 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2113 if (MD->isInstance())
2115 const Expr *Arg = CE->getArg(ArgIndex - 1);
2117 return checkFormatStringExpr(S, Arg, Args,
2118 HasVAListArg, format_idx, firstDataArg,
2119 Type, CallType, InFunctionCall,
2121 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2122 unsigned BuiltinID = FD->getBuiltinID();
2123 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2124 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2125 const Expr *Arg = CE->getArg(0);
2126 return checkFormatStringExpr(S, Arg, Args,
2127 HasVAListArg, format_idx,
2128 firstDataArg, Type, CallType,
2129 InFunctionCall, CheckedVarArgs);
2134 return SLCT_NotALiteral;
2137 case Stmt::ObjCMessageExprClass: {
2138 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(E);
2139 if (const ObjCMethodDecl *MDecl = ME->getMethodDecl()) {
2140 if (const NamedDecl *ND = dyn_cast<NamedDecl>(MDecl)) {
2141 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2142 unsigned ArgIndex = FA->getFormatIdx();
2143 if (ArgIndex <= ME->getNumArgs()) {
2144 const Expr *Arg = ME->getArg(ArgIndex-1);
2145 return checkFormatStringExpr(S, Arg, Args,
2146 HasVAListArg, format_idx,
2147 firstDataArg, Type, CallType,
2148 InFunctionCall, CheckedVarArgs);
2154 return SLCT_NotALiteral;
2157 case Stmt::ObjCStringLiteralClass:
2158 case Stmt::StringLiteralClass: {
2159 const StringLiteral *StrE = NULL;
2161 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2162 StrE = ObjCFExpr->getString();
2164 StrE = cast<StringLiteral>(E);
2167 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2168 Type, InFunctionCall, CallType, CheckedVarArgs);
2169 return SLCT_CheckedLiteral;
2172 return SLCT_NotALiteral;
2176 return SLCT_NotALiteral;
2181 Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
2182 const Expr * const *ExprArgs,
2183 SourceLocation CallSiteLoc) {
2184 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2185 e = NonNull->args_end();
2187 const Expr *ArgExpr = ExprArgs[*i];
2189 // As a special case, transparent unions initialized with zero are
2190 // considered null for the purposes of the nonnull attribute.
2191 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2192 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2193 if (const CompoundLiteralExpr *CLE =
2194 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2195 if (const InitListExpr *ILE =
2196 dyn_cast<InitListExpr>(CLE->getInitializer()))
2197 ArgExpr = ILE->getInit(0);
2201 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
2202 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
2206 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2207 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2208 .Case("scanf", FST_Scanf)
2209 .Cases("printf", "printf0", FST_Printf)
2210 .Cases("NSString", "CFString", FST_NSString)
2211 .Case("strftime", FST_Strftime)
2212 .Case("strfmon", FST_Strfmon)
2213 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2214 .Default(FST_Unknown);
2217 /// CheckFormatArguments - Check calls to printf and scanf (and similar
2218 /// functions) for correct use of format strings.
2219 /// Returns true if a format string has been fully checked.
2220 bool Sema::CheckFormatArguments(const FormatAttr *Format,
2221 ArrayRef<const Expr *> Args,
2223 VariadicCallType CallType,
2224 SourceLocation Loc, SourceRange Range,
2225 llvm::SmallBitVector &CheckedVarArgs) {
2226 FormatStringInfo FSI;
2227 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2228 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2229 FSI.FirstDataArg, GetFormatStringType(Format),
2230 CallType, Loc, Range, CheckedVarArgs);
2234 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2235 bool HasVAListArg, unsigned format_idx,
2236 unsigned firstDataArg, FormatStringType Type,
2237 VariadicCallType CallType,
2238 SourceLocation Loc, SourceRange Range,
2239 llvm::SmallBitVector &CheckedVarArgs) {
2240 // CHECK: printf/scanf-like function is called with no format string.
2241 if (format_idx >= Args.size()) {
2242 Diag(Loc, diag::warn_missing_format_string) << Range;
2246 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2248 // CHECK: format string is not a string literal.
2250 // Dynamically generated format strings are difficult to
2251 // automatically vet at compile time. Requiring that format strings
2252 // are string literals: (1) permits the checking of format strings by
2253 // the compiler and thereby (2) can practically remove the source of
2254 // many format string exploits.
2256 // Format string can be either ObjC string (e.g. @"%d") or
2257 // C string (e.g. "%d")
2258 // ObjC string uses the same format specifiers as C string, so we can use
2259 // the same format string checking logic for both ObjC and C strings.
2260 StringLiteralCheckType CT =
2261 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2262 format_idx, firstDataArg, Type, CallType,
2263 /*IsFunctionCall*/true, CheckedVarArgs);
2264 if (CT != SLCT_NotALiteral)
2265 // Literal format string found, check done!
2266 return CT == SLCT_CheckedLiteral;
2268 // Strftime is particular as it always uses a single 'time' argument,
2269 // so it is safe to pass a non-literal string.
2270 if (Type == FST_Strftime)
2273 // Do not emit diag when the string param is a macro expansion and the
2274 // format is either NSString or CFString. This is a hack to prevent
2275 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2276 // which are usually used in place of NS and CF string literals.
2277 if (Type == FST_NSString &&
2278 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2281 // If there are no arguments specified, warn with -Wformat-security, otherwise
2282 // warn only with -Wformat-nonliteral.
2283 if (Args.size() == firstDataArg)
2284 Diag(Args[format_idx]->getLocStart(),
2285 diag::warn_format_nonliteral_noargs)
2286 << OrigFormatExpr->getSourceRange();
2288 Diag(Args[format_idx]->getLocStart(),
2289 diag::warn_format_nonliteral)
2290 << OrigFormatExpr->getSourceRange();
2295 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2298 const StringLiteral *FExpr;
2299 const Expr *OrigFormatExpr;
2300 const unsigned FirstDataArg;
2301 const unsigned NumDataArgs;
2302 const char *Beg; // Start of format string.
2303 const bool HasVAListArg;
2304 ArrayRef<const Expr *> Args;
2306 llvm::SmallBitVector CoveredArgs;
2307 bool usesPositionalArgs;
2309 bool inFunctionCall;
2310 Sema::VariadicCallType CallType;
2311 llvm::SmallBitVector &CheckedVarArgs;
2313 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2314 const Expr *origFormatExpr, unsigned firstDataArg,
2315 unsigned numDataArgs, const char *beg, bool hasVAListArg,
2316 ArrayRef<const Expr *> Args,
2317 unsigned formatIdx, bool inFunctionCall,
2318 Sema::VariadicCallType callType,
2319 llvm::SmallBitVector &CheckedVarArgs)
2320 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2321 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2322 Beg(beg), HasVAListArg(hasVAListArg),
2323 Args(Args), FormatIdx(formatIdx),
2324 usesPositionalArgs(false), atFirstArg(true),
2325 inFunctionCall(inFunctionCall), CallType(callType),
2326 CheckedVarArgs(CheckedVarArgs) {
2327 CoveredArgs.resize(numDataArgs);
2328 CoveredArgs.reset();
2331 void DoneProcessing();
2333 void HandleIncompleteSpecifier(const char *startSpecifier,
2334 unsigned specifierLen);
2336 void HandleInvalidLengthModifier(
2337 const analyze_format_string::FormatSpecifier &FS,
2338 const analyze_format_string::ConversionSpecifier &CS,
2339 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
2341 void HandleNonStandardLengthModifier(
2342 const analyze_format_string::FormatSpecifier &FS,
2343 const char *startSpecifier, unsigned specifierLen);
2345 void HandleNonStandardConversionSpecifier(
2346 const analyze_format_string::ConversionSpecifier &CS,
2347 const char *startSpecifier, unsigned specifierLen);
2349 virtual void HandlePosition(const char *startPos, unsigned posLen);
2351 virtual void HandleInvalidPosition(const char *startSpecifier,
2352 unsigned specifierLen,
2353 analyze_format_string::PositionContext p);
2355 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2357 void HandleNullChar(const char *nullCharacter);
2359 template <typename Range>
2360 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2361 const Expr *ArgumentExpr,
2362 PartialDiagnostic PDiag,
2363 SourceLocation StringLoc,
2364 bool IsStringLocation, Range StringRange,
2365 ArrayRef<FixItHint> Fixit = None);
2368 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2369 const char *startSpec,
2370 unsigned specifierLen,
2371 const char *csStart, unsigned csLen);
2373 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2374 const char *startSpec,
2375 unsigned specifierLen);
2377 SourceRange getFormatStringRange();
2378 CharSourceRange getSpecifierRange(const char *startSpecifier,
2379 unsigned specifierLen);
2380 SourceLocation getLocationOfByte(const char *x);
2382 const Expr *getDataArg(unsigned i) const;
2384 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2385 const analyze_format_string::ConversionSpecifier &CS,
2386 const char *startSpecifier, unsigned specifierLen,
2389 template <typename Range>
2390 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2391 bool IsStringLocation, Range StringRange,
2392 ArrayRef<FixItHint> Fixit = None);
2394 void CheckPositionalAndNonpositionalArgs(
2395 const analyze_format_string::FormatSpecifier *FS);
2399 SourceRange CheckFormatHandler::getFormatStringRange() {
2400 return OrigFormatExpr->getSourceRange();
2403 CharSourceRange CheckFormatHandler::
2404 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2405 SourceLocation Start = getLocationOfByte(startSpecifier);
2406 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2408 // Advance the end SourceLocation by one due to half-open ranges.
2409 End = End.getLocWithOffset(1);
2411 return CharSourceRange::getCharRange(Start, End);
2414 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2415 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2418 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2419 unsigned specifierLen){
2420 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2421 getLocationOfByte(startSpecifier),
2422 /*IsStringLocation*/true,
2423 getSpecifierRange(startSpecifier, specifierLen));
2426 void CheckFormatHandler::HandleInvalidLengthModifier(
2427 const analyze_format_string::FormatSpecifier &FS,
2428 const analyze_format_string::ConversionSpecifier &CS,
2429 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2430 using namespace analyze_format_string;
2432 const LengthModifier &LM = FS.getLengthModifier();
2433 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2435 // See if we know how to fix this length modifier.
2436 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2438 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2439 getLocationOfByte(LM.getStart()),
2440 /*IsStringLocation*/true,
2441 getSpecifierRange(startSpecifier, specifierLen));
2443 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2444 << FixedLM->toString()
2445 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2449 if (DiagID == diag::warn_format_nonsensical_length)
2450 Hint = FixItHint::CreateRemoval(LMRange);
2452 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2453 getLocationOfByte(LM.getStart()),
2454 /*IsStringLocation*/true,
2455 getSpecifierRange(startSpecifier, specifierLen),
2460 void CheckFormatHandler::HandleNonStandardLengthModifier(
2461 const analyze_format_string::FormatSpecifier &FS,
2462 const char *startSpecifier, unsigned specifierLen) {
2463 using namespace analyze_format_string;
2465 const LengthModifier &LM = FS.getLengthModifier();
2466 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2468 // See if we know how to fix this length modifier.
2469 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2471 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2472 << LM.toString() << 0,
2473 getLocationOfByte(LM.getStart()),
2474 /*IsStringLocation*/true,
2475 getSpecifierRange(startSpecifier, specifierLen));
2477 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2478 << FixedLM->toString()
2479 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2482 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2483 << LM.toString() << 0,
2484 getLocationOfByte(LM.getStart()),
2485 /*IsStringLocation*/true,
2486 getSpecifierRange(startSpecifier, specifierLen));
2490 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2491 const analyze_format_string::ConversionSpecifier &CS,
2492 const char *startSpecifier, unsigned specifierLen) {
2493 using namespace analyze_format_string;
2495 // See if we know how to fix this conversion specifier.
2496 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2498 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2499 << CS.toString() << /*conversion specifier*/1,
2500 getLocationOfByte(CS.getStart()),
2501 /*IsStringLocation*/true,
2502 getSpecifierRange(startSpecifier, specifierLen));
2504 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2505 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2506 << FixedCS->toString()
2507 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2509 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2510 << CS.toString() << /*conversion specifier*/1,
2511 getLocationOfByte(CS.getStart()),
2512 /*IsStringLocation*/true,
2513 getSpecifierRange(startSpecifier, specifierLen));
2517 void CheckFormatHandler::HandlePosition(const char *startPos,
2519 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2520 getLocationOfByte(startPos),
2521 /*IsStringLocation*/true,
2522 getSpecifierRange(startPos, posLen));
2526 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2527 analyze_format_string::PositionContext p) {
2528 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2530 getLocationOfByte(startPos), /*IsStringLocation*/true,
2531 getSpecifierRange(startPos, posLen));
2534 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2536 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2537 getLocationOfByte(startPos),
2538 /*IsStringLocation*/true,
2539 getSpecifierRange(startPos, posLen));
2542 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2543 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2544 // The presence of a null character is likely an error.
2545 EmitFormatDiagnostic(
2546 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2547 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2548 getFormatStringRange());
2552 // Note that this may return NULL if there was an error parsing or building
2553 // one of the argument expressions.
2554 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2555 return Args[FirstDataArg + i];
2558 void CheckFormatHandler::DoneProcessing() {
2559 // Does the number of data arguments exceed the number of
2560 // format conversions in the format string?
2561 if (!HasVAListArg) {
2562 // Find any arguments that weren't covered.
2564 signed notCoveredArg = CoveredArgs.find_first();
2565 if (notCoveredArg >= 0) {
2566 assert((unsigned)notCoveredArg < NumDataArgs);
2567 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2568 SourceLocation Loc = E->getLocStart();
2569 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2570 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2571 Loc, /*IsStringLocation*/false,
2572 getFormatStringRange());
2580 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2582 const char *startSpec,
2583 unsigned specifierLen,
2584 const char *csStart,
2587 bool keepGoing = true;
2588 if (argIndex < NumDataArgs) {
2589 // Consider the argument coverered, even though the specifier doesn't
2591 CoveredArgs.set(argIndex);
2594 // If argIndex exceeds the number of data arguments we
2595 // don't issue a warning because that is just a cascade of warnings (and
2596 // they may have intended '%%' anyway). We don't want to continue processing
2597 // the format string after this point, however, as we will like just get
2598 // gibberish when trying to match arguments.
2602 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2603 << StringRef(csStart, csLen),
2604 Loc, /*IsStringLocation*/true,
2605 getSpecifierRange(startSpec, specifierLen));
2611 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2612 const char *startSpec,
2613 unsigned specifierLen) {
2614 EmitFormatDiagnostic(
2615 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2616 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2620 CheckFormatHandler::CheckNumArgs(
2621 const analyze_format_string::FormatSpecifier &FS,
2622 const analyze_format_string::ConversionSpecifier &CS,
2623 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2625 if (argIndex >= NumDataArgs) {
2626 PartialDiagnostic PDiag = FS.usesPositionalArg()
2627 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2628 << (argIndex+1) << NumDataArgs)
2629 : S.PDiag(diag::warn_printf_insufficient_data_args);
2630 EmitFormatDiagnostic(
2631 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2632 getSpecifierRange(startSpecifier, specifierLen));
2638 template<typename Range>
2639 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2641 bool IsStringLocation,
2643 ArrayRef<FixItHint> FixIt) {
2644 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
2645 Loc, IsStringLocation, StringRange, FixIt);
2648 /// \brief If the format string is not within the funcion call, emit a note
2649 /// so that the function call and string are in diagnostic messages.
2651 /// \param InFunctionCall if true, the format string is within the function
2652 /// call and only one diagnostic message will be produced. Otherwise, an
2653 /// extra note will be emitted pointing to location of the format string.
2655 /// \param ArgumentExpr the expression that is passed as the format string
2656 /// argument in the function call. Used for getting locations when two
2657 /// diagnostics are emitted.
2659 /// \param PDiag the callee should already have provided any strings for the
2660 /// diagnostic message. This function only adds locations and fixits
2663 /// \param Loc primary location for diagnostic. If two diagnostics are
2664 /// required, one will be at Loc and a new SourceLocation will be created for
2667 /// \param IsStringLocation if true, Loc points to the format string should be
2668 /// used for the note. Otherwise, Loc points to the argument list and will
2669 /// be used with PDiag.
2671 /// \param StringRange some or all of the string to highlight. This is
2672 /// templated so it can accept either a CharSourceRange or a SourceRange.
2674 /// \param FixIt optional fix it hint for the format string.
2675 template<typename Range>
2676 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2677 const Expr *ArgumentExpr,
2678 PartialDiagnostic PDiag,
2680 bool IsStringLocation,
2682 ArrayRef<FixItHint> FixIt) {
2683 if (InFunctionCall) {
2684 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2686 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2691 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2692 << ArgumentExpr->getSourceRange();
2694 const Sema::SemaDiagnosticBuilder &Note =
2695 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2696 diag::note_format_string_defined);
2698 Note << StringRange;
2699 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2706 //===--- CHECK: Printf format string checking ------------------------------===//
2709 class CheckPrintfHandler : public CheckFormatHandler {
2712 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2713 const Expr *origFormatExpr, unsigned firstDataArg,
2714 unsigned numDataArgs, bool isObjC,
2715 const char *beg, bool hasVAListArg,
2716 ArrayRef<const Expr *> Args,
2717 unsigned formatIdx, bool inFunctionCall,
2718 Sema::VariadicCallType CallType,
2719 llvm::SmallBitVector &CheckedVarArgs)
2720 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2721 numDataArgs, beg, hasVAListArg, Args,
2722 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2727 bool HandleInvalidPrintfConversionSpecifier(
2728 const analyze_printf::PrintfSpecifier &FS,
2729 const char *startSpecifier,
2730 unsigned specifierLen);
2732 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2733 const char *startSpecifier,
2734 unsigned specifierLen);
2735 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2736 const char *StartSpecifier,
2737 unsigned SpecifierLen,
2740 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2741 const char *startSpecifier, unsigned specifierLen);
2742 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2743 const analyze_printf::OptionalAmount &Amt,
2745 const char *startSpecifier, unsigned specifierLen);
2746 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2747 const analyze_printf::OptionalFlag &flag,
2748 const char *startSpecifier, unsigned specifierLen);
2749 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2750 const analyze_printf::OptionalFlag &ignoredFlag,
2751 const analyze_printf::OptionalFlag &flag,
2752 const char *startSpecifier, unsigned specifierLen);
2753 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
2754 const Expr *E, const CharSourceRange &CSR);
2759 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2760 const analyze_printf::PrintfSpecifier &FS,
2761 const char *startSpecifier,
2762 unsigned specifierLen) {
2763 const analyze_printf::PrintfConversionSpecifier &CS =
2764 FS.getConversionSpecifier();
2766 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2767 getLocationOfByte(CS.getStart()),
2768 startSpecifier, specifierLen,
2769 CS.getStart(), CS.getLength());
2772 bool CheckPrintfHandler::HandleAmount(
2773 const analyze_format_string::OptionalAmount &Amt,
2774 unsigned k, const char *startSpecifier,
2775 unsigned specifierLen) {
2777 if (Amt.hasDataArgument()) {
2778 if (!HasVAListArg) {
2779 unsigned argIndex = Amt.getArgIndex();
2780 if (argIndex >= NumDataArgs) {
2781 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2783 getLocationOfByte(Amt.getStart()),
2784 /*IsStringLocation*/true,
2785 getSpecifierRange(startSpecifier, specifierLen));
2786 // Don't do any more checking. We will just emit
2791 // Type check the data argument. It should be an 'int'.
2792 // Although not in conformance with C99, we also allow the argument to be
2793 // an 'unsigned int' as that is a reasonably safe case. GCC also
2794 // doesn't emit a warning for that case.
2795 CoveredArgs.set(argIndex);
2796 const Expr *Arg = getDataArg(argIndex);
2800 QualType T = Arg->getType();
2802 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2803 assert(AT.isValid());
2805 if (!AT.matchesType(S.Context, T)) {
2806 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
2807 << k << AT.getRepresentativeTypeName(S.Context)
2808 << T << Arg->getSourceRange(),
2809 getLocationOfByte(Amt.getStart()),
2810 /*IsStringLocation*/true,
2811 getSpecifierRange(startSpecifier, specifierLen));
2812 // Don't do any more checking. We will just emit
2821 void CheckPrintfHandler::HandleInvalidAmount(
2822 const analyze_printf::PrintfSpecifier &FS,
2823 const analyze_printf::OptionalAmount &Amt,
2825 const char *startSpecifier,
2826 unsigned specifierLen) {
2827 const analyze_printf::PrintfConversionSpecifier &CS =
2828 FS.getConversionSpecifier();
2831 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2832 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2833 Amt.getConstantLength()))
2836 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2837 << type << CS.toString(),
2838 getLocationOfByte(Amt.getStart()),
2839 /*IsStringLocation*/true,
2840 getSpecifierRange(startSpecifier, specifierLen),
2844 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2845 const analyze_printf::OptionalFlag &flag,
2846 const char *startSpecifier,
2847 unsigned specifierLen) {
2848 // Warn about pointless flag with a fixit removal.
2849 const analyze_printf::PrintfConversionSpecifier &CS =
2850 FS.getConversionSpecifier();
2851 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2852 << flag.toString() << CS.toString(),
2853 getLocationOfByte(flag.getPosition()),
2854 /*IsStringLocation*/true,
2855 getSpecifierRange(startSpecifier, specifierLen),
2856 FixItHint::CreateRemoval(
2857 getSpecifierRange(flag.getPosition(), 1)));
2860 void CheckPrintfHandler::HandleIgnoredFlag(
2861 const analyze_printf::PrintfSpecifier &FS,
2862 const analyze_printf::OptionalFlag &ignoredFlag,
2863 const analyze_printf::OptionalFlag &flag,
2864 const char *startSpecifier,
2865 unsigned specifierLen) {
2866 // Warn about ignored flag with a fixit removal.
2867 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2868 << ignoredFlag.toString() << flag.toString(),
2869 getLocationOfByte(ignoredFlag.getPosition()),
2870 /*IsStringLocation*/true,
2871 getSpecifierRange(startSpecifier, specifierLen),
2872 FixItHint::CreateRemoval(
2873 getSpecifierRange(ignoredFlag.getPosition(), 1)));
2876 // Determines if the specified is a C++ class or struct containing
2877 // a member with the specified name and kind (e.g. a CXXMethodDecl named
2879 template<typename MemberKind>
2880 static llvm::SmallPtrSet<MemberKind*, 1>
2881 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2882 const RecordType *RT = Ty->getAs<RecordType>();
2883 llvm::SmallPtrSet<MemberKind*, 1> Results;
2887 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2891 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2892 Sema::LookupMemberName);
2894 // We just need to include all members of the right kind turned up by the
2895 // filter, at this point.
2896 if (S.LookupQualifiedName(R, RT->getDecl()))
2897 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2898 NamedDecl *decl = (*I)->getUnderlyingDecl();
2899 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2905 // Check if a (w)string was passed when a (w)char* was needed, and offer a
2906 // better diagnostic if so. AT is assumed to be valid.
2907 // Returns true when a c_str() conversion method is found.
2908 bool CheckPrintfHandler::checkForCStrMembers(
2909 const analyze_printf::ArgType &AT, const Expr *E,
2910 const CharSourceRange &CSR) {
2911 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2914 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2916 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2918 const CXXMethodDecl *Method = *MI;
2919 if (Method->getNumParams() == 0 &&
2920 AT.matchesType(S.Context, Method->getResultType())) {
2921 // FIXME: Suggest parens if the expression needs them.
2922 SourceLocation EndLoc =
2923 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2924 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2926 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2935 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2937 const char *startSpecifier,
2938 unsigned specifierLen) {
2940 using namespace analyze_format_string;
2941 using namespace analyze_printf;
2942 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2944 if (FS.consumesDataArgument()) {
2947 usesPositionalArgs = FS.usesPositionalArg();
2949 else if (usesPositionalArgs != FS.usesPositionalArg()) {
2950 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2951 startSpecifier, specifierLen);
2956 // First check if the field width, precision, and conversion specifier
2957 // have matching data arguments.
2958 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2959 startSpecifier, specifierLen)) {
2963 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2964 startSpecifier, specifierLen)) {
2968 if (!CS.consumesDataArgument()) {
2969 // FIXME: Technically specifying a precision or field width here
2970 // makes no sense. Worth issuing a warning at some point.
2974 // Consume the argument.
2975 unsigned argIndex = FS.getArgIndex();
2976 if (argIndex < NumDataArgs) {
2977 // The check to see if the argIndex is valid will come later.
2978 // We set the bit here because we may exit early from this
2979 // function if we encounter some other error.
2980 CoveredArgs.set(argIndex);
2983 // FreeBSD kernel extensions.
2984 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
2985 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
2986 // We need at least two arguments.
2987 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
2990 // Claim the second argument.
2991 CoveredArgs.set(argIndex + 1);
2993 // Type check the first argument (int for %b, pointer for %D)
2994 const Expr *Ex = getDataArg(argIndex);
2995 const analyze_printf::ArgType &AT =
2996 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
2997 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
2998 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
2999 S.Diag(getLocationOfByte(CS.getStart()),
3000 diag::warn_printf_conversion_argument_type_mismatch)
3001 << AT.getRepresentativeType(S.Context) << Ex->getType()
3002 << getSpecifierRange(startSpecifier, specifierLen)
3003 << Ex->getSourceRange();
3005 // Type check the second argument (char * for both %b and %D)
3006 Ex = getDataArg(argIndex + 1);
3007 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3008 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3009 S.Diag(getLocationOfByte(CS.getStart()),
3010 diag::warn_printf_conversion_argument_type_mismatch)
3011 << AT2.getRepresentativeType(S.Context) << Ex->getType()
3012 << getSpecifierRange(startSpecifier, specifierLen)
3013 << Ex->getSourceRange();
3017 // END OF FREEBSD EXTENSIONS
3019 // Check for using an Objective-C specific conversion specifier
3020 // in a non-ObjC literal.
3021 if (!ObjCContext && CS.isObjCArg()) {
3022 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3026 // Check for invalid use of field width
3027 if (!FS.hasValidFieldWidth()) {
3028 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
3029 startSpecifier, specifierLen);
3032 // Check for invalid use of precision
3033 if (!FS.hasValidPrecision()) {
3034 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3035 startSpecifier, specifierLen);
3038 // Check each flag does not conflict with any other component.
3039 if (!FS.hasValidThousandsGroupingPrefix())
3040 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3041 if (!FS.hasValidLeadingZeros())
3042 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3043 if (!FS.hasValidPlusPrefix())
3044 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3045 if (!FS.hasValidSpacePrefix())
3046 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3047 if (!FS.hasValidAlternativeForm())
3048 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3049 if (!FS.hasValidLeftJustified())
3050 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3052 // Check that flags are not ignored by another flag
3053 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3054 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3055 startSpecifier, specifierLen);
3056 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3057 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3058 startSpecifier, specifierLen);
3060 // Check the length modifier is valid with the given conversion specifier.
3061 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3062 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3063 diag::warn_format_nonsensical_length);
3064 else if (!FS.hasStandardLengthModifier())
3065 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3066 else if (!FS.hasStandardLengthConversionCombination())
3067 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3068 diag::warn_format_non_standard_conversion_spec);
3070 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3071 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3073 // The remaining checks depend on the data arguments.
3077 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3080 const Expr *Arg = getDataArg(argIndex);
3084 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3087 static bool requiresParensToAddCast(const Expr *E) {
3088 // FIXME: We should have a general way to reason about operator
3089 // precedence and whether parens are actually needed here.
3090 // Take care of a few common cases where they aren't.
3091 const Expr *Inside = E->IgnoreImpCasts();
3092 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3093 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3095 switch (Inside->getStmtClass()) {
3096 case Stmt::ArraySubscriptExprClass:
3097 case Stmt::CallExprClass:
3098 case Stmt::CharacterLiteralClass:
3099 case Stmt::CXXBoolLiteralExprClass:
3100 case Stmt::DeclRefExprClass:
3101 case Stmt::FloatingLiteralClass:
3102 case Stmt::IntegerLiteralClass:
3103 case Stmt::MemberExprClass:
3104 case Stmt::ObjCArrayLiteralClass:
3105 case Stmt::ObjCBoolLiteralExprClass:
3106 case Stmt::ObjCBoxedExprClass:
3107 case Stmt::ObjCDictionaryLiteralClass:
3108 case Stmt::ObjCEncodeExprClass:
3109 case Stmt::ObjCIvarRefExprClass:
3110 case Stmt::ObjCMessageExprClass:
3111 case Stmt::ObjCPropertyRefExprClass:
3112 case Stmt::ObjCStringLiteralClass:
3113 case Stmt::ObjCSubscriptRefExprClass:
3114 case Stmt::ParenExprClass:
3115 case Stmt::StringLiteralClass:
3116 case Stmt::UnaryOperatorClass:
3124 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3125 const char *StartSpecifier,
3126 unsigned SpecifierLen,
3128 using namespace analyze_format_string;
3129 using namespace analyze_printf;
3130 // Now type check the data expression that matches the
3131 // format specifier.
3132 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3137 QualType ExprTy = E->getType();
3138 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3139 ExprTy = TET->getUnderlyingExpr()->getType();
3142 if (AT.matchesType(S.Context, ExprTy))
3145 // Look through argument promotions for our error message's reported type.
3146 // This includes the integral and floating promotions, but excludes array
3147 // and function pointer decay; seeing that an argument intended to be a
3148 // string has type 'char [6]' is probably more confusing than 'char *'.
3149 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3150 if (ICE->getCastKind() == CK_IntegralCast ||
3151 ICE->getCastKind() == CK_FloatingCast) {
3152 E = ICE->getSubExpr();
3153 ExprTy = E->getType();
3155 // Check if we didn't match because of an implicit cast from a 'char'
3156 // or 'short' to an 'int'. This is done because printf is a varargs
3158 if (ICE->getType() == S.Context.IntTy ||
3159 ICE->getType() == S.Context.UnsignedIntTy) {
3160 // All further checking is done on the subexpression.
3161 if (AT.matchesType(S.Context, ExprTy))
3165 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3166 // Special case for 'a', which has type 'int' in C.
3167 // Note, however, that we do /not/ want to treat multibyte constants like
3168 // 'MooV' as characters! This form is deprecated but still exists.
3169 if (ExprTy == S.Context.IntTy)
3170 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3171 ExprTy = S.Context.CharTy;
3174 // %C in an Objective-C context prints a unichar, not a wchar_t.
3175 // If the argument is an integer of some kind, believe the %C and suggest
3176 // a cast instead of changing the conversion specifier.
3177 QualType IntendedTy = ExprTy;
3179 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3180 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3181 !ExprTy->isCharType()) {
3182 // 'unichar' is defined as a typedef of unsigned short, but we should
3183 // prefer using the typedef if it is visible.
3184 IntendedTy = S.Context.UnsignedShortTy;
3186 // While we are here, check if the value is an IntegerLiteral that happens
3187 // to be within the valid range.
3188 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3189 const llvm::APInt &V = IL->getValue();
3190 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3194 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3195 Sema::LookupOrdinaryName);
3196 if (S.LookupName(Result, S.getCurScope())) {
3197 NamedDecl *ND = Result.getFoundDecl();
3198 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3199 if (TD->getUnderlyingType() == IntendedTy)
3200 IntendedTy = S.Context.getTypedefType(TD);
3205 // Special-case some of Darwin's platform-independence types by suggesting
3206 // casts to primitive types that are known to be large enough.
3207 bool ShouldNotPrintDirectly = false;
3208 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3209 // Use a 'while' to peel off layers of typedefs.
3210 QualType TyTy = IntendedTy;
3211 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3212 StringRef Name = UserTy->getDecl()->getName();
3213 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3214 .Case("NSInteger", S.Context.LongTy)
3215 .Case("NSUInteger", S.Context.UnsignedLongTy)
3216 .Case("SInt32", S.Context.IntTy)
3217 .Case("UInt32", S.Context.UnsignedIntTy)
3218 .Default(QualType());
3220 if (!CastTy.isNull()) {
3221 ShouldNotPrintDirectly = true;
3222 IntendedTy = CastTy;
3225 TyTy = UserTy->desugar();
3229 // We may be able to offer a FixItHint if it is a supported type.
3230 PrintfSpecifier fixedFS = FS;
3231 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3232 S.Context, ObjCContext);
3235 // Get the fix string from the fixed format specifier
3236 SmallString<16> buf;
3237 llvm::raw_svector_ostream os(buf);
3238 fixedFS.toString(os);
3240 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3242 if (IntendedTy == ExprTy) {
3243 // In this case, the specifier is wrong and should be changed to match
3245 EmitFormatDiagnostic(
3246 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3247 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3248 << E->getSourceRange(),
3250 /*IsStringLocation*/false,
3252 FixItHint::CreateReplacement(SpecRange, os.str()));
3255 // The canonical type for formatting this value is different from the
3256 // actual type of the expression. (This occurs, for example, with Darwin's
3257 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3258 // should be printed as 'long' for 64-bit compatibility.)
3259 // Rather than emitting a normal format/argument mismatch, we want to
3260 // add a cast to the recommended type (and correct the format string
3262 SmallString<16> CastBuf;
3263 llvm::raw_svector_ostream CastFix(CastBuf);
3265 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3268 SmallVector<FixItHint,4> Hints;
3269 if (!AT.matchesType(S.Context, IntendedTy))
3270 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3272 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3273 // If there's already a cast present, just replace it.
3274 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3275 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3277 } else if (!requiresParensToAddCast(E)) {
3278 // If the expression has high enough precedence,
3279 // just write the C-style cast.
3280 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3283 // Otherwise, add parens around the expression as well as the cast.
3285 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3288 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3289 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3292 if (ShouldNotPrintDirectly) {
3293 // The expression has a type that should not be printed directly.
3294 // We extract the name from the typedef because we don't want to show
3295 // the underlying type in the diagnostic.
3296 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
3298 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3299 << Name << IntendedTy
3300 << E->getSourceRange(),
3301 E->getLocStart(), /*IsStringLocation=*/false,
3304 // In this case, the expression could be printed using a different
3305 // specifier, but we've decided that the specifier is probably correct
3306 // and we should cast instead. Just use the normal warning message.
3307 EmitFormatDiagnostic(
3308 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3309 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3310 << E->getSourceRange(),
3311 E->getLocStart(), /*IsStringLocation*/false,
3316 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3318 // Since the warning for passing non-POD types to variadic functions
3319 // was deferred until now, we emit a warning for non-POD
3321 switch (S.isValidVarArgType(ExprTy)) {
3322 case Sema::VAK_Valid:
3323 case Sema::VAK_ValidInCXX11:
3324 EmitFormatDiagnostic(
3325 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3326 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3328 << E->getSourceRange(),
3329 E->getLocStart(), /*IsStringLocation*/false, CSR);
3332 case Sema::VAK_Undefined:
3333 EmitFormatDiagnostic(
3334 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
3335 << S.getLangOpts().CPlusPlus11
3338 << AT.getRepresentativeTypeName(S.Context)
3340 << E->getSourceRange(),
3341 E->getLocStart(), /*IsStringLocation*/false, CSR);
3342 checkForCStrMembers(AT, E, CSR);
3345 case Sema::VAK_Invalid:
3346 if (ExprTy->isObjCObjectType())
3347 EmitFormatDiagnostic(
3348 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3349 << S.getLangOpts().CPlusPlus11
3352 << AT.getRepresentativeTypeName(S.Context)
3354 << E->getSourceRange(),
3355 E->getLocStart(), /*IsStringLocation*/false, CSR);
3357 // FIXME: If this is an initializer list, suggest removing the braces
3358 // or inserting a cast to the target type.
3359 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3360 << isa<InitListExpr>(E) << ExprTy << CallType
3361 << AT.getRepresentativeTypeName(S.Context)
3362 << E->getSourceRange();
3366 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3367 "format string specifier index out of range");
3368 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
3374 //===--- CHECK: Scanf format string checking ------------------------------===//
3377 class CheckScanfHandler : public CheckFormatHandler {
3379 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3380 const Expr *origFormatExpr, unsigned firstDataArg,
3381 unsigned numDataArgs, const char *beg, bool hasVAListArg,
3382 ArrayRef<const Expr *> Args,
3383 unsigned formatIdx, bool inFunctionCall,
3384 Sema::VariadicCallType CallType,
3385 llvm::SmallBitVector &CheckedVarArgs)
3386 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3387 numDataArgs, beg, hasVAListArg,
3388 Args, formatIdx, inFunctionCall, CallType,
3392 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3393 const char *startSpecifier,
3394 unsigned specifierLen);
3396 bool HandleInvalidScanfConversionSpecifier(
3397 const analyze_scanf::ScanfSpecifier &FS,
3398 const char *startSpecifier,
3399 unsigned specifierLen);
3401 void HandleIncompleteScanList(const char *start, const char *end);
3405 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3407 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3408 getLocationOfByte(end), /*IsStringLocation*/true,
3409 getSpecifierRange(start, end - start));
3412 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3413 const analyze_scanf::ScanfSpecifier &FS,
3414 const char *startSpecifier,
3415 unsigned specifierLen) {
3417 const analyze_scanf::ScanfConversionSpecifier &CS =
3418 FS.getConversionSpecifier();
3420 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3421 getLocationOfByte(CS.getStart()),
3422 startSpecifier, specifierLen,
3423 CS.getStart(), CS.getLength());
3426 bool CheckScanfHandler::HandleScanfSpecifier(
3427 const analyze_scanf::ScanfSpecifier &FS,
3428 const char *startSpecifier,
3429 unsigned specifierLen) {
3431 using namespace analyze_scanf;
3432 using namespace analyze_format_string;
3434 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3436 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3437 // be used to decide if we are using positional arguments consistently.
3438 if (FS.consumesDataArgument()) {
3441 usesPositionalArgs = FS.usesPositionalArg();
3443 else if (usesPositionalArgs != FS.usesPositionalArg()) {
3444 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3445 startSpecifier, specifierLen);
3450 // Check if the field with is non-zero.
3451 const OptionalAmount &Amt = FS.getFieldWidth();
3452 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3453 if (Amt.getConstantAmount() == 0) {
3454 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3455 Amt.getConstantLength());
3456 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3457 getLocationOfByte(Amt.getStart()),
3458 /*IsStringLocation*/true, R,
3459 FixItHint::CreateRemoval(R));
3463 if (!FS.consumesDataArgument()) {
3464 // FIXME: Technically specifying a precision or field width here
3465 // makes no sense. Worth issuing a warning at some point.
3469 // Consume the argument.
3470 unsigned argIndex = FS.getArgIndex();
3471 if (argIndex < NumDataArgs) {
3472 // The check to see if the argIndex is valid will come later.
3473 // We set the bit here because we may exit early from this
3474 // function if we encounter some other error.
3475 CoveredArgs.set(argIndex);
3478 // Check the length modifier is valid with the given conversion specifier.
3479 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3480 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3481 diag::warn_format_nonsensical_length);
3482 else if (!FS.hasStandardLengthModifier())
3483 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3484 else if (!FS.hasStandardLengthConversionCombination())
3485 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3486 diag::warn_format_non_standard_conversion_spec);
3488 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3489 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3491 // The remaining checks depend on the data arguments.
3495 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3498 // Check that the argument type matches the format specifier.
3499 const Expr *Ex = getDataArg(argIndex);
3503 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3504 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3505 ScanfSpecifier fixedFS = FS;
3506 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
3510 // Get the fix string from the fixed format specifier.
3511 SmallString<128> buf;
3512 llvm::raw_svector_ostream os(buf);
3513 fixedFS.toString(os);
3515 EmitFormatDiagnostic(
3516 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3517 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3518 << Ex->getSourceRange(),
3520 /*IsStringLocation*/false,
3521 getSpecifierRange(startSpecifier, specifierLen),
3522 FixItHint::CreateReplacement(
3523 getSpecifierRange(startSpecifier, specifierLen),
3526 EmitFormatDiagnostic(
3527 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3528 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3529 << Ex->getSourceRange(),
3531 /*IsStringLocation*/false,
3532 getSpecifierRange(startSpecifier, specifierLen));
3539 void Sema::CheckFormatString(const StringLiteral *FExpr,
3540 const Expr *OrigFormatExpr,
3541 ArrayRef<const Expr *> Args,
3542 bool HasVAListArg, unsigned format_idx,
3543 unsigned firstDataArg, FormatStringType Type,
3544 bool inFunctionCall, VariadicCallType CallType,
3545 llvm::SmallBitVector &CheckedVarArgs) {
3547 // CHECK: is the format string a wide literal?
3548 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3549 CheckFormatHandler::EmitFormatDiagnostic(
3550 *this, inFunctionCall, Args[format_idx],
3551 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3552 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3556 // Str - The format string. NOTE: this is NOT null-terminated!
3557 StringRef StrRef = FExpr->getString();
3558 const char *Str = StrRef.data();
3559 unsigned StrLen = StrRef.size();
3560 const unsigned numDataArgs = Args.size() - firstDataArg;
3562 // CHECK: empty format string?
3563 if (StrLen == 0 && numDataArgs > 0) {
3564 CheckFormatHandler::EmitFormatDiagnostic(
3565 *this, inFunctionCall, Args[format_idx],
3566 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3567 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3571 if (Type == FST_Printf || Type == FST_NSString) {
3572 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
3573 numDataArgs, (Type == FST_NSString),
3574 Str, HasVAListArg, Args, format_idx,
3575 inFunctionCall, CallType, CheckedVarArgs);
3577 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
3579 Context.getTargetInfo()))
3581 } else if (Type == FST_Scanf) {
3582 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
3583 Str, HasVAListArg, Args, format_idx,
3584 inFunctionCall, CallType, CheckedVarArgs);
3586 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
3588 Context.getTargetInfo()))
3590 } // TODO: handle other formats
3593 //===--- CHECK: Standard memory functions ---------------------------------===//
3595 /// \brief Determine whether the given type is a dynamic class type (e.g.,
3596 /// whether it has a vtable).
3597 static bool isDynamicClassType(QualType T) {
3598 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3599 if (CXXRecordDecl *Definition = Record->getDefinition())
3600 if (Definition->isDynamicClass())
3606 /// \brief If E is a sizeof expression, returns its argument expression,
3607 /// otherwise returns NULL.
3608 static const Expr *getSizeOfExprArg(const Expr* E) {
3609 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3610 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3611 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3612 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
3617 /// \brief If E is a sizeof expression, returns its argument type.
3618 static QualType getSizeOfArgType(const Expr* E) {
3619 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3620 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3621 if (SizeOf->getKind() == clang::UETT_SizeOf)
3622 return SizeOf->getTypeOfArgument();
3627 /// \brief Check for dangerous or invalid arguments to memset().
3629 /// This issues warnings on known problematic, dangerous or unspecified
3630 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3633 /// \param Call The call expression to diagnose.
3634 void Sema::CheckMemaccessArguments(const CallExpr *Call,
3636 IdentifierInfo *FnName) {
3639 // It is possible to have a non-standard definition of memset. Validate
3640 // we have enough arguments, and if not, abort further checking.
3641 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
3642 if (Call->getNumArgs() < ExpectedNumArgs)
3645 unsigned LastArg = (BId == Builtin::BImemset ||
3646 BId == Builtin::BIstrndup ? 1 : 2);
3647 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
3648 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
3650 // We have special checking when the length is a sizeof expression.
3651 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3652 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3653 llvm::FoldingSetNodeID SizeOfArgID;
3655 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3656 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
3657 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
3659 QualType DestTy = Dest->getType();
3660 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3661 QualType PointeeTy = DestPtrTy->getPointeeType();
3663 // Never warn about void type pointers. This can be used to suppress
3665 if (PointeeTy->isVoidType())
3668 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3669 // actually comparing the expressions for equality. Because computing the
3670 // expression IDs can be expensive, we only do this if the diagnostic is
3673 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3674 SizeOfArg->getExprLoc())) {
3675 // We only compute IDs for expressions if the warning is enabled, and
3676 // cache the sizeof arg's ID.
3677 if (SizeOfArgID == llvm::FoldingSetNodeID())
3678 SizeOfArg->Profile(SizeOfArgID, Context, true);
3679 llvm::FoldingSetNodeID DestID;
3680 Dest->Profile(DestID, Context, true);
3681 if (DestID == SizeOfArgID) {
3682 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3683 // over sizeof(src) as well.
3684 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
3685 StringRef ReadableName = FnName->getName();
3687 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
3688 if (UnaryOp->getOpcode() == UO_AddrOf)
3689 ActionIdx = 1; // If its an address-of operator, just remove it.
3690 if (!PointeeTy->isIncompleteType() &&
3691 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
3692 ActionIdx = 2; // If the pointee's size is sizeof(char),
3693 // suggest an explicit length.
3695 // If the function is defined as a builtin macro, do not show macro
3697 SourceLocation SL = SizeOfArg->getExprLoc();
3698 SourceRange DSR = Dest->getSourceRange();
3699 SourceRange SSR = SizeOfArg->getSourceRange();
3700 SourceManager &SM = PP.getSourceManager();
3702 if (SM.isMacroArgExpansion(SL)) {
3703 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3704 SL = SM.getSpellingLoc(SL);
3705 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3706 SM.getSpellingLoc(DSR.getEnd()));
3707 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3708 SM.getSpellingLoc(SSR.getEnd()));
3711 DiagRuntimeBehavior(SL, SizeOfArg,
3712 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
3718 DiagRuntimeBehavior(SL, SizeOfArg,
3719 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3727 // Also check for cases where the sizeof argument is the exact same
3728 // type as the memory argument, and where it points to a user-defined
3730 if (SizeOfArgTy != QualType()) {
3731 if (PointeeTy->isRecordType() &&
3732 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3733 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3734 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3735 << FnName << SizeOfArgTy << ArgIdx
3736 << PointeeTy << Dest->getSourceRange()
3737 << LenExpr->getSourceRange());
3742 // Always complain about dynamic classes.
3743 if (isDynamicClassType(PointeeTy)) {
3745 unsigned OperationType = 0;
3746 // "overwritten" if we're warning about the destination for any call
3747 // but memcmp; otherwise a verb appropriate to the call.
3748 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3749 if (BId == Builtin::BImemcpy)
3751 else if(BId == Builtin::BImemmove)
3753 else if (BId == Builtin::BImemcmp)
3757 DiagRuntimeBehavior(
3758 Dest->getExprLoc(), Dest,
3759 PDiag(diag::warn_dyn_class_memaccess)
3760 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
3761 << FnName << PointeeTy
3763 << Call->getCallee()->getSourceRange());
3764 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3765 BId != Builtin::BImemset)
3766 DiagRuntimeBehavior(
3767 Dest->getExprLoc(), Dest,
3768 PDiag(diag::warn_arc_object_memaccess)
3769 << ArgIdx << FnName << PointeeTy
3770 << Call->getCallee()->getSourceRange());
3774 DiagRuntimeBehavior(
3775 Dest->getExprLoc(), Dest,
3776 PDiag(diag::note_bad_memaccess_silence)
3777 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3783 // A little helper routine: ignore addition and subtraction of integer literals.
3784 // This intentionally does not ignore all integer constant expressions because
3785 // we don't want to remove sizeof().
3786 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3787 Ex = Ex->IgnoreParenCasts();
3790 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3791 if (!BO || !BO->isAdditiveOp())
3794 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3795 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3797 if (isa<IntegerLiteral>(RHS))
3799 else if (isa<IntegerLiteral>(LHS))
3808 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3809 ASTContext &Context) {
3810 // Only handle constant-sized or VLAs, but not flexible members.
3811 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3812 // Only issue the FIXIT for arrays of size > 1.
3813 if (CAT->getSize().getSExtValue() <= 1)
3815 } else if (!Ty->isVariableArrayType()) {
3821 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3822 // be the size of the source, instead of the destination.
3823 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3824 IdentifierInfo *FnName) {
3826 // Don't crash if the user has the wrong number of arguments
3827 if (Call->getNumArgs() != 3)
3830 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3831 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3832 const Expr *CompareWithSrc = NULL;
3834 // Look for 'strlcpy(dst, x, sizeof(x))'
3835 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3836 CompareWithSrc = Ex;
3838 // Look for 'strlcpy(dst, x, strlen(x))'
3839 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
3840 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
3841 && SizeCall->getNumArgs() == 1)
3842 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3846 if (!CompareWithSrc)
3849 // Determine if the argument to sizeof/strlen is equal to the source
3850 // argument. In principle there's all kinds of things you could do
3851 // here, for instance creating an == expression and evaluating it with
3852 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3853 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3857 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3858 if (!CompareWithSrcDRE ||
3859 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3862 const Expr *OriginalSizeArg = Call->getArg(2);
3863 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3864 << OriginalSizeArg->getSourceRange() << FnName;
3866 // Output a FIXIT hint if the destination is an array (rather than a
3867 // pointer to an array). This could be enhanced to handle some
3868 // pointers if we know the actual size, like if DstArg is 'array+2'
3869 // we could say 'sizeof(array)-2'.
3870 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
3871 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
3874 SmallString<128> sizeString;
3875 llvm::raw_svector_ostream OS(sizeString);
3877 DstArg->printPretty(OS, 0, getPrintingPolicy());
3880 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3881 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3885 /// Check if two expressions refer to the same declaration.
3886 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3887 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3888 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3889 return D1->getDecl() == D2->getDecl();
3893 static const Expr *getStrlenExprArg(const Expr *E) {
3894 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3895 const FunctionDecl *FD = CE->getDirectCallee();
3896 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3898 return CE->getArg(0)->IgnoreParenCasts();
3903 // Warn on anti-patterns as the 'size' argument to strncat.
3904 // The correct size argument should look like following:
3905 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3906 void Sema::CheckStrncatArguments(const CallExpr *CE,
3907 IdentifierInfo *FnName) {
3908 // Don't crash if the user has the wrong number of arguments.
3909 if (CE->getNumArgs() < 3)
3911 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3912 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3913 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3915 // Identify common expressions, which are wrongly used as the size argument
3916 // to strncat and may lead to buffer overflows.
3917 unsigned PatternType = 0;
3918 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3920 if (referToTheSameDecl(SizeOfArg, DstArg))
3923 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3925 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3926 if (BE->getOpcode() == BO_Sub) {
3927 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3928 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3929 // - sizeof(dst) - strlen(dst)
3930 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3931 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3933 // - sizeof(src) - (anything)
3934 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3939 if (PatternType == 0)
3942 // Generate the diagnostic.
3943 SourceLocation SL = LenArg->getLocStart();
3944 SourceRange SR = LenArg->getSourceRange();
3945 SourceManager &SM = PP.getSourceManager();
3947 // If the function is defined as a builtin macro, do not show macro expansion.
3948 if (SM.isMacroArgExpansion(SL)) {
3949 SL = SM.getSpellingLoc(SL);
3950 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3951 SM.getSpellingLoc(SR.getEnd()));
3954 // Check if the destination is an array (rather than a pointer to an array).
3955 QualType DstTy = DstArg->getType();
3956 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3958 if (!isKnownSizeArray) {
3959 if (PatternType == 1)
3960 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3962 Diag(SL, diag::warn_strncat_src_size) << SR;
3966 if (PatternType == 1)
3967 Diag(SL, diag::warn_strncat_large_size) << SR;
3969 Diag(SL, diag::warn_strncat_src_size) << SR;
3971 SmallString<128> sizeString;
3972 llvm::raw_svector_ostream OS(sizeString);
3974 DstArg->printPretty(OS, 0, getPrintingPolicy());
3977 DstArg->printPretty(OS, 0, getPrintingPolicy());
3980 Diag(SL, diag::note_strncat_wrong_size)
3981 << FixItHint::CreateReplacement(SR, OS.str());
3984 //===--- CHECK: Return Address of Stack Variable --------------------------===//
3986 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3988 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3991 /// CheckReturnStackAddr - Check if a return statement returns the address
3992 /// of a stack variable.
3994 Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3995 SourceLocation ReturnLoc) {
3998 SmallVector<DeclRefExpr *, 8> refVars;
4000 // Perform checking for returned stack addresses, local blocks,
4001 // label addresses or references to temporaries.
4002 if (lhsType->isPointerType() ||
4003 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
4004 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
4005 } else if (lhsType->isReferenceType()) {
4006 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
4010 return; // Nothing suspicious was found.
4012 SourceLocation diagLoc;
4013 SourceRange diagRange;
4014 if (refVars.empty()) {
4015 diagLoc = stackE->getLocStart();
4016 diagRange = stackE->getSourceRange();
4018 // We followed through a reference variable. 'stackE' contains the
4019 // problematic expression but we will warn at the return statement pointing
4020 // at the reference variable. We will later display the "trail" of
4021 // reference variables using notes.
4022 diagLoc = refVars[0]->getLocStart();
4023 diagRange = refVars[0]->getSourceRange();
4026 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
4027 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
4028 : diag::warn_ret_stack_addr)
4029 << DR->getDecl()->getDeclName() << diagRange;
4030 } else if (isa<BlockExpr>(stackE)) { // local block.
4031 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
4032 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
4033 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
4034 } else { // local temporary.
4035 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4036 : diag::warn_ret_local_temp_addr)
4040 // Display the "trail" of reference variables that we followed until we
4041 // found the problematic expression using notes.
4042 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4043 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4044 // If this var binds to another reference var, show the range of the next
4045 // var, otherwise the var binds to the problematic expression, in which case
4046 // show the range of the expression.
4047 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4048 : stackE->getSourceRange();
4049 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4050 << VD->getDeclName() << range;
4054 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4055 /// check if the expression in a return statement evaluates to an address
4056 /// to a location on the stack, a local block, an address of a label, or a
4057 /// reference to local temporary. The recursion is used to traverse the
4058 /// AST of the return expression, with recursion backtracking when we
4059 /// encounter a subexpression that (1) clearly does not lead to one of the
4060 /// above problematic expressions (2) is something we cannot determine leads to
4061 /// a problematic expression based on such local checking.
4063 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
4064 /// the expression that they point to. Such variables are added to the
4065 /// 'refVars' vector so that we know what the reference variable "trail" was.
4067 /// EvalAddr processes expressions that are pointers that are used as
4068 /// references (and not L-values). EvalVal handles all other values.
4069 /// At the base case of the recursion is a check for the above problematic
4072 /// This implementation handles:
4074 /// * pointer-to-pointer casts
4075 /// * implicit conversions from array references to pointers
4076 /// * taking the address of fields
4077 /// * arbitrary interplay between "&" and "*" operators
4078 /// * pointer arithmetic from an address of a stack variable
4079 /// * taking the address of an array element where the array is on the stack
4080 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4082 if (E->isTypeDependent())
4085 // We should only be called for evaluating pointer expressions.
4086 assert((E->getType()->isAnyPointerType() ||
4087 E->getType()->isBlockPointerType() ||
4088 E->getType()->isObjCQualifiedIdType()) &&
4089 "EvalAddr only works on pointers");
4091 E = E->IgnoreParens();
4093 // Our "symbolic interpreter" is just a dispatch off the currently
4094 // viewed AST node. We then recursively traverse the AST by calling
4095 // EvalAddr and EvalVal appropriately.
4096 switch (E->getStmtClass()) {
4097 case Stmt::DeclRefExprClass: {
4098 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4100 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4101 // If this is a reference variable, follow through to the expression that
4103 if (V->hasLocalStorage() &&
4104 V->getType()->isReferenceType() && V->hasInit()) {
4105 // Add the reference variable to the "trail".
4106 refVars.push_back(DR);
4107 return EvalAddr(V->getInit(), refVars, ParentDecl);
4113 case Stmt::UnaryOperatorClass: {
4114 // The only unary operator that make sense to handle here
4115 // is AddrOf. All others don't make sense as pointers.
4116 UnaryOperator *U = cast<UnaryOperator>(E);
4118 if (U->getOpcode() == UO_AddrOf)
4119 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
4124 case Stmt::BinaryOperatorClass: {
4125 // Handle pointer arithmetic. All other binary operators are not valid
4127 BinaryOperator *B = cast<BinaryOperator>(E);
4128 BinaryOperatorKind op = B->getOpcode();
4130 if (op != BO_Add && op != BO_Sub)
4133 Expr *Base = B->getLHS();
4135 // Determine which argument is the real pointer base. It could be
4136 // the RHS argument instead of the LHS.
4137 if (!Base->getType()->isPointerType()) Base = B->getRHS();
4139 assert (Base->getType()->isPointerType());
4140 return EvalAddr(Base, refVars, ParentDecl);
4143 // For conditional operators we need to see if either the LHS or RHS are
4144 // valid DeclRefExpr*s. If one of them is valid, we return it.
4145 case Stmt::ConditionalOperatorClass: {
4146 ConditionalOperator *C = cast<ConditionalOperator>(E);
4148 // Handle the GNU extension for missing LHS.
4149 if (Expr *lhsExpr = C->getLHS()) {
4150 // In C++, we can have a throw-expression, which has 'void' type.
4151 if (!lhsExpr->getType()->isVoidType())
4152 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
4156 // In C++, we can have a throw-expression, which has 'void' type.
4157 if (C->getRHS()->getType()->isVoidType())
4160 return EvalAddr(C->getRHS(), refVars, ParentDecl);
4163 case Stmt::BlockExprClass:
4164 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
4165 return E; // local block.
4168 case Stmt::AddrLabelExprClass:
4169 return E; // address of label.
4171 case Stmt::ExprWithCleanupsClass:
4172 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4175 // For casts, we need to handle conversions from arrays to
4176 // pointer values, and pointer-to-pointer conversions.
4177 case Stmt::ImplicitCastExprClass:
4178 case Stmt::CStyleCastExprClass:
4179 case Stmt::CXXFunctionalCastExprClass:
4180 case Stmt::ObjCBridgedCastExprClass:
4181 case Stmt::CXXStaticCastExprClass:
4182 case Stmt::CXXDynamicCastExprClass:
4183 case Stmt::CXXConstCastExprClass:
4184 case Stmt::CXXReinterpretCastExprClass: {
4185 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4186 switch (cast<CastExpr>(E)->getCastKind()) {
4188 case CK_LValueToRValue:
4190 case CK_BaseToDerived:
4191 case CK_DerivedToBase:
4192 case CK_UncheckedDerivedToBase:
4194 case CK_CPointerToObjCPointerCast:
4195 case CK_BlockPointerToObjCPointerCast:
4196 case CK_AnyPointerToBlockPointerCast:
4197 return EvalAddr(SubExpr, refVars, ParentDecl);
4199 case CK_ArrayToPointerDecay:
4200 return EvalVal(SubExpr, refVars, ParentDecl);
4207 case Stmt::MaterializeTemporaryExprClass:
4208 if (Expr *Result = EvalAddr(
4209 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4210 refVars, ParentDecl))
4215 // Everything else: we simply don't reason about them.
4222 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
4223 /// See the comments for EvalAddr for more details.
4224 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4227 // We should only be called for evaluating non-pointer expressions, or
4228 // expressions with a pointer type that are not used as references but instead
4229 // are l-values (e.g., DeclRefExpr with a pointer type).
4231 // Our "symbolic interpreter" is just a dispatch off the currently
4232 // viewed AST node. We then recursively traverse the AST by calling
4233 // EvalAddr and EvalVal appropriately.
4235 E = E->IgnoreParens();
4236 switch (E->getStmtClass()) {
4237 case Stmt::ImplicitCastExprClass: {
4238 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
4239 if (IE->getValueKind() == VK_LValue) {
4240 E = IE->getSubExpr();
4246 case Stmt::ExprWithCleanupsClass:
4247 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
4249 case Stmt::DeclRefExprClass: {
4250 // When we hit a DeclRefExpr we are looking at code that refers to a
4251 // variable's name. If it's not a reference variable we check if it has
4252 // local storage within the function, and if so, return the expression.
4253 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4255 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4256 // Check if it refers to itself, e.g. "int& i = i;".
4257 if (V == ParentDecl)
4260 if (V->hasLocalStorage()) {
4261 if (!V->getType()->isReferenceType())
4264 // Reference variable, follow through to the expression that
4267 // Add the reference variable to the "trail".
4268 refVars.push_back(DR);
4269 return EvalVal(V->getInit(), refVars, V);
4277 case Stmt::UnaryOperatorClass: {
4278 // The only unary operator that make sense to handle here
4279 // is Deref. All others don't resolve to a "name." This includes
4280 // handling all sorts of rvalues passed to a unary operator.
4281 UnaryOperator *U = cast<UnaryOperator>(E);
4283 if (U->getOpcode() == UO_Deref)
4284 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
4289 case Stmt::ArraySubscriptExprClass: {
4290 // Array subscripts are potential references to data on the stack. We
4291 // retrieve the DeclRefExpr* for the array variable if it indeed
4292 // has local storage.
4293 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
4296 case Stmt::ConditionalOperatorClass: {
4297 // For conditional operators we need to see if either the LHS or RHS are
4298 // non-NULL Expr's. If one is non-NULL, we return it.
4299 ConditionalOperator *C = cast<ConditionalOperator>(E);
4301 // Handle the GNU extension for missing LHS.
4302 if (Expr *lhsExpr = C->getLHS())
4303 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
4306 return EvalVal(C->getRHS(), refVars, ParentDecl);
4309 // Accesses to members are potential references to data on the stack.
4310 case Stmt::MemberExprClass: {
4311 MemberExpr *M = cast<MemberExpr>(E);
4313 // Check for indirect access. We only want direct field accesses.
4317 // Check whether the member type is itself a reference, in which case
4318 // we're not going to refer to the member, but to what the member refers to.
4319 if (M->getMemberDecl()->getType()->isReferenceType())
4322 return EvalVal(M->getBase(), refVars, ParentDecl);
4325 case Stmt::MaterializeTemporaryExprClass:
4326 if (Expr *Result = EvalVal(
4327 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4328 refVars, ParentDecl))
4334 // Check that we don't return or take the address of a reference to a
4335 // temporary. This is only useful in C++.
4336 if (!E->isTypeDependent() && E->isRValue())
4339 // Everything else: we simply don't reason about them.
4345 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4347 /// Check for comparisons of floating point operands using != and ==.
4348 /// Issue a warning if these are no self-comparisons, as they are not likely
4349 /// to do what the programmer intended.
4350 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
4351 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4352 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
4354 // Special case: check for x == x (which is OK).
4355 // Do not emit warnings for such cases.
4356 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4357 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4358 if (DRL->getDecl() == DRR->getDecl())
4362 // Special case: check for comparisons against literals that can be exactly
4363 // represented by APFloat. In such cases, do not emit a warning. This
4364 // is a heuristic: often comparison against such literals are used to
4365 // detect if a value in a variable has not changed. This clearly can
4366 // lead to false negatives.
4367 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4371 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4375 // Check for comparisons with builtin types.
4376 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4377 if (CL->isBuiltinCall())
4380 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4381 if (CR->isBuiltinCall())
4384 // Emit the diagnostic.
4385 Diag(Loc, diag::warn_floatingpoint_eq)
4386 << LHS->getSourceRange() << RHS->getSourceRange();
4389 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4390 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
4394 /// Structure recording the 'active' range of an integer-valued
4397 /// The number of bits active in the int.
4400 /// True if the int is known not to have negative values.
4403 IntRange(unsigned Width, bool NonNegative)
4404 : Width(Width), NonNegative(NonNegative)
4407 /// Returns the range of the bool type.
4408 static IntRange forBoolType() {
4409 return IntRange(1, true);
4412 /// Returns the range of an opaque value of the given integral type.
4413 static IntRange forValueOfType(ASTContext &C, QualType T) {
4414 return forValueOfCanonicalType(C,
4415 T->getCanonicalTypeInternal().getTypePtr());
4418 /// Returns the range of an opaque value of a canonical integral type.
4419 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
4420 assert(T->isCanonicalUnqualified());
4422 if (const VectorType *VT = dyn_cast<VectorType>(T))
4423 T = VT->getElementType().getTypePtr();
4424 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4425 T = CT->getElementType().getTypePtr();
4427 // For enum types, use the known bit width of the enumerators.
4428 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4429 EnumDecl *Enum = ET->getDecl();
4430 if (!Enum->isCompleteDefinition())
4431 return IntRange(C.getIntWidth(QualType(T, 0)), false);
4433 unsigned NumPositive = Enum->getNumPositiveBits();
4434 unsigned NumNegative = Enum->getNumNegativeBits();
4436 if (NumNegative == 0)
4437 return IntRange(NumPositive, true/*NonNegative*/);
4439 return IntRange(std::max(NumPositive + 1, NumNegative),
4440 false/*NonNegative*/);
4443 const BuiltinType *BT = cast<BuiltinType>(T);
4444 assert(BT->isInteger());
4446 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4449 /// Returns the "target" range of a canonical integral type, i.e.
4450 /// the range of values expressible in the type.
4452 /// This matches forValueOfCanonicalType except that enums have the
4453 /// full range of their type, not the range of their enumerators.
4454 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4455 assert(T->isCanonicalUnqualified());
4457 if (const VectorType *VT = dyn_cast<VectorType>(T))
4458 T = VT->getElementType().getTypePtr();
4459 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4460 T = CT->getElementType().getTypePtr();
4461 if (const EnumType *ET = dyn_cast<EnumType>(T))
4462 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
4464 const BuiltinType *BT = cast<BuiltinType>(T);
4465 assert(BT->isInteger());
4467 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4470 /// Returns the supremum of two ranges: i.e. their conservative merge.
4471 static IntRange join(IntRange L, IntRange R) {
4472 return IntRange(std::max(L.Width, R.Width),
4473 L.NonNegative && R.NonNegative);
4476 /// Returns the infinum of two ranges: i.e. their aggressive merge.
4477 static IntRange meet(IntRange L, IntRange R) {
4478 return IntRange(std::min(L.Width, R.Width),
4479 L.NonNegative || R.NonNegative);
4483 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4484 unsigned MaxWidth) {
4485 if (value.isSigned() && value.isNegative())
4486 return IntRange(value.getMinSignedBits(), false);
4488 if (value.getBitWidth() > MaxWidth)
4489 value = value.trunc(MaxWidth);
4491 // isNonNegative() just checks the sign bit without considering
4493 return IntRange(value.getActiveBits(), true);
4496 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4497 unsigned MaxWidth) {
4499 return GetValueRange(C, result.getInt(), MaxWidth);
4501 if (result.isVector()) {
4502 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4503 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4504 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4505 R = IntRange::join(R, El);
4510 if (result.isComplexInt()) {
4511 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4512 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4513 return IntRange::join(R, I);
4516 // This can happen with lossless casts to intptr_t of "based" lvalues.
4517 // Assume it might use arbitrary bits.
4518 // FIXME: The only reason we need to pass the type in here is to get
4519 // the sign right on this one case. It would be nice if APValue
4521 assert(result.isLValue() || result.isAddrLabelDiff());
4522 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
4525 static QualType GetExprType(Expr *E) {
4526 QualType Ty = E->getType();
4527 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4528 Ty = AtomicRHS->getValueType();
4532 /// Pseudo-evaluate the given integer expression, estimating the
4533 /// range of values it might take.
4535 /// \param MaxWidth - the width to which the value will be truncated
4536 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
4537 E = E->IgnoreParens();
4539 // Try a full evaluation first.
4540 Expr::EvalResult result;
4541 if (E->EvaluateAsRValue(result, C))
4542 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
4544 // I think we only want to look through implicit casts here; if the
4545 // user has an explicit widening cast, we should treat the value as
4546 // being of the new, wider type.
4547 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
4548 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
4549 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4551 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
4553 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
4555 // Assume that non-integer casts can span the full range of the type.
4557 return OutputTypeRange;
4560 = GetExprRange(C, CE->getSubExpr(),
4561 std::min(MaxWidth, OutputTypeRange.Width));
4563 // Bail out if the subexpr's range is as wide as the cast type.
4564 if (SubRange.Width >= OutputTypeRange.Width)
4565 return OutputTypeRange;
4567 // Otherwise, we take the smaller width, and we're non-negative if
4568 // either the output type or the subexpr is.
4569 return IntRange(SubRange.Width,
4570 SubRange.NonNegative || OutputTypeRange.NonNegative);
4573 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4574 // If we can fold the condition, just take that operand.
4576 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4577 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4578 : CO->getFalseExpr(),
4581 // Otherwise, conservatively merge.
4582 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4583 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4584 return IntRange::join(L, R);
4587 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4588 switch (BO->getOpcode()) {
4590 // Boolean-valued operations are single-bit and positive.
4599 return IntRange::forBoolType();
4601 // The type of the assignments is the type of the LHS, so the RHS
4602 // is not necessarily the same type.
4611 return IntRange::forValueOfType(C, GetExprType(E));
4613 // Simple assignments just pass through the RHS, which will have
4614 // been coerced to the LHS type.
4617 return GetExprRange(C, BO->getRHS(), MaxWidth);
4619 // Operations with opaque sources are black-listed.
4622 return IntRange::forValueOfType(C, GetExprType(E));
4624 // Bitwise-and uses the *infinum* of the two source ranges.
4627 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4628 GetExprRange(C, BO->getRHS(), MaxWidth));
4630 // Left shift gets black-listed based on a judgement call.
4632 // ...except that we want to treat '1 << (blah)' as logically
4633 // positive. It's an important idiom.
4634 if (IntegerLiteral *I
4635 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4636 if (I->getValue() == 1) {
4637 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
4638 return IntRange(R.Width, /*NonNegative*/ true);
4644 return IntRange::forValueOfType(C, GetExprType(E));
4646 // Right shift by a constant can narrow its left argument.
4648 case BO_ShrAssign: {
4649 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4651 // If the shift amount is a positive constant, drop the width by
4654 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4655 shift.isNonNegative()) {
4656 unsigned zext = shift.getZExtValue();
4657 if (zext >= L.Width)
4658 L.Width = (L.NonNegative ? 0 : 1);
4666 // Comma acts as its right operand.
4668 return GetExprRange(C, BO->getRHS(), MaxWidth);
4670 // Black-list pointer subtractions.
4672 if (BO->getLHS()->getType()->isPointerType())
4673 return IntRange::forValueOfType(C, GetExprType(E));
4676 // The width of a division result is mostly determined by the size
4679 // Don't 'pre-truncate' the operands.
4680 unsigned opWidth = C.getIntWidth(GetExprType(E));
4681 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4683 // If the divisor is constant, use that.
4684 llvm::APSInt divisor;
4685 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4686 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4687 if (log2 >= L.Width)
4688 L.Width = (L.NonNegative ? 0 : 1);
4690 L.Width = std::min(L.Width - log2, MaxWidth);
4694 // Otherwise, just use the LHS's width.
4695 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4696 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4699 // The result of a remainder can't be larger than the result of
4702 // Don't 'pre-truncate' the operands.
4703 unsigned opWidth = C.getIntWidth(GetExprType(E));
4704 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4705 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4707 IntRange meet = IntRange::meet(L, R);
4708 meet.Width = std::min(meet.Width, MaxWidth);
4712 // The default behavior is okay for these.
4720 // The default case is to treat the operation as if it were closed
4721 // on the narrowest type that encompasses both operands.
4722 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4723 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4724 return IntRange::join(L, R);
4727 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4728 switch (UO->getOpcode()) {
4729 // Boolean-valued operations are white-listed.
4731 return IntRange::forBoolType();
4733 // Operations with opaque sources are black-listed.
4735 case UO_AddrOf: // should be impossible
4736 return IntRange::forValueOfType(C, GetExprType(E));
4739 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4743 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4744 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4746 if (FieldDecl *BitField = E->getSourceBitField())
4747 return IntRange(BitField->getBitWidthValue(C),
4748 BitField->getType()->isUnsignedIntegerOrEnumerationType());
4750 return IntRange::forValueOfType(C, GetExprType(E));
4753 static IntRange GetExprRange(ASTContext &C, Expr *E) {
4754 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
4757 /// Checks whether the given value, which currently has the given
4758 /// source semantics, has the same value when coerced through the
4759 /// target semantics.
4760 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4761 const llvm::fltSemantics &Src,
4762 const llvm::fltSemantics &Tgt) {
4763 llvm::APFloat truncated = value;
4766 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4767 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4769 return truncated.bitwiseIsEqual(value);
4772 /// Checks whether the given value, which currently has the given
4773 /// source semantics, has the same value when coerced through the
4774 /// target semantics.
4776 /// The value might be a vector of floats (or a complex number).
4777 static bool IsSameFloatAfterCast(const APValue &value,
4778 const llvm::fltSemantics &Src,
4779 const llvm::fltSemantics &Tgt) {
4780 if (value.isFloat())
4781 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4783 if (value.isVector()) {
4784 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4785 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4790 assert(value.isComplexFloat());
4791 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4792 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4795 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
4797 static bool IsZero(Sema &S, Expr *E) {
4798 // Suppress cases where we are comparing against an enum constant.
4799 if (const DeclRefExpr *DR =
4800 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4801 if (isa<EnumConstantDecl>(DR->getDecl()))
4804 // Suppress cases where the '0' value is expanded from a macro.
4805 if (E->getLocStart().isMacroID())
4809 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4812 static bool HasEnumType(Expr *E) {
4813 // Strip off implicit integral promotions.
4814 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4815 if (ICE->getCastKind() != CK_IntegralCast &&
4816 ICE->getCastKind() != CK_NoOp)
4818 E = ICE->getSubExpr();
4821 return E->getType()->isEnumeralType();
4824 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
4825 // Disable warning in template instantiations.
4826 if (!S.ActiveTemplateInstantiations.empty())
4829 BinaryOperatorKind op = E->getOpcode();
4830 if (E->isValueDependent())
4833 if (op == BO_LT && IsZero(S, E->getRHS())) {
4834 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
4835 << "< 0" << "false" << HasEnumType(E->getLHS())
4836 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4837 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
4838 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
4839 << ">= 0" << "true" << HasEnumType(E->getLHS())
4840 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4841 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
4842 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
4843 << "0 >" << "false" << HasEnumType(E->getRHS())
4844 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4845 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
4846 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
4847 << "0 <=" << "true" << HasEnumType(E->getRHS())
4848 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4852 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
4853 Expr *Constant, Expr *Other,
4856 // Disable warning in template instantiations.
4857 if (!S.ActiveTemplateInstantiations.empty())
4860 // 0 values are handled later by CheckTrivialUnsignedComparison().
4864 BinaryOperatorKind op = E->getOpcode();
4865 QualType OtherT = Other->getType();
4866 QualType ConstantT = Constant->getType();
4867 QualType CommonT = E->getLHS()->getType();
4868 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
4870 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
4871 && "comparison with non-integer type");
4873 bool ConstantSigned = ConstantT->isSignedIntegerType();
4874 bool CommonSigned = CommonT->isSignedIntegerType();
4876 bool EqualityOnly = false;
4878 // TODO: Investigate using GetExprRange() to get tighter bounds on
4879 // on the bit ranges.
4880 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
4881 unsigned OtherWidth = OtherRange.Width;
4884 // The common type is signed, therefore no signed to unsigned conversion.
4885 if (!OtherRange.NonNegative) {
4886 // Check that the constant is representable in type OtherT.
4887 if (ConstantSigned) {
4888 if (OtherWidth >= Value.getMinSignedBits())
4890 } else { // !ConstantSigned
4891 if (OtherWidth >= Value.getActiveBits() + 1)
4894 } else { // !OtherSigned
4895 // Check that the constant is representable in type OtherT.
4896 // Negative values are out of range.
4897 if (ConstantSigned) {
4898 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4900 } else { // !ConstantSigned
4901 if (OtherWidth >= Value.getActiveBits())
4905 } else { // !CommonSigned
4906 if (OtherRange.NonNegative) {
4907 if (OtherWidth >= Value.getActiveBits())
4909 } else if (!OtherRange.NonNegative && !ConstantSigned) {
4910 // Check to see if the constant is representable in OtherT.
4911 if (OtherWidth > Value.getActiveBits())
4913 // Check to see if the constant is equivalent to a negative value
4915 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
4916 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
4918 // The constant value rests between values that OtherT can represent after
4919 // conversion. Relational comparison still works, but equality
4920 // comparisons will be tautological.
4921 EqualityOnly = true;
4922 } else { // OtherSigned && ConstantSigned
4923 assert(0 && "Two signed types converted to unsigned types.");
4927 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4930 if (op == BO_EQ || op == BO_NE) {
4931 IsTrue = op == BO_NE;
4932 } else if (EqualityOnly) {
4934 } else if (RhsConstant) {
4935 if (op == BO_GT || op == BO_GE)
4936 IsTrue = !PositiveConstant;
4937 else // op == BO_LT || op == BO_LE
4938 IsTrue = PositiveConstant;
4940 if (op == BO_LT || op == BO_LE)
4941 IsTrue = !PositiveConstant;
4942 else // op == BO_GT || op == BO_GE
4943 IsTrue = PositiveConstant;
4946 // If this is a comparison to an enum constant, include that
4947 // constant in the diagnostic.
4948 const EnumConstantDecl *ED = 0;
4949 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4950 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4952 SmallString<64> PrettySourceValue;
4953 llvm::raw_svector_ostream OS(PrettySourceValue);
4955 OS << '\'' << *ED << "' (" << Value << ")";
4959 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
4960 << OS.str() << OtherT << IsTrue
4961 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4964 /// Analyze the operands of the given comparison. Implements the
4965 /// fallback case from AnalyzeComparison.
4966 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
4967 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4968 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4971 /// \brief Implements -Wsign-compare.
4973 /// \param E the binary operator to check for warnings
4974 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
4975 // The type the comparison is being performed in.
4976 QualType T = E->getLHS()->getType();
4977 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4978 && "comparison with mismatched types");
4979 if (E->isValueDependent())
4980 return AnalyzeImpConvsInComparison(S, E);
4982 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4983 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
4985 bool IsComparisonConstant = false;
4987 // Check whether an integer constant comparison results in a value
4988 // of 'true' or 'false'.
4989 if (T->isIntegralType(S.Context)) {
4990 llvm::APSInt RHSValue;
4991 bool IsRHSIntegralLiteral =
4992 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4993 llvm::APSInt LHSValue;
4994 bool IsLHSIntegralLiteral =
4995 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4996 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4997 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4998 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4999 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5001 IsComparisonConstant =
5002 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
5003 } else if (!T->hasUnsignedIntegerRepresentation())
5004 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
5006 // We don't do anything special if this isn't an unsigned integral
5007 // comparison: we're only interested in integral comparisons, and
5008 // signed comparisons only happen in cases we don't care to warn about.
5010 // We also don't care about value-dependent expressions or expressions
5011 // whose result is a constant.
5012 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
5013 return AnalyzeImpConvsInComparison(S, E);
5015 // Check to see if one of the (unmodified) operands is of different
5017 Expr *signedOperand, *unsignedOperand;
5018 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5019 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
5020 "unsigned comparison between two signed integer expressions?");
5021 signedOperand = LHS;
5022 unsignedOperand = RHS;
5023 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5024 signedOperand = RHS;
5025 unsignedOperand = LHS;
5027 CheckTrivialUnsignedComparison(S, E);
5028 return AnalyzeImpConvsInComparison(S, E);
5031 // Otherwise, calculate the effective range of the signed operand.
5032 IntRange signedRange = GetExprRange(S.Context, signedOperand);
5034 // Go ahead and analyze implicit conversions in the operands. Note
5035 // that we skip the implicit conversions on both sides.
5036 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5037 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
5039 // If the signed range is non-negative, -Wsign-compare won't fire,
5040 // but we should still check for comparisons which are always true
5042 if (signedRange.NonNegative)
5043 return CheckTrivialUnsignedComparison(S, E);
5045 // For (in)equality comparisons, if the unsigned operand is a
5046 // constant which cannot collide with a overflowed signed operand,
5047 // then reinterpreting the signed operand as unsigned will not
5048 // change the result of the comparison.
5049 if (E->isEqualityOp()) {
5050 unsigned comparisonWidth = S.Context.getIntWidth(T);
5051 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
5053 // We should never be unable to prove that the unsigned operand is
5055 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5057 if (unsignedRange.Width < comparisonWidth)
5061 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5062 S.PDiag(diag::warn_mixed_sign_comparison)
5063 << LHS->getType() << RHS->getType()
5064 << LHS->getSourceRange() << RHS->getSourceRange());
5067 /// Analyzes an attempt to assign the given value to a bitfield.
5069 /// Returns true if there was something fishy about the attempt.
5070 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5071 SourceLocation InitLoc) {
5072 assert(Bitfield->isBitField());
5073 if (Bitfield->isInvalidDecl())
5076 // White-list bool bitfields.
5077 if (Bitfield->getType()->isBooleanType())
5080 // Ignore value- or type-dependent expressions.
5081 if (Bitfield->getBitWidth()->isValueDependent() ||
5082 Bitfield->getBitWidth()->isTypeDependent() ||
5083 Init->isValueDependent() ||
5084 Init->isTypeDependent())
5087 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5090 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
5093 unsigned OriginalWidth = Value.getBitWidth();
5094 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
5096 if (OriginalWidth <= FieldWidth)
5099 // Compute the value which the bitfield will contain.
5100 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
5101 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
5103 // Check whether the stored value is equal to the original value.
5104 TruncatedValue = TruncatedValue.extend(OriginalWidth);
5105 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
5108 // Special-case bitfields of width 1: booleans are naturally 0/1, and
5109 // therefore don't strictly fit into a signed bitfield of width 1.
5110 if (FieldWidth == 1 && Value == 1)
5113 std::string PrettyValue = Value.toString(10);
5114 std::string PrettyTrunc = TruncatedValue.toString(10);
5116 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5117 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5118 << Init->getSourceRange();
5123 /// Analyze the given simple or compound assignment for warning-worthy
5125 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
5126 // Just recurse on the LHS.
5127 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5129 // We want to recurse on the RHS as normal unless we're assigning to
5131 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
5132 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
5133 E->getOperatorLoc())) {
5134 // Recurse, ignoring any implicit conversions on the RHS.
5135 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5136 E->getOperatorLoc());
5140 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5143 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
5144 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
5145 SourceLocation CContext, unsigned diag,
5146 bool pruneControlFlow = false) {
5147 if (pruneControlFlow) {
5148 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5150 << SourceType << T << E->getSourceRange()
5151 << SourceRange(CContext));
5154 S.Diag(E->getExprLoc(), diag)
5155 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5158 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
5159 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
5160 SourceLocation CContext, unsigned diag,
5161 bool pruneControlFlow = false) {
5162 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
5165 /// Diagnose an implicit cast from a literal expression. Does not warn when the
5166 /// cast wouldn't lose information.
5167 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5168 SourceLocation CContext) {
5169 // Try to convert the literal exactly to an integer. If we can, don't warn.
5170 bool isExact = false;
5171 const llvm::APFloat &Value = FL->getValue();
5172 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5173 T->hasUnsignedIntegerRepresentation());
5174 if (Value.convertToInteger(IntegerValue,
5175 llvm::APFloat::rmTowardZero, &isExact)
5176 == llvm::APFloat::opOK && isExact)
5179 // FIXME: Force the precision of the source value down so we don't print
5180 // digits which are usually useless (we don't really care here if we
5181 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5182 // would automatically print the shortest representation, but it's a bit
5183 // tricky to implement.
5184 SmallString<16> PrettySourceValue;
5185 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5186 precision = (precision * 59 + 195) / 196;
5187 Value.toString(PrettySourceValue, precision);
5189 SmallString<16> PrettyTargetValue;
5190 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5191 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5193 IntegerValue.toString(PrettyTargetValue);
5195 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
5196 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5197 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
5200 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5201 if (!Range.Width) return "0";
5203 llvm::APSInt ValueInRange = Value;
5204 ValueInRange.setIsSigned(!Range.NonNegative);
5205 ValueInRange = ValueInRange.trunc(Range.Width);
5206 return ValueInRange.toString(10);
5209 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5210 if (!isa<ImplicitCastExpr>(Ex))
5213 Expr *InnerE = Ex->IgnoreParenImpCasts();
5214 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5215 const Type *Source =
5216 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5217 if (Target->isDependentType())
5220 const BuiltinType *FloatCandidateBT =
5221 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5222 const Type *BoolCandidateType = ToBool ? Target : Source;
5224 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5225 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5228 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5229 SourceLocation CC) {
5230 unsigned NumArgs = TheCall->getNumArgs();
5231 for (unsigned i = 0; i < NumArgs; ++i) {
5232 Expr *CurrA = TheCall->getArg(i);
5233 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5236 bool IsSwapped = ((i > 0) &&
5237 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5238 IsSwapped |= ((i < (NumArgs - 1)) &&
5239 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5241 // Warn on this floating-point to bool conversion.
5242 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5243 CurrA->getType(), CC,
5244 diag::warn_impcast_floating_point_to_bool);
5249 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
5250 SourceLocation CC, bool *ICContext = 0) {
5251 if (E->isTypeDependent() || E->isValueDependent()) return;
5253 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5254 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5255 if (Source == Target) return;
5256 if (Target->isDependentType()) return;
5258 // If the conversion context location is invalid don't complain. We also
5259 // don't want to emit a warning if the issue occurs from the expansion of
5260 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5261 // delay this check as long as possible. Once we detect we are in that
5262 // scenario, we just return.
5266 // Diagnose implicit casts to bool.
5267 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5268 if (isa<StringLiteral>(E))
5269 // Warn on string literal to bool. Checks for string literals in logical
5270 // expressions, for instances, assert(0 && "error here"), is prevented
5271 // by a check in AnalyzeImplicitConversions().
5272 return DiagnoseImpCast(S, E, T, CC,
5273 diag::warn_impcast_string_literal_to_bool);
5274 if (Source->isFunctionType()) {
5275 // Warn on function to bool. Checks free functions and static member
5276 // functions. Weakly imported functions are excluded from the check,
5277 // since it's common to test their value to check whether the linker
5278 // found a definition for them.
5280 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5282 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5283 D = M->getMemberDecl();
5286 if (D && !D->isWeak()) {
5287 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5288 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5289 << F << E->getSourceRange() << SourceRange(CC);
5290 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5291 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5292 QualType ReturnType;
5293 UnresolvedSet<4> NonTemplateOverloads;
5294 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
5295 if (!ReturnType.isNull()
5296 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5297 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5298 << FixItHint::CreateInsertion(
5299 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
5306 // Strip vector types.
5307 if (isa<VectorType>(Source)) {
5308 if (!isa<VectorType>(Target)) {
5309 if (S.SourceMgr.isInSystemMacro(CC))
5311 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
5314 // If the vector cast is cast between two vectors of the same size, it is
5315 // a bitcast, not a conversion.
5316 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5319 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5320 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5323 // Strip complex types.
5324 if (isa<ComplexType>(Source)) {
5325 if (!isa<ComplexType>(Target)) {
5326 if (S.SourceMgr.isInSystemMacro(CC))
5329 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
5332 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5333 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5336 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5337 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5339 // If the source is floating point...
5340 if (SourceBT && SourceBT->isFloatingPoint()) {
5341 // ...and the target is floating point...
5342 if (TargetBT && TargetBT->isFloatingPoint()) {
5343 // ...then warn if we're dropping FP rank.
5345 // Builtin FP kinds are ordered by increasing FP rank.
5346 if (SourceBT->getKind() > TargetBT->getKind()) {
5347 // Don't warn about float constants that are precisely
5348 // representable in the target type.
5349 Expr::EvalResult result;
5350 if (E->EvaluateAsRValue(result, S.Context)) {
5351 // Value might be a float, a float vector, or a float complex.
5352 if (IsSameFloatAfterCast(result.Val,
5353 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5354 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
5358 if (S.SourceMgr.isInSystemMacro(CC))
5361 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
5366 // If the target is integral, always warn.
5367 if (TargetBT && TargetBT->isInteger()) {
5368 if (S.SourceMgr.isInSystemMacro(CC))
5371 Expr *InnerE = E->IgnoreParenImpCasts();
5372 // We also want to warn on, e.g., "int i = -1.234"
5373 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5374 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5375 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5377 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5378 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
5380 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5384 // If the target is bool, warn if expr is a function or method call.
5385 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5387 // Check last argument of function call to see if it is an
5388 // implicit cast from a type matching the type the result
5389 // is being cast to.
5390 CallExpr *CEx = cast<CallExpr>(E);
5391 unsigned NumArgs = CEx->getNumArgs();
5393 Expr *LastA = CEx->getArg(NumArgs - 1);
5394 Expr *InnerE = LastA->IgnoreParenImpCasts();
5395 const Type *InnerType =
5396 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5397 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5398 // Warn on this floating-point to bool conversion
5399 DiagnoseImpCast(S, E, T, CC,
5400 diag::warn_impcast_floating_point_to_bool);
5407 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
5408 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
5409 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
5410 && Target->isScalarType() && !Target->isNullPtrType()) {
5411 SourceLocation Loc = E->getSourceRange().getBegin();
5412 if (Loc.isMacroID())
5413 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
5414 if (!Loc.isMacroID() || CC.isMacroID())
5415 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5416 << T << clang::SourceRange(CC)
5417 << FixItHint::CreateReplacement(Loc,
5418 S.getFixItZeroLiteralForType(T, Loc));
5421 if (!Source->isIntegerType() || !Target->isIntegerType())
5424 // TODO: remove this early return once the false positives for constant->bool
5425 // in templates, macros, etc, are reduced or removed.
5426 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5429 IntRange SourceRange = GetExprRange(S.Context, E);
5430 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
5432 if (SourceRange.Width > TargetRange.Width) {
5433 // If the source is a constant, use a default-on diagnostic.
5434 // TODO: this should happen for bitfield stores, too.
5435 llvm::APSInt Value(32);
5436 if (E->isIntegerConstantExpr(Value, S.Context)) {
5437 if (S.SourceMgr.isInSystemMacro(CC))
5440 std::string PrettySourceValue = Value.toString(10);
5441 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
5443 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5444 S.PDiag(diag::warn_impcast_integer_precision_constant)
5445 << PrettySourceValue << PrettyTargetValue
5446 << E->getType() << T << E->getSourceRange()
5447 << clang::SourceRange(CC));
5451 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5452 if (S.SourceMgr.isInSystemMacro(CC))
5455 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
5456 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5457 /* pruneControlFlow */ true);
5458 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
5461 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5462 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5463 SourceRange.Width == TargetRange.Width)) {
5465 if (S.SourceMgr.isInSystemMacro(CC))
5468 unsigned DiagID = diag::warn_impcast_integer_sign;
5470 // Traditionally, gcc has warned about this under -Wsign-compare.
5471 // We also want to warn about it in -Wconversion.
5472 // So if -Wconversion is off, use a completely identical diagnostic
5473 // in the sign-compare group.
5474 // The conditional-checking code will
5476 DiagID = diag::warn_impcast_integer_sign_conditional;
5480 return DiagnoseImpCast(S, E, T, CC, DiagID);
5483 // Diagnose conversions between different enumeration types.
5484 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5485 // type, to give us better diagnostics.
5486 QualType SourceType = E->getType();
5487 if (!S.getLangOpts().CPlusPlus) {
5488 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5489 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5490 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5491 SourceType = S.Context.getTypeDeclType(Enum);
5492 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5496 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5497 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
5498 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5499 TargetEnum->getDecl()->hasNameForLinkage() &&
5500 SourceEnum != TargetEnum) {
5501 if (S.SourceMgr.isInSystemMacro(CC))
5504 return DiagnoseImpCast(S, E, SourceType, T, CC,
5505 diag::warn_impcast_different_enum_types);
5511 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5512 SourceLocation CC, QualType T);
5514 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
5515 SourceLocation CC, bool &ICContext) {
5516 E = E->IgnoreParenImpCasts();
5518 if (isa<ConditionalOperator>(E))
5519 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
5521 AnalyzeImplicitConversions(S, E, CC);
5522 if (E->getType() != T)
5523 return CheckImplicitConversion(S, E, T, CC, &ICContext);
5527 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5528 SourceLocation CC, QualType T) {
5529 AnalyzeImplicitConversions(S, E->getCond(), CC);
5531 bool Suspicious = false;
5532 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5533 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
5535 // If -Wconversion would have warned about either of the candidates
5536 // for a signedness conversion to the context type...
5537 if (!Suspicious) return;
5539 // ...but it's currently ignored...
5540 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5544 // ...then check whether it would have warned about either of the
5545 // candidates for a signedness conversion to the condition type.
5546 if (E->getType() == T) return;
5549 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5550 E->getType(), CC, &Suspicious);
5552 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
5553 E->getType(), CC, &Suspicious);
5556 /// AnalyzeImplicitConversions - Find and report any interesting
5557 /// implicit conversions in the given expression. There are a couple
5558 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
5559 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
5560 QualType T = OrigE->getType();
5561 Expr *E = OrigE->IgnoreParenImpCasts();
5563 if (E->isTypeDependent() || E->isValueDependent())
5566 // For conditional operators, we analyze the arguments as if they
5567 // were being fed directly into the output.
5568 if (isa<ConditionalOperator>(E)) {
5569 ConditionalOperator *CO = cast<ConditionalOperator>(E);
5570 CheckConditionalOperator(S, CO, CC, T);
5574 // Check implicit argument conversions for function calls.
5575 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5576 CheckImplicitArgumentConversions(S, Call, CC);
5578 // Go ahead and check any implicit conversions we might have skipped.
5579 // The non-canonical typecheck is just an optimization;
5580 // CheckImplicitConversion will filter out dead implicit conversions.
5581 if (E->getType() != T)
5582 CheckImplicitConversion(S, E, T, CC);
5584 // Now continue drilling into this expression.
5586 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
5587 if (POE->getResultExpr())
5588 E = POE->getResultExpr();
5591 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5592 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5594 // Skip past explicit casts.
5595 if (isa<ExplicitCastExpr>(E)) {
5596 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
5597 return AnalyzeImplicitConversions(S, E, CC);
5600 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5601 // Do a somewhat different check with comparison operators.
5602 if (BO->isComparisonOp())
5603 return AnalyzeComparison(S, BO);
5605 // And with simple assignments.
5606 if (BO->getOpcode() == BO_Assign)
5607 return AnalyzeAssignment(S, BO);
5610 // These break the otherwise-useful invariant below. Fortunately,
5611 // we don't really need to recurse into them, because any internal
5612 // expressions should have been analyzed already when they were
5613 // built into statements.
5614 if (isa<StmtExpr>(E)) return;
5616 // Don't descend into unevaluated contexts.
5617 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
5619 // Now just recurse over the expression's children.
5620 CC = E->getExprLoc();
5621 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5622 bool IsLogicalOperator = BO && BO->isLogicalOp();
5623 for (Stmt::child_range I = E->children(); I; ++I) {
5624 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
5628 if (IsLogicalOperator &&
5629 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5630 // Ignore checking string literals that are in logical operators.
5632 AnalyzeImplicitConversions(S, ChildExpr, CC);
5636 } // end anonymous namespace
5638 /// Diagnoses "dangerous" implicit conversions within the given
5639 /// expression (which is a full expression). Implements -Wconversion
5640 /// and -Wsign-compare.
5642 /// \param CC the "context" location of the implicit conversion, i.e.
5643 /// the most location of the syntactic entity requiring the implicit
5645 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
5646 // Don't diagnose in unevaluated contexts.
5647 if (isUnevaluatedContext())
5650 // Don't diagnose for value- or type-dependent expressions.
5651 if (E->isTypeDependent() || E->isValueDependent())
5654 // Check for array bounds violations in cases where the check isn't triggered
5655 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5656 // ArraySubscriptExpr is on the RHS of a variable initialization.
5657 CheckArrayAccess(E);
5659 // This is not the right CC for (e.g.) a variable initialization.
5660 AnalyzeImplicitConversions(*this, E, CC);
5663 /// Diagnose when expression is an integer constant expression and its evaluation
5664 /// results in integer overflow
5665 void Sema::CheckForIntOverflow (Expr *E) {
5666 if (isa<BinaryOperator>(E->IgnoreParens()))
5667 E->EvaluateForOverflow(Context);
5671 /// \brief Visitor for expressions which looks for unsequenced operations on the
5673 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
5674 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5676 /// \brief A tree of sequenced regions within an expression. Two regions are
5677 /// unsequenced if one is an ancestor or a descendent of the other. When we
5678 /// finish processing an expression with sequencing, such as a comma
5679 /// expression, we fold its tree nodes into its parent, since they are
5680 /// unsequenced with respect to nodes we will visit later.
5681 class SequenceTree {
5683 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5684 unsigned Parent : 31;
5687 SmallVector<Value, 8> Values;
5690 /// \brief A region within an expression which may be sequenced with respect
5691 /// to some other region.
5693 explicit Seq(unsigned N) : Index(N) {}
5695 friend class SequenceTree;
5700 SequenceTree() { Values.push_back(Value(0)); }
5701 Seq root() const { return Seq(0); }
5703 /// \brief Create a new sequence of operations, which is an unsequenced
5704 /// subset of \p Parent. This sequence of operations is sequenced with
5705 /// respect to other children of \p Parent.
5706 Seq allocate(Seq Parent) {
5707 Values.push_back(Value(Parent.Index));
5708 return Seq(Values.size() - 1);
5711 /// \brief Merge a sequence of operations into its parent.
5713 Values[S.Index].Merged = true;
5716 /// \brief Determine whether two operations are unsequenced. This operation
5717 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5718 /// should have been merged into its parent as appropriate.
5719 bool isUnsequenced(Seq Cur, Seq Old) {
5720 unsigned C = representative(Cur.Index);
5721 unsigned Target = representative(Old.Index);
5722 while (C >= Target) {
5725 C = Values[C].Parent;
5731 /// \brief Pick a representative for a sequence.
5732 unsigned representative(unsigned K) {
5733 if (Values[K].Merged)
5734 // Perform path compression as we go.
5735 return Values[K].Parent = representative(Values[K].Parent);
5740 /// An object for which we can track unsequenced uses.
5741 typedef NamedDecl *Object;
5743 /// Different flavors of object usage which we track. We only track the
5744 /// least-sequenced usage of each kind.
5746 /// A read of an object. Multiple unsequenced reads are OK.
5748 /// A modification of an object which is sequenced before the value
5749 /// computation of the expression, such as ++n in C++.
5751 /// A modification of an object which is not sequenced before the value
5752 /// computation of the expression, such as n++.
5755 UK_Count = UK_ModAsSideEffect + 1
5759 Usage() : Use(0), Seq() {}
5761 SequenceTree::Seq Seq;
5765 UsageInfo() : Diagnosed(false) {}
5766 Usage Uses[UK_Count];
5767 /// Have we issued a diagnostic for this variable already?
5770 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5773 /// Sequenced regions within the expression.
5775 /// Declaration modifications and references which we have seen.
5776 UsageInfoMap UsageMap;
5777 /// The region we are currently within.
5778 SequenceTree::Seq Region;
5779 /// Filled in with declarations which were modified as a side-effect
5780 /// (that is, post-increment operations).
5781 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
5782 /// Expressions to check later. We defer checking these to reduce
5784 SmallVectorImpl<Expr *> &WorkList;
5786 /// RAII object wrapping the visitation of a sequenced subexpression of an
5787 /// expression. At the end of this process, the side-effects of the evaluation
5788 /// become sequenced with respect to the value computation of the result, so
5789 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5791 struct SequencedSubexpression {
5792 SequencedSubexpression(SequenceChecker &Self)
5793 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5794 Self.ModAsSideEffect = &ModAsSideEffect;
5796 ~SequencedSubexpression() {
5797 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5798 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5799 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5800 Self.addUsage(U, ModAsSideEffect[I].first,
5801 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5803 Self.ModAsSideEffect = OldModAsSideEffect;
5806 SequenceChecker &Self;
5807 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5808 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5811 /// RAII object wrapping the visitation of a subexpression which we might
5812 /// choose to evaluate as a constant. If any subexpression is evaluated and
5813 /// found to be non-constant, this allows us to suppress the evaluation of
5814 /// the outer expression.
5815 class EvaluationTracker {
5817 EvaluationTracker(SequenceChecker &Self)
5818 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5819 Self.EvalTracker = this;
5821 ~EvaluationTracker() {
5822 Self.EvalTracker = Prev;
5824 Prev->EvalOK &= EvalOK;
5827 bool evaluate(const Expr *E, bool &Result) {
5828 if (!EvalOK || E->isValueDependent())
5830 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5835 SequenceChecker &Self;
5836 EvaluationTracker *Prev;
5840 /// \brief Find the object which is produced by the specified expression,
5842 Object getObject(Expr *E, bool Mod) const {
5843 E = E->IgnoreParenCasts();
5844 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5845 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5846 return getObject(UO->getSubExpr(), Mod);
5847 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5848 if (BO->getOpcode() == BO_Comma)
5849 return getObject(BO->getRHS(), Mod);
5850 if (Mod && BO->isAssignmentOp())
5851 return getObject(BO->getLHS(), Mod);
5852 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5853 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5854 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5855 return ME->getMemberDecl();
5856 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5857 // FIXME: If this is a reference, map through to its value.
5858 return DRE->getDecl();
5862 /// \brief Note that an object was modified or used by an expression.
5863 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5864 Usage &U = UI.Uses[UK];
5865 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5866 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5867 ModAsSideEffect->push_back(std::make_pair(O, U));
5872 /// \brief Check whether a modification or use conflicts with a prior usage.
5873 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5878 const Usage &U = UI.Uses[OtherKind];
5879 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5883 Expr *ModOrUse = Ref;
5884 if (OtherKind == UK_Use)
5885 std::swap(Mod, ModOrUse);
5887 SemaRef.Diag(Mod->getExprLoc(),
5888 IsModMod ? diag::warn_unsequenced_mod_mod
5889 : diag::warn_unsequenced_mod_use)
5890 << O << SourceRange(ModOrUse->getExprLoc());
5891 UI.Diagnosed = true;
5894 void notePreUse(Object O, Expr *Use) {
5895 UsageInfo &U = UsageMap[O];
5896 // Uses conflict with other modifications.
5897 checkUsage(O, U, Use, UK_ModAsValue, false);
5899 void notePostUse(Object O, Expr *Use) {
5900 UsageInfo &U = UsageMap[O];
5901 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5902 addUsage(U, O, Use, UK_Use);
5905 void notePreMod(Object O, Expr *Mod) {
5906 UsageInfo &U = UsageMap[O];
5907 // Modifications conflict with other modifications and with uses.
5908 checkUsage(O, U, Mod, UK_ModAsValue, true);
5909 checkUsage(O, U, Mod, UK_Use, false);
5911 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5912 UsageInfo &U = UsageMap[O];
5913 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5914 addUsage(U, O, Use, UK);
5918 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5919 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5920 WorkList(WorkList), EvalTracker(0) {
5924 void VisitStmt(Stmt *S) {
5925 // Skip all statements which aren't expressions for now.
5928 void VisitExpr(Expr *E) {
5929 // By default, just recurse to evaluated subexpressions.
5933 void VisitCastExpr(CastExpr *E) {
5934 Object O = Object();
5935 if (E->getCastKind() == CK_LValueToRValue)
5936 O = getObject(E->getSubExpr(), false);
5945 void VisitBinComma(BinaryOperator *BO) {
5946 // C++11 [expr.comma]p1:
5947 // Every value computation and side effect associated with the left
5948 // expression is sequenced before every value computation and side
5949 // effect associated with the right expression.
5950 SequenceTree::Seq LHS = Tree.allocate(Region);
5951 SequenceTree::Seq RHS = Tree.allocate(Region);
5952 SequenceTree::Seq OldRegion = Region;
5955 SequencedSubexpression SeqLHS(*this);
5957 Visit(BO->getLHS());
5961 Visit(BO->getRHS());
5965 // Forget that LHS and RHS are sequenced. They are both unsequenced
5966 // with respect to other stuff.
5971 void VisitBinAssign(BinaryOperator *BO) {
5972 // The modification is sequenced after the value computation of the LHS
5973 // and RHS, so check it before inspecting the operands and update the
5975 Object O = getObject(BO->getLHS(), true);
5977 return VisitExpr(BO);
5981 // C++11 [expr.ass]p7:
5982 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5985 // Therefore, for a compound assignment operator, O is considered used
5986 // everywhere except within the evaluation of E1 itself.
5987 if (isa<CompoundAssignOperator>(BO))
5990 Visit(BO->getLHS());
5992 if (isa<CompoundAssignOperator>(BO))
5995 Visit(BO->getRHS());
5997 // C++11 [expr.ass]p1:
5998 // the assignment is sequenced [...] before the value computation of the
5999 // assignment expression.
6000 // C11 6.5.16/3 has no such rule.
6001 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6002 : UK_ModAsSideEffect);
6004 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6005 VisitBinAssign(CAO);
6008 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6009 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6010 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6011 Object O = getObject(UO->getSubExpr(), true);
6013 return VisitExpr(UO);
6016 Visit(UO->getSubExpr());
6017 // C++11 [expr.pre.incr]p1:
6018 // the expression ++x is equivalent to x+=1
6019 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6020 : UK_ModAsSideEffect);
6023 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6024 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6025 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6026 Object O = getObject(UO->getSubExpr(), true);
6028 return VisitExpr(UO);
6031 Visit(UO->getSubExpr());
6032 notePostMod(O, UO, UK_ModAsSideEffect);
6035 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6036 void VisitBinLOr(BinaryOperator *BO) {
6037 // The side-effects of the LHS of an '&&' are sequenced before the
6038 // value computation of the RHS, and hence before the value computation
6039 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6040 // as if they were unconditionally sequenced.
6041 EvaluationTracker Eval(*this);
6043 SequencedSubexpression Sequenced(*this);
6044 Visit(BO->getLHS());
6048 if (Eval.evaluate(BO->getLHS(), Result)) {
6050 Visit(BO->getRHS());
6052 // Check for unsequenced operations in the RHS, treating it as an
6053 // entirely separate evaluation.
6055 // FIXME: If there are operations in the RHS which are unsequenced
6056 // with respect to operations outside the RHS, and those operations
6057 // are unconditionally evaluated, diagnose them.
6058 WorkList.push_back(BO->getRHS());
6061 void VisitBinLAnd(BinaryOperator *BO) {
6062 EvaluationTracker Eval(*this);
6064 SequencedSubexpression Sequenced(*this);
6065 Visit(BO->getLHS());
6069 if (Eval.evaluate(BO->getLHS(), Result)) {
6071 Visit(BO->getRHS());
6073 WorkList.push_back(BO->getRHS());
6077 // Only visit the condition, unless we can be sure which subexpression will
6079 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
6080 EvaluationTracker Eval(*this);
6082 SequencedSubexpression Sequenced(*this);
6083 Visit(CO->getCond());
6087 if (Eval.evaluate(CO->getCond(), Result))
6088 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
6090 WorkList.push_back(CO->getTrueExpr());
6091 WorkList.push_back(CO->getFalseExpr());
6095 void VisitCallExpr(CallExpr *CE) {
6096 // C++11 [intro.execution]p15:
6097 // When calling a function [...], every value computation and side effect
6098 // associated with any argument expression, or with the postfix expression
6099 // designating the called function, is sequenced before execution of every
6100 // expression or statement in the body of the function [and thus before
6101 // the value computation of its result].
6102 SequencedSubexpression Sequenced(*this);
6103 Base::VisitCallExpr(CE);
6105 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6108 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
6109 // This is a call, so all subexpressions are sequenced before the result.
6110 SequencedSubexpression Sequenced(*this);
6112 if (!CCE->isListInitialization())
6113 return VisitExpr(CCE);
6115 // In C++11, list initializations are sequenced.
6116 SmallVector<SequenceTree::Seq, 32> Elts;
6117 SequenceTree::Seq Parent = Region;
6118 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6121 Region = Tree.allocate(Parent);
6122 Elts.push_back(Region);
6126 // Forget that the initializers are sequenced.
6128 for (unsigned I = 0; I < Elts.size(); ++I)
6129 Tree.merge(Elts[I]);
6132 void VisitInitListExpr(InitListExpr *ILE) {
6133 if (!SemaRef.getLangOpts().CPlusPlus11)
6134 return VisitExpr(ILE);
6136 // In C++11, list initializations are sequenced.
6137 SmallVector<SequenceTree::Seq, 32> Elts;
6138 SequenceTree::Seq Parent = Region;
6139 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6140 Expr *E = ILE->getInit(I);
6142 Region = Tree.allocate(Parent);
6143 Elts.push_back(Region);
6147 // Forget that the initializers are sequenced.
6149 for (unsigned I = 0; I < Elts.size(); ++I)
6150 Tree.merge(Elts[I]);
6155 void Sema::CheckUnsequencedOperations(Expr *E) {
6156 SmallVector<Expr *, 8> WorkList;
6157 WorkList.push_back(E);
6158 while (!WorkList.empty()) {
6159 Expr *Item = WorkList.pop_back_val();
6160 SequenceChecker(*this, Item, WorkList);
6164 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6166 CheckImplicitConversions(E, CheckLoc);
6167 CheckUnsequencedOperations(E);
6168 if (!IsConstexpr && !E->isValueDependent())
6169 CheckForIntOverflow(E);
6172 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6173 FieldDecl *BitField,
6175 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6178 /// CheckParmsForFunctionDef - Check that the parameters of the given
6179 /// function are appropriate for the definition of a function. This
6180 /// takes care of any checks that cannot be performed on the
6181 /// declaration itself, e.g., that the types of each of the function
6182 /// parameters are complete.
6183 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6184 ParmVarDecl *const *PEnd,
6185 bool CheckParameterNames) {
6186 bool HasInvalidParm = false;
6187 for (; P != PEnd; ++P) {
6188 ParmVarDecl *Param = *P;
6190 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6191 // function declarator that is part of a function definition of
6192 // that function shall not have incomplete type.
6194 // This is also C++ [dcl.fct]p6.
6195 if (!Param->isInvalidDecl() &&
6196 RequireCompleteType(Param->getLocation(), Param->getType(),
6197 diag::err_typecheck_decl_incomplete_type)) {
6198 Param->setInvalidDecl();
6199 HasInvalidParm = true;
6202 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6203 // declaration of each parameter shall include an identifier.
6204 if (CheckParameterNames &&
6205 Param->getIdentifier() == 0 &&
6206 !Param->isImplicit() &&
6207 !getLangOpts().CPlusPlus)
6208 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
6211 // If the function declarator is not part of a definition of that
6212 // function, parameters may have incomplete type and may use the [*]
6213 // notation in their sequences of declarator specifiers to specify
6214 // variable length array types.
6215 QualType PType = Param->getOriginalType();
6216 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
6217 if (AT->getSizeModifier() == ArrayType::Star) {
6218 // FIXME: This diagnostic should point the '[*]' if source-location
6219 // information is added for it.
6220 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
6223 PType= AT->getElementType();
6226 // MSVC destroys objects passed by value in the callee. Therefore a
6227 // function definition which takes such a parameter must be able to call the
6228 // object's destructor.
6229 if (getLangOpts().CPlusPlus &&
6230 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6231 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6232 FinalizeVarWithDestructor(Param, RT);
6236 return HasInvalidParm;
6239 /// CheckCastAlign - Implements -Wcast-align, which warns when a
6240 /// pointer cast increases the alignment requirements.
6241 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6242 // This is actually a lot of work to potentially be doing on every
6243 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
6244 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6246 == DiagnosticsEngine::Ignored)
6249 // Ignore dependent types.
6250 if (T->isDependentType() || Op->getType()->isDependentType())
6253 // Require that the destination be a pointer type.
6254 const PointerType *DestPtr = T->getAs<PointerType>();
6255 if (!DestPtr) return;
6257 // If the destination has alignment 1, we're done.
6258 QualType DestPointee = DestPtr->getPointeeType();
6259 if (DestPointee->isIncompleteType()) return;
6260 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6261 if (DestAlign.isOne()) return;
6263 // Require that the source be a pointer type.
6264 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6265 if (!SrcPtr) return;
6266 QualType SrcPointee = SrcPtr->getPointeeType();
6268 // Whitelist casts from cv void*. We already implicitly
6269 // whitelisted casts to cv void*, since they have alignment 1.
6270 // Also whitelist casts involving incomplete types, which implicitly
6272 if (SrcPointee->isIncompleteType()) return;
6274 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6275 if (SrcAlign >= DestAlign) return;
6277 Diag(TRange.getBegin(), diag::warn_cast_align)
6278 << Op->getType() << T
6279 << static_cast<unsigned>(SrcAlign.getQuantity())
6280 << static_cast<unsigned>(DestAlign.getQuantity())
6281 << TRange << Op->getSourceRange();
6284 static const Type* getElementType(const Expr *BaseExpr) {
6285 const Type* EltType = BaseExpr->getType().getTypePtr();
6286 if (EltType->isAnyPointerType())
6287 return EltType->getPointeeType().getTypePtr();
6288 else if (EltType->isArrayType())
6289 return EltType->getBaseElementTypeUnsafe();
6293 /// \brief Check whether this array fits the idiom of a size-one tail padded
6294 /// array member of a struct.
6296 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
6297 /// commonly used to emulate flexible arrays in C89 code.
6298 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6299 const NamedDecl *ND) {
6300 if (Size != 1 || !ND) return false;
6302 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6303 if (!FD) return false;
6305 // Don't consider sizes resulting from macro expansions or template argument
6306 // substitution to form C89 tail-padded arrays.
6308 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
6310 TypeLoc TL = TInfo->getTypeLoc();
6311 // Look through typedefs.
6312 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6313 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
6314 TInfo = TDL->getTypeSourceInfo();
6317 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6318 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
6319 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6325 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
6326 if (!RD) return false;
6327 if (RD->isUnion()) return false;
6328 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6329 if (!CRD->isStandardLayout()) return false;
6332 // See if this is the last field decl in the record.
6334 while ((D = D->getNextDeclInContext()))
6335 if (isa<FieldDecl>(D))
6340 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
6341 const ArraySubscriptExpr *ASE,
6342 bool AllowOnePastEnd, bool IndexNegated) {
6343 IndexExpr = IndexExpr->IgnoreParenImpCasts();
6344 if (IndexExpr->isValueDependent())
6347 const Type *EffectiveType = getElementType(BaseExpr);
6348 BaseExpr = BaseExpr->IgnoreParenCasts();
6349 const ConstantArrayType *ArrayTy =
6350 Context.getAsConstantArrayType(BaseExpr->getType());
6355 if (!IndexExpr->EvaluateAsInt(index, Context))
6360 const NamedDecl *ND = NULL;
6361 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6362 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6363 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6364 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6366 if (index.isUnsigned() || !index.isNegative()) {
6367 llvm::APInt size = ArrayTy->getSize();
6368 if (!size.isStrictlyPositive())
6371 const Type* BaseType = getElementType(BaseExpr);
6372 if (BaseType != EffectiveType) {
6373 // Make sure we're comparing apples to apples when comparing index to size
6374 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6375 uint64_t array_typesize = Context.getTypeSize(BaseType);
6376 // Handle ptrarith_typesize being zero, such as when casting to void*
6377 if (!ptrarith_typesize) ptrarith_typesize = 1;
6378 if (ptrarith_typesize != array_typesize) {
6379 // There's a cast to a different size type involved
6380 uint64_t ratio = array_typesize / ptrarith_typesize;
6381 // TODO: Be smarter about handling cases where array_typesize is not a
6382 // multiple of ptrarith_typesize
6383 if (ptrarith_typesize * ratio == array_typesize)
6384 size *= llvm::APInt(size.getBitWidth(), ratio);
6388 if (size.getBitWidth() > index.getBitWidth())
6389 index = index.zext(size.getBitWidth());
6390 else if (size.getBitWidth() < index.getBitWidth())
6391 size = size.zext(index.getBitWidth());
6393 // For array subscripting the index must be less than size, but for pointer
6394 // arithmetic also allow the index (offset) to be equal to size since
6395 // computing the next address after the end of the array is legal and
6396 // commonly done e.g. in C++ iterators and range-based for loops.
6397 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
6400 // Also don't warn for arrays of size 1 which are members of some
6401 // structure. These are often used to approximate flexible arrays in C89
6403 if (IsTailPaddedMemberArray(*this, size, ND))
6406 // Suppress the warning if the subscript expression (as identified by the
6407 // ']' location) and the index expression are both from macro expansions
6408 // within a system header.
6410 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6411 ASE->getRBracketLoc());
6412 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6413 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6414 IndexExpr->getLocStart());
6415 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
6420 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
6422 DiagID = diag::warn_array_index_exceeds_bounds;
6424 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6425 PDiag(DiagID) << index.toString(10, true)
6426 << size.toString(10, true)
6427 << (unsigned)size.getLimitedValue(~0U)
6428 << IndexExpr->getSourceRange());
6430 unsigned DiagID = diag::warn_array_index_precedes_bounds;
6432 DiagID = diag::warn_ptr_arith_precedes_bounds;
6433 if (index.isNegative()) index = -index;
6436 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6437 PDiag(DiagID) << index.toString(10, true)
6438 << IndexExpr->getSourceRange());
6442 // Try harder to find a NamedDecl to point at in the note.
6443 while (const ArraySubscriptExpr *ASE =
6444 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6445 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6446 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6447 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6448 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6449 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6453 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6454 PDiag(diag::note_array_index_out_of_bounds)
6455 << ND->getDeclName());
6458 void Sema::CheckArrayAccess(const Expr *expr) {
6459 int AllowOnePastEnd = 0;
6461 expr = expr->IgnoreParenImpCasts();
6462 switch (expr->getStmtClass()) {
6463 case Stmt::ArraySubscriptExprClass: {
6464 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
6465 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
6466 AllowOnePastEnd > 0);
6469 case Stmt::UnaryOperatorClass: {
6470 // Only unwrap the * and & unary operators
6471 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6472 expr = UO->getSubExpr();
6473 switch (UO->getOpcode()) {
6485 case Stmt::ConditionalOperatorClass: {
6486 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6487 if (const Expr *lhs = cond->getLHS())
6488 CheckArrayAccess(lhs);
6489 if (const Expr *rhs = cond->getRHS())
6490 CheckArrayAccess(rhs);
6499 //===--- CHECK: Objective-C retain cycles ----------------------------------//
6502 struct RetainCycleOwner {
6503 RetainCycleOwner() : Variable(0), Indirect(false) {}
6509 void setLocsFrom(Expr *e) {
6510 Loc = e->getExprLoc();
6511 Range = e->getSourceRange();
6516 /// Consider whether capturing the given variable can possibly lead to
6518 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
6519 // In ARC, it's captured strongly iff the variable has __strong
6520 // lifetime. In MRR, it's captured strongly if the variable is
6521 // __block and has an appropriate type.
6522 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6525 owner.Variable = var;
6527 owner.setLocsFrom(ref);
6531 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
6533 e = e->IgnoreParens();
6534 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6535 switch (cast->getCastKind()) {
6537 case CK_LValueBitCast:
6538 case CK_LValueToRValue:
6539 case CK_ARCReclaimReturnedObject:
6540 e = cast->getSubExpr();
6548 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6549 ObjCIvarDecl *ivar = ref->getDecl();
6550 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6553 // Try to find a retain cycle in the base.
6554 if (!findRetainCycleOwner(S, ref->getBase(), owner))
6557 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6558 owner.Indirect = true;
6562 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6563 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6564 if (!var) return false;
6565 return considerVariable(var, ref, owner);
6568 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6569 if (member->isArrow()) return false;
6571 // Don't count this as an indirect ownership.
6572 e = member->getBase();
6576 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6577 // Only pay attention to pseudo-objects on property references.
6578 ObjCPropertyRefExpr *pre
6579 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6581 if (!pre) return false;
6582 if (pre->isImplicitProperty()) return false;
6583 ObjCPropertyDecl *property = pre->getExplicitProperty();
6584 if (!property->isRetaining() &&
6585 !(property->getPropertyIvarDecl() &&
6586 property->getPropertyIvarDecl()->getType()
6587 .getObjCLifetime() == Qualifiers::OCL_Strong))
6590 owner.Indirect = true;
6591 if (pre->isSuperReceiver()) {
6592 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6593 if (!owner.Variable)
6595 owner.Loc = pre->getLocation();
6596 owner.Range = pre->getSourceRange();
6599 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6611 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6612 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6613 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6614 Variable(variable), Capturer(0) {}
6619 void VisitDeclRefExpr(DeclRefExpr *ref) {
6620 if (ref->getDecl() == Variable && !Capturer)
6624 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6625 if (Capturer) return;
6626 Visit(ref->getBase());
6627 if (Capturer && ref->isFreeIvar())
6631 void VisitBlockExpr(BlockExpr *block) {
6632 // Look inside nested blocks
6633 if (block->getBlockDecl()->capturesVariable(Variable))
6634 Visit(block->getBlockDecl()->getBody());
6637 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6638 if (Capturer) return;
6639 if (OVE->getSourceExpr())
6640 Visit(OVE->getSourceExpr());
6645 /// Check whether the given argument is a block which captures a
6647 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6648 assert(owner.Variable && owner.Loc.isValid());
6650 e = e->IgnoreParenCasts();
6652 // Look through [^{...} copy] and Block_copy(^{...}).
6653 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6654 Selector Cmd = ME->getSelector();
6655 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6656 e = ME->getInstanceReceiver();
6659 e = e->IgnoreParenCasts();
6661 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6662 if (CE->getNumArgs() == 1) {
6663 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
6665 const IdentifierInfo *FnI = Fn->getIdentifier();
6666 if (FnI && FnI->isStr("_Block_copy")) {
6667 e = CE->getArg(0)->IgnoreParenCasts();
6673 BlockExpr *block = dyn_cast<BlockExpr>(e);
6674 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6677 FindCaptureVisitor visitor(S.Context, owner.Variable);
6678 visitor.Visit(block->getBlockDecl()->getBody());
6679 return visitor.Capturer;
6682 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6683 RetainCycleOwner &owner) {
6685 assert(owner.Variable && owner.Loc.isValid());
6687 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6688 << owner.Variable << capturer->getSourceRange();
6689 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6690 << owner.Indirect << owner.Range;
6693 /// Check for a keyword selector that starts with the word 'add' or
6695 static bool isSetterLikeSelector(Selector sel) {
6696 if (sel.isUnarySelector()) return false;
6698 StringRef str = sel.getNameForSlot(0);
6699 while (!str.empty() && str.front() == '_') str = str.substr(1);
6700 if (str.startswith("set"))
6701 str = str.substr(3);
6702 else if (str.startswith("add")) {
6703 // Specially whitelist 'addOperationWithBlock:'.
6704 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6706 str = str.substr(3);
6711 if (str.empty()) return true;
6712 return !isLowercase(str.front());
6715 /// Check a message send to see if it's likely to cause a retain cycle.
6716 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6717 // Only check instance methods whose selector looks like a setter.
6718 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6721 // Try to find a variable that the receiver is strongly owned by.
6722 RetainCycleOwner owner;
6723 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
6724 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
6727 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6728 owner.Variable = getCurMethodDecl()->getSelfDecl();
6729 owner.Loc = msg->getSuperLoc();
6730 owner.Range = msg->getSuperLoc();
6733 // Check whether the receiver is captured by any of the arguments.
6734 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6735 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6736 return diagnoseRetainCycle(*this, capturer, owner);
6739 /// Check a property assign to see if it's likely to cause a retain cycle.
6740 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6741 RetainCycleOwner owner;
6742 if (!findRetainCycleOwner(*this, receiver, owner))
6745 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6746 diagnoseRetainCycle(*this, capturer, owner);
6749 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6750 RetainCycleOwner Owner;
6751 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6754 // Because we don't have an expression for the variable, we have to set the
6755 // location explicitly here.
6756 Owner.Loc = Var->getLocation();
6757 Owner.Range = Var->getSourceRange();
6759 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6760 diagnoseRetainCycle(*this, Capturer, Owner);
6763 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6764 Expr *RHS, bool isProperty) {
6765 // Check if RHS is an Objective-C object literal, which also can get
6766 // immediately zapped in a weak reference. Note that we explicitly
6767 // allow ObjCStringLiterals, since those are designed to never really die.
6768 RHS = RHS->IgnoreParenImpCasts();
6770 // This enum needs to match with the 'select' in
6771 // warn_objc_arc_literal_assign (off-by-1).
6772 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6773 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6776 S.Diag(Loc, diag::warn_arc_literal_assign)
6778 << (isProperty ? 0 : 1)
6779 << RHS->getSourceRange();
6784 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6785 Qualifiers::ObjCLifetime LT,
6786 Expr *RHS, bool isProperty) {
6787 // Strip off any implicit cast added to get to the one ARC-specific.
6788 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6789 if (cast->getCastKind() == CK_ARCConsumeObject) {
6790 S.Diag(Loc, diag::warn_arc_retained_assign)
6791 << (LT == Qualifiers::OCL_ExplicitNone)
6792 << (isProperty ? 0 : 1)
6793 << RHS->getSourceRange();
6796 RHS = cast->getSubExpr();
6799 if (LT == Qualifiers::OCL_Weak &&
6800 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6806 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6807 QualType LHS, Expr *RHS) {
6808 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6810 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6813 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6819 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6820 Expr *LHS, Expr *RHS) {
6822 // PropertyRef on LHS type need be directly obtained from
6823 // its declaration as it has a PsuedoType.
6824 ObjCPropertyRefExpr *PRE
6825 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6826 if (PRE && !PRE->isImplicitProperty()) {
6827 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6829 LHSType = PD->getType();
6832 if (LHSType.isNull())
6833 LHSType = LHS->getType();
6835 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6837 if (LT == Qualifiers::OCL_Weak) {
6838 DiagnosticsEngine::Level Level =
6839 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6840 if (Level != DiagnosticsEngine::Ignored)
6841 getCurFunction()->markSafeWeakUse(LHS);
6844 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6847 // FIXME. Check for other life times.
6848 if (LT != Qualifiers::OCL_None)
6852 if (PRE->isImplicitProperty())
6854 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6858 unsigned Attributes = PD->getPropertyAttributes();
6859 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
6860 // when 'assign' attribute was not explicitly specified
6861 // by user, ignore it and rely on property type itself
6862 // for lifetime info.
6863 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6864 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6865 LHSType->isObjCRetainableType())
6868 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6869 if (cast->getCastKind() == CK_ARCConsumeObject) {
6870 Diag(Loc, diag::warn_arc_retained_property_assign)
6871 << RHS->getSourceRange();
6874 RHS = cast->getSubExpr();
6877 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
6878 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6884 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6887 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6888 SourceLocation StmtLoc,
6889 const NullStmt *Body) {
6890 // Do not warn if the body is a macro that expands to nothing, e.g:
6896 if (Body->hasLeadingEmptyMacro())
6899 // Get line numbers of statement and body.
6900 bool StmtLineInvalid;
6901 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6903 if (StmtLineInvalid)
6906 bool BodyLineInvalid;
6907 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6909 if (BodyLineInvalid)
6912 // Warn if null statement and body are on the same line.
6913 if (StmtLine != BodyLine)
6918 } // Unnamed namespace
6920 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6923 // Since this is a syntactic check, don't emit diagnostic for template
6924 // instantiations, this just adds noise.
6925 if (CurrentInstantiationScope)
6928 // The body should be a null statement.
6929 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6933 // Do the usual checks.
6934 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6937 Diag(NBody->getSemiLoc(), DiagID);
6938 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6941 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6942 const Stmt *PossibleBody) {
6943 assert(!CurrentInstantiationScope); // Ensured by caller
6945 SourceLocation StmtLoc;
6948 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6949 StmtLoc = FS->getRParenLoc();
6950 Body = FS->getBody();
6951 DiagID = diag::warn_empty_for_body;
6952 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6953 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6954 Body = WS->getBody();
6955 DiagID = diag::warn_empty_while_body;
6957 return; // Neither `for' nor `while'.
6959 // The body should be a null statement.
6960 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6964 // Skip expensive checks if diagnostic is disabled.
6965 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6966 DiagnosticsEngine::Ignored)
6969 // Do the usual checks.
6970 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6973 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6974 // noise level low, emit diagnostics only if for/while is followed by a
6975 // CompoundStmt, e.g.:
6976 // for (int i = 0; i < n; i++);
6980 // or if for/while is followed by a statement with more indentation
6981 // than for/while itself:
6982 // for (int i = 0; i < n; i++);
6984 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6985 if (!ProbableTypo) {
6986 bool BodyColInvalid;
6987 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6988 PossibleBody->getLocStart(),
6993 bool StmtColInvalid;
6994 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7000 if (BodyCol > StmtCol)
7001 ProbableTypo = true;
7005 Diag(NBody->getSemiLoc(), DiagID);
7006 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7010 //===--- Layout compatibility ----------------------------------------------//
7014 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7016 /// \brief Check if two enumeration types are layout-compatible.
7017 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7018 // C++11 [dcl.enum] p8:
7019 // Two enumeration types are layout-compatible if they have the same
7021 return ED1->isComplete() && ED2->isComplete() &&
7022 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7025 /// \brief Check if two fields are layout-compatible.
7026 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7027 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7030 if (Field1->isBitField() != Field2->isBitField())
7033 if (Field1->isBitField()) {
7034 // Make sure that the bit-fields are the same length.
7035 unsigned Bits1 = Field1->getBitWidthValue(C);
7036 unsigned Bits2 = Field2->getBitWidthValue(C);
7045 /// \brief Check if two standard-layout structs are layout-compatible.
7046 /// (C++11 [class.mem] p17)
7047 bool isLayoutCompatibleStruct(ASTContext &C,
7050 // If both records are C++ classes, check that base classes match.
7051 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7052 // If one of records is a CXXRecordDecl we are in C++ mode,
7053 // thus the other one is a CXXRecordDecl, too.
7054 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7055 // Check number of base classes.
7056 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7059 // Check the base classes.
7060 for (CXXRecordDecl::base_class_const_iterator
7061 Base1 = D1CXX->bases_begin(),
7062 BaseEnd1 = D1CXX->bases_end(),
7063 Base2 = D2CXX->bases_begin();
7066 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7069 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7070 // If only RD2 is a C++ class, it should have zero base classes.
7071 if (D2CXX->getNumBases() > 0)
7075 // Check the fields.
7076 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7077 Field2End = RD2->field_end(),
7078 Field1 = RD1->field_begin(),
7079 Field1End = RD1->field_end();
7080 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7081 if (!isLayoutCompatible(C, *Field1, *Field2))
7084 if (Field1 != Field1End || Field2 != Field2End)
7090 /// \brief Check if two standard-layout unions are layout-compatible.
7091 /// (C++11 [class.mem] p18)
7092 bool isLayoutCompatibleUnion(ASTContext &C,
7095 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7096 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7097 Field2End = RD2->field_end();
7098 Field2 != Field2End; ++Field2) {
7099 UnmatchedFields.insert(*Field2);
7102 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7103 Field1End = RD1->field_end();
7104 Field1 != Field1End; ++Field1) {
7105 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7106 I = UnmatchedFields.begin(),
7107 E = UnmatchedFields.end();
7109 for ( ; I != E; ++I) {
7110 if (isLayoutCompatible(C, *Field1, *I)) {
7111 bool Result = UnmatchedFields.erase(*I);
7121 return UnmatchedFields.empty();
7124 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7125 if (RD1->isUnion() != RD2->isUnion())
7129 return isLayoutCompatibleUnion(C, RD1, RD2);
7131 return isLayoutCompatibleStruct(C, RD1, RD2);
7134 /// \brief Check if two types are layout-compatible in C++11 sense.
7135 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7136 if (T1.isNull() || T2.isNull())
7139 // C++11 [basic.types] p11:
7140 // If two types T1 and T2 are the same type, then T1 and T2 are
7141 // layout-compatible types.
7142 if (C.hasSameType(T1, T2))
7145 T1 = T1.getCanonicalType().getUnqualifiedType();
7146 T2 = T2.getCanonicalType().getUnqualifiedType();
7148 const Type::TypeClass TC1 = T1->getTypeClass();
7149 const Type::TypeClass TC2 = T2->getTypeClass();
7154 if (TC1 == Type::Enum) {
7155 return isLayoutCompatible(C,
7156 cast<EnumType>(T1)->getDecl(),
7157 cast<EnumType>(T2)->getDecl());
7158 } else if (TC1 == Type::Record) {
7159 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7162 return isLayoutCompatible(C,
7163 cast<RecordType>(T1)->getDecl(),
7164 cast<RecordType>(T2)->getDecl());
7171 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7174 /// \brief Given a type tag expression find the type tag itself.
7176 /// \param TypeExpr Type tag expression, as it appears in user's code.
7178 /// \param VD Declaration of an identifier that appears in a type tag.
7180 /// \param MagicValue Type tag magic value.
7181 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7182 const ValueDecl **VD, uint64_t *MagicValue) {
7187 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7189 switch (TypeExpr->getStmtClass()) {
7190 case Stmt::UnaryOperatorClass: {
7191 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7192 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7193 TypeExpr = UO->getSubExpr();
7199 case Stmt::DeclRefExprClass: {
7200 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7201 *VD = DRE->getDecl();
7205 case Stmt::IntegerLiteralClass: {
7206 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7207 llvm::APInt MagicValueAPInt = IL->getValue();
7208 if (MagicValueAPInt.getActiveBits() <= 64) {
7209 *MagicValue = MagicValueAPInt.getZExtValue();
7215 case Stmt::BinaryConditionalOperatorClass:
7216 case Stmt::ConditionalOperatorClass: {
7217 const AbstractConditionalOperator *ACO =
7218 cast<AbstractConditionalOperator>(TypeExpr);
7220 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7222 TypeExpr = ACO->getTrueExpr();
7224 TypeExpr = ACO->getFalseExpr();
7230 case Stmt::BinaryOperatorClass: {
7231 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7232 if (BO->getOpcode() == BO_Comma) {
7233 TypeExpr = BO->getRHS();
7245 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
7247 /// \param TypeExpr Expression that specifies a type tag.
7249 /// \param MagicValues Registered magic values.
7251 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7254 /// \param TypeInfo Information about the corresponding C type.
7256 /// \returns true if the corresponding C type was found.
7257 bool GetMatchingCType(
7258 const IdentifierInfo *ArgumentKind,
7259 const Expr *TypeExpr, const ASTContext &Ctx,
7260 const llvm::DenseMap<Sema::TypeTagMagicValue,
7261 Sema::TypeTagData> *MagicValues,
7262 bool &FoundWrongKind,
7263 Sema::TypeTagData &TypeInfo) {
7264 FoundWrongKind = false;
7266 // Variable declaration that has type_tag_for_datatype attribute.
7267 const ValueDecl *VD = NULL;
7269 uint64_t MagicValue;
7271 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7275 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7276 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7277 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7279 if (I->getArgumentKind() != ArgumentKind) {
7280 FoundWrongKind = true;
7283 TypeInfo.Type = I->getMatchingCType();
7284 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7285 TypeInfo.MustBeNull = I->getMustBeNull();
7294 llvm::DenseMap<Sema::TypeTagMagicValue,
7295 Sema::TypeTagData>::const_iterator I =
7296 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7297 if (I == MagicValues->end())
7300 TypeInfo = I->second;
7303 } // unnamed namespace
7305 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7306 uint64_t MagicValue, QualType Type,
7307 bool LayoutCompatible,
7309 if (!TypeTagForDatatypeMagicValues)
7310 TypeTagForDatatypeMagicValues.reset(
7311 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7313 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7314 (*TypeTagForDatatypeMagicValues)[Magic] =
7315 TypeTagData(Type, LayoutCompatible, MustBeNull);
7319 bool IsSameCharType(QualType T1, QualType T2) {
7320 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7324 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7328 BuiltinType::Kind T1Kind = BT1->getKind();
7329 BuiltinType::Kind T2Kind = BT2->getKind();
7331 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7332 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7333 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7334 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7336 } // unnamed namespace
7338 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7339 const Expr * const *ExprArgs) {
7340 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7341 bool IsPointerAttr = Attr->getIsPointer();
7343 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7344 bool FoundWrongKind;
7345 TypeTagData TypeInfo;
7346 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7347 TypeTagForDatatypeMagicValues.get(),
7348 FoundWrongKind, TypeInfo)) {
7350 Diag(TypeTagExpr->getExprLoc(),
7351 diag::warn_type_tag_for_datatype_wrong_kind)
7352 << TypeTagExpr->getSourceRange();
7356 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7357 if (IsPointerAttr) {
7358 // Skip implicit cast of pointer to `void *' (as a function argument).
7359 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
7360 if (ICE->getType()->isVoidPointerType() &&
7361 ICE->getCastKind() == CK_BitCast)
7362 ArgumentExpr = ICE->getSubExpr();
7364 QualType ArgumentType = ArgumentExpr->getType();
7366 // Passing a `void*' pointer shouldn't trigger a warning.
7367 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7370 if (TypeInfo.MustBeNull) {
7371 // Type tag with matching void type requires a null pointer.
7372 if (!ArgumentExpr->isNullPointerConstant(Context,
7373 Expr::NPC_ValueDependentIsNotNull)) {
7374 Diag(ArgumentExpr->getExprLoc(),
7375 diag::warn_type_safety_null_pointer_required)
7376 << ArgumentKind->getName()
7377 << ArgumentExpr->getSourceRange()
7378 << TypeTagExpr->getSourceRange();
7383 QualType RequiredType = TypeInfo.Type;
7385 RequiredType = Context.getPointerType(RequiredType);
7387 bool mismatch = false;
7388 if (!TypeInfo.LayoutCompatible) {
7389 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7391 // C++11 [basic.fundamental] p1:
7392 // Plain char, signed char, and unsigned char are three distinct types.
7394 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7395 // char' depending on the current char signedness mode.
7397 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7398 RequiredType->getPointeeType())) ||
7399 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7403 mismatch = !isLayoutCompatible(Context,
7404 ArgumentType->getPointeeType(),
7405 RequiredType->getPointeeType());
7407 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7410 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7411 << ArgumentType << ArgumentKind->getName()
7412 << TypeInfo.LayoutCompatible << RequiredType
7413 << ArgumentExpr->getSourceRange()
7414 << TypeTagExpr->getSourceRange();