blob: 5fe2d03d1d19a550d88c7867ed9b42df2559a481 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattner59907c42007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Richard Smith0e218972013-08-05 18:49:43 +000035#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "llvm/ADT/SmallString.h"
Richard Smith0e218972013-08-05 18:49:43 +000037#include "llvm/ADT/STLExtras.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000048}
49
John McCall8e10f3b2011-02-26 05:39:39 +000050/// 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.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
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();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerougee5939212012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
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();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerougee5939212012-04-28 17:39:16 +000084
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();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith5154dce2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
104 ExprResult Arg(S.Owned(TheCall->getArg(0)));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
109 TheCall->setArg(0, Arg.take());
110 TheCall->setType(ResultType);
111 return false;
112}
113
John McCall60d7b3a2010-08-24 06:29:42 +0000114ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000116 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000117
Chris Lattner946928f2010-10-01 23:23:24 +0000118 // 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.
124
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;
129
130 llvm::APSInt Result;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132 return true;
133 ICEArguments &= ~(1 << ArgNo);
134 }
135
Anders Carlssond406bf02009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000142 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinVAStart(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000148 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:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 if (SemaBuiltinUnorderedCompare(TheCall))
155 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000156 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000157 case Builtin::BI__builtin_fpclassify:
158 if (SemaBuiltinFPClassification(TheCall, 6))
159 return ExprError();
160 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000161 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:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000166 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000167 return ExprError();
168 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000169 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000170 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.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000173 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000174 if (SemaBuiltinPrefetch(TheCall))
175 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000176 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000177 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000178 if (SemaBuiltinObjectSize(TheCall))
179 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000180 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000181 case Builtin::BI__builtin_longjmp:
182 if (SemaBuiltinLongjmp(TheCall))
183 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000184 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000185
186 case Builtin::BI__builtin_classify_type:
187 if (checkArgCount(*this, TheCall, 1)) return true;
188 TheCall->setType(Context.IntTy);
189 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000190 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000191 if (checkArgCount(*this, TheCall, 1)) return true;
192 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000193 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000194 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000195 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000200 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000201 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000206 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000207 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000212 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000213 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000218 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000219 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000224 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000225 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000230 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000231 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000236 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000237 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000242 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000243 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000248 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000249 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000254 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000255 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000260 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000261 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000266 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000267 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:
Chris Lattner5caa3702009-05-08 06:58:22 +0000272 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000273 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:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000278 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000279 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:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000284 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000285#define BUILTIN(ID, TYPE, ATTRS)
286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000289#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000290 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000291 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000292 return ExprError();
293 break;
Richard Smith5154dce2013-07-11 02:27:57 +0000294 case Builtin::BI__builtin_addressof:
295 if (SemaBuiltinAddressof(*this, TheCall))
296 return ExprError();
297 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000298 }
299
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) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000303 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000304 case llvm::Triple::arm:
305 case llvm::Triple::thumb:
306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307 return ExprError();
308 break;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000309 case llvm::Triple::aarch64:
310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
311 return ExprError();
312 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000313 case llvm::Triple::mips:
314 case llvm::Triple::mipsel:
315 case llvm::Triple::mips64:
316 case llvm::Triple::mips64el:
317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
318 return ExprError();
319 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000320 default:
321 break;
322 }
323 }
324
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000325 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000326}
327
Nate Begeman61eecf52010-06-14 05:21:25 +0000328// Get the valid immediate range for the specified NEON type code.
329static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000330 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 return shift ? 63 : (1 << IsQuad) - 1;
343 case NeonTypeFlags::Float16:
344 assert(!shift && "cannot shift float types!");
345 return (4 << IsQuad) - 1;
346 case NeonTypeFlags::Float32:
347 assert(!shift && "cannot shift float types!");
348 return (2 << IsQuad) - 1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000349 case NeonTypeFlags::Float64:
350 assert(!shift && "cannot shift float types!");
351 return (1 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000352 }
David Blaikie7530c032012-01-17 06:56:22 +0000353 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000354}
355
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000356/// getNeonEltType - Return the QualType corresponding to the elements of
357/// the vector type specified by the NeonTypeFlags. This is used to check
358/// the pointer arguments for Neon load/store intrinsics.
359static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
360 switch (Flags.getEltType()) {
361 case NeonTypeFlags::Int8:
362 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
363 case NeonTypeFlags::Int16:
364 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
365 case NeonTypeFlags::Int32:
366 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
367 case NeonTypeFlags::Int64:
368 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
369 case NeonTypeFlags::Poly8:
370 return Context.SignedCharTy;
371 case NeonTypeFlags::Poly16:
372 return Context.ShortTy;
373 case NeonTypeFlags::Float16:
374 return Context.UnsignedShortTy;
375 case NeonTypeFlags::Float32:
376 return Context.FloatTy;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000377 case NeonTypeFlags::Float64:
378 return Context.DoubleTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000379 }
David Blaikie7530c032012-01-17 06:56:22 +0000380 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000381}
382
Tim Northoverb793f0d2013-08-01 09:23:19 +0000383bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
384 CallExpr *TheCall) {
385
386 llvm::APSInt Result;
387
388 uint64_t mask = 0;
389 unsigned TV = 0;
390 int PtrArgNum = -1;
391 bool HasConstPtr = false;
392 switch (BuiltinID) {
393#define GET_NEON_AARCH64_OVERLOAD_CHECK
394#include "clang/Basic/arm_neon.inc"
395#undef GET_NEON_AARCH64_OVERLOAD_CHECK
396 }
397
398 // For NEON intrinsics which are overloaded on vector element type, validate
399 // the immediate which specifies which variant to emit.
400 unsigned ImmArg = TheCall->getNumArgs() - 1;
401 if (mask) {
402 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
403 return true;
404
405 TV = Result.getLimitedValue(64);
406 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
407 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
408 << TheCall->getArg(ImmArg)->getSourceRange();
409 }
410
411 if (PtrArgNum >= 0) {
412 // Check that pointer arguments have the specified type.
413 Expr *Arg = TheCall->getArg(PtrArgNum);
414 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
415 Arg = ICE->getSubExpr();
416 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
417 QualType RHSTy = RHS.get()->getType();
418 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
419 if (HasConstPtr)
420 EltTy = EltTy.withConst();
421 QualType LHSTy = Context.getPointerType(EltTy);
422 AssignConvertType ConvTy;
423 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
424 if (RHS.isInvalid())
425 return true;
426 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
427 RHS.get(), AA_Assigning))
428 return true;
429 }
430
431 // For NEON intrinsics which take an immediate value as part of the
432 // instruction, range check them here.
433 unsigned i = 0, l = 0, u = 0;
434 switch (BuiltinID) {
435 default:
436 return false;
437#define GET_NEON_AARCH64_IMMEDIATE_CHECK
438#include "clang/Basic/arm_neon.inc"
439#undef GET_NEON_AARCH64_IMMEDIATE_CHECK
440 }
441 ;
442
443 // We can't check the value of a dependent argument.
444 if (TheCall->getArg(i)->isTypeDependent() ||
445 TheCall->getArg(i)->isValueDependent())
446 return false;
447
448 // Check that the immediate argument is actually a constant.
449 if (SemaBuiltinConstantArg(TheCall, i, Result))
450 return true;
451
452 // Range check against the upper/lower values for this isntruction.
453 unsigned Val = Result.getZExtValue();
454 if (Val < l || Val > (u + l))
455 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
456 << l << u + l << TheCall->getArg(i)->getSourceRange();
457
458 return false;
459}
460
Tim Northover09df2b02013-07-16 09:47:53 +0000461bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
462 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
463 BuiltinID == ARM::BI__builtin_arm_strex) &&
464 "unexpected ARM builtin");
465 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
466
467 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
468
469 // Ensure that we have the proper number of arguments.
470 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
471 return true;
472
473 // Inspect the pointer argument of the atomic builtin. This should always be
474 // a pointer type, whose element is an integral scalar or pointer type.
475 // Because it is a pointer type, we don't have to worry about any implicit
476 // casts here.
477 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
478 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
479 if (PointerArgRes.isInvalid())
480 return true;
481 PointerArg = PointerArgRes.take();
482
483 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
484 if (!pointerType) {
485 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
486 << PointerArg->getType() << PointerArg->getSourceRange();
487 return true;
488 }
489
490 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
491 // task is to insert the appropriate casts into the AST. First work out just
492 // what the appropriate type is.
493 QualType ValType = pointerType->getPointeeType();
494 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
495 if (IsLdrex)
496 AddrType.addConst();
497
498 // Issue a warning if the cast is dodgy.
499 CastKind CastNeeded = CK_NoOp;
500 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
501 CastNeeded = CK_BitCast;
502 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
503 << PointerArg->getType()
504 << Context.getPointerType(AddrType)
505 << AA_Passing << PointerArg->getSourceRange();
506 }
507
508 // Finally, do the cast and replace the argument with the corrected version.
509 AddrType = Context.getPointerType(AddrType);
510 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
511 if (PointerArgRes.isInvalid())
512 return true;
513 PointerArg = PointerArgRes.take();
514
515 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
516
517 // In general, we allow ints, floats and pointers to be loaded and stored.
518 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
519 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
520 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
521 << PointerArg->getType() << PointerArg->getSourceRange();
522 return true;
523 }
524
525 // But ARM doesn't have instructions to deal with 128-bit versions.
526 if (Context.getTypeSize(ValType) > 64) {
527 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
528 << PointerArg->getType() << PointerArg->getSourceRange();
529 return true;
530 }
531
532 switch (ValType.getObjCLifetime()) {
533 case Qualifiers::OCL_None:
534 case Qualifiers::OCL_ExplicitNone:
535 // okay
536 break;
537
538 case Qualifiers::OCL_Weak:
539 case Qualifiers::OCL_Strong:
540 case Qualifiers::OCL_Autoreleasing:
541 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
542 << ValType << PointerArg->getSourceRange();
543 return true;
544 }
545
546
547 if (IsLdrex) {
548 TheCall->setType(ValType);
549 return false;
550 }
551
552 // Initialize the argument to be stored.
553 ExprResult ValArg = TheCall->getArg(0);
554 InitializedEntity Entity = InitializedEntity::InitializeParameter(
555 Context, ValType, /*consume*/ false);
556 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
557 if (ValArg.isInvalid())
558 return true;
Tim Northover09df2b02013-07-16 09:47:53 +0000559 TheCall->setArg(0, ValArg.get());
Tim Northovera6306fc2013-10-29 12:32:58 +0000560
561 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
562 // but the custom checker bypasses all default analysis.
563 TheCall->setType(Context.IntTy);
Tim Northover09df2b02013-07-16 09:47:53 +0000564 return false;
565}
566
Nate Begeman26a31422010-06-08 02:47:44 +0000567bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000568 llvm::APSInt Result;
569
Tim Northover09df2b02013-07-16 09:47:53 +0000570 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
571 BuiltinID == ARM::BI__builtin_arm_strex) {
572 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
573 }
574
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000575 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000576 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000577 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000578 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000579 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000580#define GET_NEON_OVERLOAD_CHECK
581#include "clang/Basic/arm_neon.inc"
582#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000583 }
584
Nate Begeman0d15c532010-06-13 04:47:52 +0000585 // For NEON intrinsics which are overloaded on vector element type, validate
586 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000587 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000588 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000589 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000590 return true;
591
Bob Wilsonda95f732011-11-08 01:16:11 +0000592 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000593 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000594 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000595 << TheCall->getArg(ImmArg)->getSourceRange();
596 }
597
Bob Wilson46482552011-11-16 21:32:23 +0000598 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000599 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000600 Expr *Arg = TheCall->getArg(PtrArgNum);
601 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
602 Arg = ICE->getSubExpr();
603 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
604 QualType RHSTy = RHS.get()->getType();
605 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
606 if (HasConstPtr)
607 EltTy = EltTy.withConst();
608 QualType LHSTy = Context.getPointerType(EltTy);
609 AssignConvertType ConvTy;
610 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
611 if (RHS.isInvalid())
612 return true;
613 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
614 RHS.get(), AA_Assigning))
615 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000616 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000617
Nate Begeman0d15c532010-06-13 04:47:52 +0000618 // For NEON intrinsics which take an immediate value as part of the
619 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000620 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000621 switch (BuiltinID) {
622 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000623 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
624 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000625 case ARM::BI__builtin_arm_vcvtr_f:
626 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000627#define GET_NEON_IMMEDIATE_CHECK
628#include "clang/Basic/arm_neon.inc"
629#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000630 };
631
Douglas Gregor592a4232012-06-29 01:05:22 +0000632 // We can't check the value of a dependent argument.
633 if (TheCall->getArg(i)->isTypeDependent() ||
634 TheCall->getArg(i)->isValueDependent())
635 return false;
636
Nate Begeman61eecf52010-06-14 05:21:25 +0000637 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000638 if (SemaBuiltinConstantArg(TheCall, i, Result))
639 return true;
640
Nate Begeman61eecf52010-06-14 05:21:25 +0000641 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000642 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000643 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000644 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000645 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000646
Nate Begeman99c40bb2010-08-03 21:32:34 +0000647 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000648 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000649}
Daniel Dunbarde454282008-10-02 18:44:07 +0000650
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000651bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
652 unsigned i = 0, l = 0, u = 0;
653 switch (BuiltinID) {
654 default: return false;
655 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
656 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000657 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
658 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
659 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
660 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
661 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000662 };
663
664 // We can't check the value of a dependent argument.
665 if (TheCall->getArg(i)->isTypeDependent() ||
666 TheCall->getArg(i)->isValueDependent())
667 return false;
668
669 // Check that the immediate argument is actually a constant.
670 llvm::APSInt Result;
671 if (SemaBuiltinConstantArg(TheCall, i, Result))
672 return true;
673
674 // Range check against the upper/lower values for this instruction.
675 unsigned Val = Result.getZExtValue();
676 if (Val < l || Val > u)
677 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
678 << l << u << TheCall->getArg(i)->getSourceRange();
679
680 return false;
681}
682
Richard Smith831421f2012-06-25 20:30:08 +0000683/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
684/// parameter with the FormatAttr's correct format_idx and firstDataArg.
685/// Returns true when the format fits the function and the FormatStringInfo has
686/// been populated.
687bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
688 FormatStringInfo *FSI) {
689 FSI->HasVAListArg = Format->getFirstArg() == 0;
690 FSI->FormatIdx = Format->getFormatIdx() - 1;
691 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000692
Richard Smith831421f2012-06-25 20:30:08 +0000693 // The way the format attribute works in GCC, the implicit this argument
694 // of member functions is counted. However, it doesn't appear in our own
695 // lists, so decrement format_idx in that case.
696 if (IsCXXMember) {
697 if(FSI->FormatIdx == 0)
698 return false;
699 --FSI->FormatIdx;
700 if (FSI->FirstDataArg != 0)
701 --FSI->FirstDataArg;
702 }
703 return true;
704}
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Richard Smith831421f2012-06-25 20:30:08 +0000706/// Handles the checks for format strings, non-POD arguments to vararg
707/// functions, and NULL arguments passed to non-NULL parameters.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000708void Sema::checkCall(NamedDecl *FDecl,
709 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000710 unsigned NumProtoArgs,
711 bool IsMemberFunction,
712 SourceLocation Loc,
713 SourceRange Range,
714 VariadicCallType CallType) {
Richard Smith0e218972013-08-05 18:49:43 +0000715 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +0000716 if (CurContext->isDependentContext())
717 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000718
Ted Kremenekc82faca2010-09-09 04:33:05 +0000719 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +0000720 llvm::SmallBitVector CheckedVarArgs;
721 if (FDecl) {
Richard Trieu0538f0e2013-06-22 00:20:41 +0000722 for (specific_attr_iterator<FormatAttr>
Benjamin Kramer47abb252013-08-08 11:08:26 +0000723 I = FDecl->specific_attr_begin<FormatAttr>(),
724 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000725 I != E; ++I) {
726 // Only create vector if there are format attributes.
727 CheckedVarArgs.resize(Args.size());
728
Benjamin Kramer47abb252013-08-08 11:08:26 +0000729 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
730 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000731 }
Richard Smith0e218972013-08-05 18:49:43 +0000732 }
Richard Smith831421f2012-06-25 20:30:08 +0000733
734 // Refuse POD arguments that weren't caught by the format string
735 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +0000736 if (CallType != VariadicDoesNotApply) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000737 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000738 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +0000739 if (const Expr *Arg = Args[ArgIdx]) {
740 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
741 checkVariadicArgument(Arg, CallType);
742 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000743 }
Richard Smith0e218972013-08-05 18:49:43 +0000744 }
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Richard Trieu0538f0e2013-06-22 00:20:41 +0000746 if (FDecl) {
747 for (specific_attr_iterator<NonNullAttr>
748 I = FDecl->specific_attr_begin<NonNullAttr>(),
749 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
750 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000751
Richard Trieu0538f0e2013-06-22 00:20:41 +0000752 // Type safety checking.
753 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
754 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
755 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
756 i != e; ++i) {
757 CheckArgumentWithTypeTag(*i, Args.data());
758 }
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000759 }
Richard Smith831421f2012-06-25 20:30:08 +0000760}
761
762/// CheckConstructorCall - Check a constructor call for correctness and safety
763/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000764void Sema::CheckConstructorCall(FunctionDecl *FDecl,
765 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000766 const FunctionProtoType *Proto,
767 SourceLocation Loc) {
768 VariadicCallType CallType =
769 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000770 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000771 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
772}
773
774/// CheckFunctionCall - Check a direct function call for various correctness
775/// and safety properties not strictly enforced by the C type system.
776bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
777 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000778 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
779 isa<CXXMethodDecl>(FDecl);
780 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
781 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000782 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
783 TheCall->getCallee());
784 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000785 Expr** Args = TheCall->getArgs();
786 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000787 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000788 // If this is a call to a member operator, hide the first argument
789 // from checkCall.
790 // FIXME: Our choice of AST representation here is less than ideal.
791 ++Args;
792 --NumArgs;
793 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000794 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
795 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000796 IsMemberFunction, TheCall->getRParenLoc(),
797 TheCall->getCallee()->getSourceRange(), CallType);
798
799 IdentifierInfo *FnInfo = FDecl->getIdentifier();
800 // None of the checks below are needed for functions that don't have
801 // simple names (e.g., C++ conversion functions).
802 if (!FnInfo)
803 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000804
Anna Zaks0a151a12012-01-17 00:37:07 +0000805 unsigned CMId = FDecl->getMemoryFunctionKind();
806 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000807 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000808
Anna Zaksd9b859a2012-01-13 21:52:01 +0000809 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000810 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000811 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000812 else if (CMId == Builtin::BIstrncat)
813 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000814 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000815 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000816
Anders Carlssond406bf02009-08-16 01:56:34 +0000817 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000818}
819
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000820bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000821 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000822 VariadicCallType CallType =
823 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000824
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000825 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000826 /*IsMemberFunction=*/false,
827 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000828
829 return false;
830}
831
Richard Trieuf462b012013-06-20 21:03:13 +0000832bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
833 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000834 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
835 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000836 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000838 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000839 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000840 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Richard Trieuf462b012013-06-20 21:03:13 +0000842 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000843 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000844 CallType = VariadicDoesNotApply;
845 } else if (Ty->isBlockPointerType()) {
846 CallType = VariadicBlock;
847 } else { // Ty->isFunctionPointerType()
848 CallType = VariadicFunction;
849 }
Richard Smith831421f2012-06-25 20:30:08 +0000850 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000851
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000852 checkCall(NDecl,
853 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
854 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000855 NumProtoArgs, /*IsMemberFunction=*/false,
856 TheCall->getRParenLoc(),
857 TheCall->getCallee()->getSourceRange(), CallType);
858
Anders Carlssond406bf02009-08-16 01:56:34 +0000859 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000860}
861
Richard Trieu0538f0e2013-06-22 00:20:41 +0000862/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
863/// such as function pointers returned from functions.
864bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
865 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
866 TheCall->getCallee());
867 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
868
869 checkCall(/*FDecl=*/0,
870 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
871 TheCall->getNumArgs()),
872 NumProtoArgs, /*IsMemberFunction=*/false,
873 TheCall->getRParenLoc(),
874 TheCall->getCallee()->getSourceRange(), CallType);
875
876 return false;
877}
878
Richard Smithff34d402012-04-12 05:08:17 +0000879ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
880 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000881 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
882 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000883
Richard Smithff34d402012-04-12 05:08:17 +0000884 // All these operations take one of the following forms:
885 enum {
886 // C __c11_atomic_init(A *, C)
887 Init,
888 // C __c11_atomic_load(A *, int)
889 Load,
890 // void __atomic_load(A *, CP, int)
891 Copy,
892 // C __c11_atomic_add(A *, M, int)
893 Arithmetic,
894 // C __atomic_exchange_n(A *, CP, int)
895 Xchg,
896 // void __atomic_exchange(A *, C *, CP, int)
897 GNUXchg,
898 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
899 C11CmpXchg,
900 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
901 GNUCmpXchg
902 } Form = Init;
903 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
904 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
905 // where:
906 // C is an appropriate type,
907 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
908 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
909 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
910 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000911
Richard Smithff34d402012-04-12 05:08:17 +0000912 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
913 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
914 && "need to update code for modified C11 atomics");
915 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
916 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
917 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
918 Op == AtomicExpr::AO__atomic_store_n ||
919 Op == AtomicExpr::AO__atomic_exchange_n ||
920 Op == AtomicExpr::AO__atomic_compare_exchange_n;
921 bool IsAddSub = false;
922
923 switch (Op) {
924 case AtomicExpr::AO__c11_atomic_init:
925 Form = Init;
926 break;
927
928 case AtomicExpr::AO__c11_atomic_load:
929 case AtomicExpr::AO__atomic_load_n:
930 Form = Load;
931 break;
932
933 case AtomicExpr::AO__c11_atomic_store:
934 case AtomicExpr::AO__atomic_load:
935 case AtomicExpr::AO__atomic_store:
936 case AtomicExpr::AO__atomic_store_n:
937 Form = Copy;
938 break;
939
940 case AtomicExpr::AO__c11_atomic_fetch_add:
941 case AtomicExpr::AO__c11_atomic_fetch_sub:
942 case AtomicExpr::AO__atomic_fetch_add:
943 case AtomicExpr::AO__atomic_fetch_sub:
944 case AtomicExpr::AO__atomic_add_fetch:
945 case AtomicExpr::AO__atomic_sub_fetch:
946 IsAddSub = true;
947 // Fall through.
948 case AtomicExpr::AO__c11_atomic_fetch_and:
949 case AtomicExpr::AO__c11_atomic_fetch_or:
950 case AtomicExpr::AO__c11_atomic_fetch_xor:
951 case AtomicExpr::AO__atomic_fetch_and:
952 case AtomicExpr::AO__atomic_fetch_or:
953 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000954 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000955 case AtomicExpr::AO__atomic_and_fetch:
956 case AtomicExpr::AO__atomic_or_fetch:
957 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000958 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000959 Form = Arithmetic;
960 break;
961
962 case AtomicExpr::AO__c11_atomic_exchange:
963 case AtomicExpr::AO__atomic_exchange_n:
964 Form = Xchg;
965 break;
966
967 case AtomicExpr::AO__atomic_exchange:
968 Form = GNUXchg;
969 break;
970
971 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
972 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
973 Form = C11CmpXchg;
974 break;
975
976 case AtomicExpr::AO__atomic_compare_exchange:
977 case AtomicExpr::AO__atomic_compare_exchange_n:
978 Form = GNUCmpXchg;
979 break;
980 }
981
982 // Check we have the right number of arguments.
983 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000984 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000985 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000986 << TheCall->getCallee()->getSourceRange();
987 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000988 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
989 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000990 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000991 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000992 << TheCall->getCallee()->getSourceRange();
993 return ExprError();
994 }
995
Richard Smithff34d402012-04-12 05:08:17 +0000996 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000997 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000998 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
999 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1000 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +00001001 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +00001002 << Ptr->getType() << Ptr->getSourceRange();
1003 return ExprError();
1004 }
1005
Richard Smithff34d402012-04-12 05:08:17 +00001006 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1007 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1008 QualType ValType = AtomTy; // 'C'
1009 if (IsC11) {
1010 if (!AtomTy->isAtomicType()) {
1011 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1012 << Ptr->getType() << Ptr->getSourceRange();
1013 return ExprError();
1014 }
Richard Smithbc57b102012-09-15 06:09:58 +00001015 if (AtomTy.isConstQualified()) {
1016 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1017 << Ptr->getType() << Ptr->getSourceRange();
1018 return ExprError();
1019 }
Richard Smithff34d402012-04-12 05:08:17 +00001020 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001021 }
Eli Friedman276b0612011-10-11 02:20:01 +00001022
Richard Smithff34d402012-04-12 05:08:17 +00001023 // For an arithmetic operation, the implied arithmetic must be well-formed.
1024 if (Form == Arithmetic) {
1025 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1026 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1027 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1028 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1029 return ExprError();
1030 }
1031 if (!IsAddSub && !ValType->isIntegerType()) {
1032 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1033 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1034 return ExprError();
1035 }
1036 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1037 // For __atomic_*_n operations, the value type must be a scalar integral or
1038 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001039 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001040 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1041 return ExprError();
1042 }
1043
Eli Friedmana3d727b2013-09-11 03:49:34 +00001044 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1045 !AtomTy->isScalarType()) {
Richard Smithff34d402012-04-12 05:08:17 +00001046 // For GNU atomics, require a trivially-copyable type. This is not part of
1047 // the GNU atomics specification, but we enforce it for sanity.
1048 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001049 << Ptr->getType() << Ptr->getSourceRange();
1050 return ExprError();
1051 }
1052
Richard Smithff34d402012-04-12 05:08:17 +00001053 // FIXME: For any builtin other than a load, the ValType must not be
1054 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001055
1056 switch (ValType.getObjCLifetime()) {
1057 case Qualifiers::OCL_None:
1058 case Qualifiers::OCL_ExplicitNone:
1059 // okay
1060 break;
1061
1062 case Qualifiers::OCL_Weak:
1063 case Qualifiers::OCL_Strong:
1064 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001065 // FIXME: Can this happen? By this point, ValType should be known
1066 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001067 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1068 << ValType << Ptr->getSourceRange();
1069 return ExprError();
1070 }
1071
1072 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001073 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001074 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001075 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001076 ResultType = Context.BoolTy;
1077
Richard Smithff34d402012-04-12 05:08:17 +00001078 // The type of a parameter passed 'by value'. In the GNU atomics, such
1079 // arguments are actually passed as pointers.
1080 QualType ByValType = ValType; // 'CP'
1081 if (!IsC11 && !IsN)
1082 ByValType = Ptr->getType();
1083
Eli Friedman276b0612011-10-11 02:20:01 +00001084 // The first argument --- the pointer --- has a fixed type; we
1085 // deduce the types of the rest of the arguments accordingly. Walk
1086 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001087 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001088 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001089 if (i < NumVals[Form] + 1) {
1090 switch (i) {
1091 case 1:
1092 // The second argument is the non-atomic operand. For arithmetic, this
1093 // is always passed by value, and for a compare_exchange it is always
1094 // passed by address. For the rest, GNU uses by-address and C11 uses
1095 // by-value.
1096 assert(Form != Load);
1097 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1098 Ty = ValType;
1099 else if (Form == Copy || Form == Xchg)
1100 Ty = ByValType;
1101 else if (Form == Arithmetic)
1102 Ty = Context.getPointerDiffType();
1103 else
1104 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1105 break;
1106 case 2:
1107 // The third argument to compare_exchange / GNU exchange is a
1108 // (pointer to a) desired value.
1109 Ty = ByValType;
1110 break;
1111 case 3:
1112 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1113 Ty = Context.BoolTy;
1114 break;
1115 }
Eli Friedman276b0612011-10-11 02:20:01 +00001116 } else {
1117 // The order(s) are always converted to int.
1118 Ty = Context.IntTy;
1119 }
Richard Smithff34d402012-04-12 05:08:17 +00001120
Eli Friedman276b0612011-10-11 02:20:01 +00001121 InitializedEntity Entity =
1122 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001123 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001124 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1125 if (Arg.isInvalid())
1126 return true;
1127 TheCall->setArg(i, Arg.get());
1128 }
1129
Richard Smithff34d402012-04-12 05:08:17 +00001130 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001131 SmallVector<Expr*, 5> SubExprs;
1132 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001133 switch (Form) {
1134 case Init:
1135 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001136 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001137 break;
1138 case Load:
1139 SubExprs.push_back(TheCall->getArg(1)); // Order
1140 break;
1141 case Copy:
1142 case Arithmetic:
1143 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001144 SubExprs.push_back(TheCall->getArg(2)); // Order
1145 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001146 break;
1147 case GNUXchg:
1148 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1149 SubExprs.push_back(TheCall->getArg(3)); // Order
1150 SubExprs.push_back(TheCall->getArg(1)); // Val1
1151 SubExprs.push_back(TheCall->getArg(2)); // Val2
1152 break;
1153 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001154 SubExprs.push_back(TheCall->getArg(3)); // Order
1155 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001156 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001157 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001158 break;
1159 case GNUCmpXchg:
1160 SubExprs.push_back(TheCall->getArg(4)); // Order
1161 SubExprs.push_back(TheCall->getArg(1)); // Val1
1162 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1163 SubExprs.push_back(TheCall->getArg(2)); // Val2
1164 SubExprs.push_back(TheCall->getArg(3)); // Weak
1165 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001166 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001167
1168 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1169 SubExprs, ResultType, Op,
1170 TheCall->getRParenLoc());
1171
1172 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1173 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1174 Context.AtomicUsesUnsupportedLibcall(AE))
1175 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1176 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001177
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001178 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +00001179}
1180
1181
John McCall5f8d6042011-08-27 01:09:30 +00001182/// checkBuiltinArgument - Given a call to a builtin function, perform
1183/// normal type-checking on the given argument, updating the call in
1184/// place. This is useful when a builtin function requires custom
1185/// type-checking for some of its arguments but not necessarily all of
1186/// them.
1187///
1188/// Returns true on error.
1189static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1190 FunctionDecl *Fn = E->getDirectCallee();
1191 assert(Fn && "builtin call without direct callee!");
1192
1193 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1194 InitializedEntity Entity =
1195 InitializedEntity::InitializeParameter(S.Context, Param);
1196
1197 ExprResult Arg = E->getArg(0);
1198 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1199 if (Arg.isInvalid())
1200 return true;
1201
1202 E->setArg(ArgIndex, Arg.take());
1203 return false;
1204}
1205
Chris Lattner5caa3702009-05-08 06:58:22 +00001206/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1207/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1208/// type of its first argument. The main ActOnCallExpr routines have already
1209/// promoted the types of arguments because all of these calls are prototyped as
1210/// void(...).
1211///
1212/// This function goes through and does final semantic checking for these
1213/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001214ExprResult
1215Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001216 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001217 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1218 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1219
1220 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001221 if (TheCall->getNumArgs() < 1) {
1222 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1223 << 0 << 1 << TheCall->getNumArgs()
1224 << TheCall->getCallee()->getSourceRange();
1225 return ExprError();
1226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Chris Lattner5caa3702009-05-08 06:58:22 +00001228 // Inspect the first argument of the atomic builtin. This should always be
1229 // a pointer type, whose element is an integral scalar or pointer type.
1230 // Because it is a pointer type, we don't have to worry about any implicit
1231 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001232 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001233 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001234 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1235 if (FirstArgResult.isInvalid())
1236 return ExprError();
1237 FirstArg = FirstArgResult.take();
1238 TheCall->setArg(0, FirstArg);
1239
John McCallf85e1932011-06-15 23:02:42 +00001240 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1241 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001242 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1243 << FirstArg->getType() << FirstArg->getSourceRange();
1244 return ExprError();
1245 }
Mike Stump1eb44332009-09-09 15:08:12 +00001246
John McCallf85e1932011-06-15 23:02:42 +00001247 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001248 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001249 !ValType->isBlockPointerType()) {
1250 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1251 << FirstArg->getType() << FirstArg->getSourceRange();
1252 return ExprError();
1253 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001254
John McCallf85e1932011-06-15 23:02:42 +00001255 switch (ValType.getObjCLifetime()) {
1256 case Qualifiers::OCL_None:
1257 case Qualifiers::OCL_ExplicitNone:
1258 // okay
1259 break;
1260
1261 case Qualifiers::OCL_Weak:
1262 case Qualifiers::OCL_Strong:
1263 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001264 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001265 << ValType << FirstArg->getSourceRange();
1266 return ExprError();
1267 }
1268
John McCallb45ae252011-10-05 07:41:44 +00001269 // Strip any qualifiers off ValType.
1270 ValType = ValType.getUnqualifiedType();
1271
Chandler Carruth8d13d222010-07-18 20:54:12 +00001272 // The majority of builtins return a value, but a few have special return
1273 // types, so allow them to override appropriately below.
1274 QualType ResultType = ValType;
1275
Chris Lattner5caa3702009-05-08 06:58:22 +00001276 // We need to figure out which concrete builtin this maps onto. For example,
1277 // __sync_fetch_and_add with a 2 byte object turns into
1278 // __sync_fetch_and_add_2.
1279#define BUILTIN_ROW(x) \
1280 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1281 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Chris Lattner5caa3702009-05-08 06:58:22 +00001283 static const unsigned BuiltinIndices[][5] = {
1284 BUILTIN_ROW(__sync_fetch_and_add),
1285 BUILTIN_ROW(__sync_fetch_and_sub),
1286 BUILTIN_ROW(__sync_fetch_and_or),
1287 BUILTIN_ROW(__sync_fetch_and_and),
1288 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Chris Lattner5caa3702009-05-08 06:58:22 +00001290 BUILTIN_ROW(__sync_add_and_fetch),
1291 BUILTIN_ROW(__sync_sub_and_fetch),
1292 BUILTIN_ROW(__sync_and_and_fetch),
1293 BUILTIN_ROW(__sync_or_and_fetch),
1294 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Chris Lattner5caa3702009-05-08 06:58:22 +00001296 BUILTIN_ROW(__sync_val_compare_and_swap),
1297 BUILTIN_ROW(__sync_bool_compare_and_swap),
1298 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001299 BUILTIN_ROW(__sync_lock_release),
1300 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001301 };
Mike Stump1eb44332009-09-09 15:08:12 +00001302#undef BUILTIN_ROW
1303
Chris Lattner5caa3702009-05-08 06:58:22 +00001304 // Determine the index of the size.
1305 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001306 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001307 case 1: SizeIndex = 0; break;
1308 case 2: SizeIndex = 1; break;
1309 case 4: SizeIndex = 2; break;
1310 case 8: SizeIndex = 3; break;
1311 case 16: SizeIndex = 4; break;
1312 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001313 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1314 << FirstArg->getType() << FirstArg->getSourceRange();
1315 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001316 }
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Chris Lattner5caa3702009-05-08 06:58:22 +00001318 // Each of these builtins has one pointer argument, followed by some number of
1319 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1320 // that we ignore. Find out which row of BuiltinIndices to read from as well
1321 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001322 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001323 unsigned BuiltinIndex, NumFixed = 1;
1324 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001325 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001326 case Builtin::BI__sync_fetch_and_add:
1327 case Builtin::BI__sync_fetch_and_add_1:
1328 case Builtin::BI__sync_fetch_and_add_2:
1329 case Builtin::BI__sync_fetch_and_add_4:
1330 case Builtin::BI__sync_fetch_and_add_8:
1331 case Builtin::BI__sync_fetch_and_add_16:
1332 BuiltinIndex = 0;
1333 break;
1334
1335 case Builtin::BI__sync_fetch_and_sub:
1336 case Builtin::BI__sync_fetch_and_sub_1:
1337 case Builtin::BI__sync_fetch_and_sub_2:
1338 case Builtin::BI__sync_fetch_and_sub_4:
1339 case Builtin::BI__sync_fetch_and_sub_8:
1340 case Builtin::BI__sync_fetch_and_sub_16:
1341 BuiltinIndex = 1;
1342 break;
1343
1344 case Builtin::BI__sync_fetch_and_or:
1345 case Builtin::BI__sync_fetch_and_or_1:
1346 case Builtin::BI__sync_fetch_and_or_2:
1347 case Builtin::BI__sync_fetch_and_or_4:
1348 case Builtin::BI__sync_fetch_and_or_8:
1349 case Builtin::BI__sync_fetch_and_or_16:
1350 BuiltinIndex = 2;
1351 break;
1352
1353 case Builtin::BI__sync_fetch_and_and:
1354 case Builtin::BI__sync_fetch_and_and_1:
1355 case Builtin::BI__sync_fetch_and_and_2:
1356 case Builtin::BI__sync_fetch_and_and_4:
1357 case Builtin::BI__sync_fetch_and_and_8:
1358 case Builtin::BI__sync_fetch_and_and_16:
1359 BuiltinIndex = 3;
1360 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Douglas Gregora9766412011-11-28 16:30:08 +00001362 case Builtin::BI__sync_fetch_and_xor:
1363 case Builtin::BI__sync_fetch_and_xor_1:
1364 case Builtin::BI__sync_fetch_and_xor_2:
1365 case Builtin::BI__sync_fetch_and_xor_4:
1366 case Builtin::BI__sync_fetch_and_xor_8:
1367 case Builtin::BI__sync_fetch_and_xor_16:
1368 BuiltinIndex = 4;
1369 break;
1370
1371 case Builtin::BI__sync_add_and_fetch:
1372 case Builtin::BI__sync_add_and_fetch_1:
1373 case Builtin::BI__sync_add_and_fetch_2:
1374 case Builtin::BI__sync_add_and_fetch_4:
1375 case Builtin::BI__sync_add_and_fetch_8:
1376 case Builtin::BI__sync_add_and_fetch_16:
1377 BuiltinIndex = 5;
1378 break;
1379
1380 case Builtin::BI__sync_sub_and_fetch:
1381 case Builtin::BI__sync_sub_and_fetch_1:
1382 case Builtin::BI__sync_sub_and_fetch_2:
1383 case Builtin::BI__sync_sub_and_fetch_4:
1384 case Builtin::BI__sync_sub_and_fetch_8:
1385 case Builtin::BI__sync_sub_and_fetch_16:
1386 BuiltinIndex = 6;
1387 break;
1388
1389 case Builtin::BI__sync_and_and_fetch:
1390 case Builtin::BI__sync_and_and_fetch_1:
1391 case Builtin::BI__sync_and_and_fetch_2:
1392 case Builtin::BI__sync_and_and_fetch_4:
1393 case Builtin::BI__sync_and_and_fetch_8:
1394 case Builtin::BI__sync_and_and_fetch_16:
1395 BuiltinIndex = 7;
1396 break;
1397
1398 case Builtin::BI__sync_or_and_fetch:
1399 case Builtin::BI__sync_or_and_fetch_1:
1400 case Builtin::BI__sync_or_and_fetch_2:
1401 case Builtin::BI__sync_or_and_fetch_4:
1402 case Builtin::BI__sync_or_and_fetch_8:
1403 case Builtin::BI__sync_or_and_fetch_16:
1404 BuiltinIndex = 8;
1405 break;
1406
1407 case Builtin::BI__sync_xor_and_fetch:
1408 case Builtin::BI__sync_xor_and_fetch_1:
1409 case Builtin::BI__sync_xor_and_fetch_2:
1410 case Builtin::BI__sync_xor_and_fetch_4:
1411 case Builtin::BI__sync_xor_and_fetch_8:
1412 case Builtin::BI__sync_xor_and_fetch_16:
1413 BuiltinIndex = 9;
1414 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Chris Lattner5caa3702009-05-08 06:58:22 +00001416 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001417 case Builtin::BI__sync_val_compare_and_swap_1:
1418 case Builtin::BI__sync_val_compare_and_swap_2:
1419 case Builtin::BI__sync_val_compare_and_swap_4:
1420 case Builtin::BI__sync_val_compare_and_swap_8:
1421 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001422 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001423 NumFixed = 2;
1424 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001425
Chris Lattner5caa3702009-05-08 06:58:22 +00001426 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001427 case Builtin::BI__sync_bool_compare_and_swap_1:
1428 case Builtin::BI__sync_bool_compare_and_swap_2:
1429 case Builtin::BI__sync_bool_compare_and_swap_4:
1430 case Builtin::BI__sync_bool_compare_and_swap_8:
1431 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001432 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001433 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001434 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001435 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001436
1437 case Builtin::BI__sync_lock_test_and_set:
1438 case Builtin::BI__sync_lock_test_and_set_1:
1439 case Builtin::BI__sync_lock_test_and_set_2:
1440 case Builtin::BI__sync_lock_test_and_set_4:
1441 case Builtin::BI__sync_lock_test_and_set_8:
1442 case Builtin::BI__sync_lock_test_and_set_16:
1443 BuiltinIndex = 12;
1444 break;
1445
Chris Lattner5caa3702009-05-08 06:58:22 +00001446 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001447 case Builtin::BI__sync_lock_release_1:
1448 case Builtin::BI__sync_lock_release_2:
1449 case Builtin::BI__sync_lock_release_4:
1450 case Builtin::BI__sync_lock_release_8:
1451 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001452 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001453 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001454 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001455 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001456
1457 case Builtin::BI__sync_swap:
1458 case Builtin::BI__sync_swap_1:
1459 case Builtin::BI__sync_swap_2:
1460 case Builtin::BI__sync_swap_4:
1461 case Builtin::BI__sync_swap_8:
1462 case Builtin::BI__sync_swap_16:
1463 BuiltinIndex = 14;
1464 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001465 }
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Chris Lattner5caa3702009-05-08 06:58:22 +00001467 // Now that we know how many fixed arguments we expect, first check that we
1468 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001469 if (TheCall->getNumArgs() < 1+NumFixed) {
1470 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1471 << 0 << 1+NumFixed << TheCall->getNumArgs()
1472 << TheCall->getCallee()->getSourceRange();
1473 return ExprError();
1474 }
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001476 // Get the decl for the concrete builtin from this, we can tell what the
1477 // concrete integer type we should convert to is.
1478 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1479 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001480 FunctionDecl *NewBuiltinDecl;
1481 if (NewBuiltinID == BuiltinID)
1482 NewBuiltinDecl = FDecl;
1483 else {
1484 // Perform builtin lookup to avoid redeclaring it.
1485 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1486 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1487 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1488 assert(Res.getFoundDecl());
1489 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1490 if (NewBuiltinDecl == 0)
1491 return ExprError();
1492 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001493
John McCallf871d0c2010-08-07 06:22:56 +00001494 // The first argument --- the pointer --- has a fixed type; we
1495 // deduce the types of the rest of the arguments accordingly. Walk
1496 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001497 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001498 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Chris Lattner5caa3702009-05-08 06:58:22 +00001500 // GCC does an implicit conversion to the pointer or integer ValType. This
1501 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001502 // Initialize the argument.
1503 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1504 ValType, /*consume*/ false);
1505 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001506 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001507 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Chris Lattner5caa3702009-05-08 06:58:22 +00001509 // Okay, we have something that *can* be converted to the right type. Check
1510 // to see if there is a potentially weird extension going on here. This can
1511 // happen when you do an atomic operation on something like an char* and
1512 // pass in 42. The 42 gets converted to char. This is even more strange
1513 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001514 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001515 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001516 }
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001518 ASTContext& Context = this->getASTContext();
1519
1520 // Create a new DeclRefExpr to refer to the new decl.
1521 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1522 Context,
1523 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001524 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001525 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001526 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001527 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001528 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001529 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Chris Lattner5caa3702009-05-08 06:58:22 +00001531 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001532 // FIXME: This loses syntactic information.
1533 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1534 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1535 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001536 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001538 // Change the result type of the call to match the original value type. This
1539 // is arbitrary, but the codegen for these builtins ins design to handle it
1540 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001541 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001542
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001543 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001544}
1545
Chris Lattner69039812009-02-18 06:01:06 +00001546/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001547/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001548/// Note: It might also make sense to do the UTF-16 conversion here (would
1549/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001550bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001551 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001552 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1553
Douglas Gregor5cee1192011-07-27 05:40:30 +00001554 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001555 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1556 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001557 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001558 }
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001560 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001561 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001562 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001563 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001564 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001565 UTF16 *ToPtr = &ToBuf[0];
1566
1567 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1568 &ToPtr, ToPtr + NumBytes,
1569 strictConversion);
1570 // Check for conversion failure.
1571 if (Result != conversionOK)
1572 Diag(Arg->getLocStart(),
1573 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1574 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001575 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001576}
1577
Chris Lattnerc27c6652007-12-20 00:05:45 +00001578/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1579/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001580bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1581 Expr *Fn = TheCall->getCallee();
1582 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001583 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001584 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001585 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1586 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001587 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001588 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001589 return true;
1590 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001591
1592 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001593 return Diag(TheCall->getLocEnd(),
1594 diag::err_typecheck_call_too_few_args_at_least)
1595 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001596 }
1597
John McCall5f8d6042011-08-27 01:09:30 +00001598 // Type-check the first argument normally.
1599 if (checkBuiltinArgument(*this, TheCall, 0))
1600 return true;
1601
Chris Lattnerc27c6652007-12-20 00:05:45 +00001602 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001603 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001604 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001605 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001606 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001607 else if (FunctionDecl *FD = getCurFunctionDecl())
1608 isVariadic = FD->isVariadic();
1609 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001610 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Chris Lattnerc27c6652007-12-20 00:05:45 +00001612 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001613 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1614 return true;
1615 }
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Chris Lattner30ce3442007-12-19 23:59:04 +00001617 // Verify that the second argument to the builtin is the last argument of the
1618 // current function or method.
1619 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001620 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Nico Weberb07d4482013-05-24 23:31:57 +00001622 // These are valid if SecondArgIsLastNamedArgument is false after the next
1623 // block.
1624 QualType Type;
1625 SourceLocation ParamLoc;
1626
Anders Carlsson88cf2262008-02-11 04:20:54 +00001627 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1628 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001629 // FIXME: This isn't correct for methods (results in bogus warning).
1630 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001631 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001632 if (CurBlock)
1633 LastArg = *(CurBlock->TheDecl->param_end()-1);
1634 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001635 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001636 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001637 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001638 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001639
1640 Type = PV->getType();
1641 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001642 }
1643 }
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Chris Lattner30ce3442007-12-19 23:59:04 +00001645 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001646 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001647 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001648 else if (Type->isReferenceType()) {
1649 Diag(Arg->getLocStart(),
1650 diag::warn_va_start_of_reference_type_is_undefined);
1651 Diag(ParamLoc, diag::note_parameter_type) << Type;
1652 }
1653
Enea Zaffanella54de9bb2013-11-07 08:14:26 +00001654 TheCall->setType(Context.VoidTy);
Chris Lattner30ce3442007-12-19 23:59:04 +00001655 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001656}
Chris Lattner30ce3442007-12-19 23:59:04 +00001657
Chris Lattner1b9a0792007-12-20 00:26:33 +00001658/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1659/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001660bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1661 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001662 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001663 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001664 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001665 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001666 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001667 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001668 << SourceRange(TheCall->getArg(2)->getLocStart(),
1669 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001670
John Wiegley429bb272011-04-08 18:41:53 +00001671 ExprResult OrigArg0 = TheCall->getArg(0);
1672 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001673
Chris Lattner1b9a0792007-12-20 00:26:33 +00001674 // Do standard promotions between the two arguments, returning their common
1675 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001676 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001677 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1678 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001679
1680 // Make sure any conversions are pushed back into the call; this is
1681 // type safe since unordered compare builtins are declared as "_Bool
1682 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001683 TheCall->setArg(0, OrigArg0.get());
1684 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001685
John Wiegley429bb272011-04-08 18:41:53 +00001686 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001687 return false;
1688
Chris Lattner1b9a0792007-12-20 00:26:33 +00001689 // If the common type isn't a real floating type, then the arguments were
1690 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001691 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001692 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001693 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001694 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1695 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Chris Lattner1b9a0792007-12-20 00:26:33 +00001697 return false;
1698}
1699
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001700/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1701/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001702/// to check everything. We expect the last argument to be a floating point
1703/// value.
1704bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1705 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001706 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001707 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001708 if (TheCall->getNumArgs() > NumArgs)
1709 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001710 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001711 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001712 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001713 (*(TheCall->arg_end()-1))->getLocEnd());
1714
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001715 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Eli Friedman9ac6f622009-08-31 20:06:00 +00001717 if (OrigArg->isTypeDependent())
1718 return false;
1719
Chris Lattner81368fb2010-05-06 05:50:07 +00001720 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001721 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001722 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001723 diag::err_typecheck_call_invalid_unary_fp)
1724 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Chris Lattner81368fb2010-05-06 05:50:07 +00001726 // If this is an implicit conversion from float -> double, remove it.
1727 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1728 Expr *CastArg = Cast->getSubExpr();
1729 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1730 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1731 "promotion from float to double is the only expected cast here");
1732 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001733 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001734 }
1735 }
1736
Eli Friedman9ac6f622009-08-31 20:06:00 +00001737 return false;
1738}
1739
Eli Friedmand38617c2008-05-14 19:38:39 +00001740/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1741// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001742ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001743 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001744 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001745 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00001746 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1747 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001748
Nate Begeman37b6a572010-06-08 00:16:34 +00001749 // Determine which of the following types of shufflevector we're checking:
1750 // 1) unary, vector mask: (lhs, mask)
1751 // 2) binary, vector mask: (lhs, rhs, mask)
1752 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1753 QualType resType = TheCall->getArg(0)->getType();
1754 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00001755
Douglas Gregorcde01732009-05-19 22:10:17 +00001756 if (!TheCall->getArg(0)->isTypeDependent() &&
1757 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001758 QualType LHSType = TheCall->getArg(0)->getType();
1759 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00001760
Craig Topperbbe759c2013-07-29 06:47:04 +00001761 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1762 return ExprError(Diag(TheCall->getLocStart(),
1763 diag::err_shufflevector_non_vector)
1764 << SourceRange(TheCall->getArg(0)->getLocStart(),
1765 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001766
Nate Begeman37b6a572010-06-08 00:16:34 +00001767 numElements = LHSType->getAs<VectorType>()->getNumElements();
1768 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Nate Begeman37b6a572010-06-08 00:16:34 +00001770 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1771 // with mask. If so, verify that RHS is an integer vector type with the
1772 // same number of elts as lhs.
1773 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001774 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001775 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00001776 return ExprError(Diag(TheCall->getLocStart(),
1777 diag::err_shufflevector_incompatible_vector)
1778 << SourceRange(TheCall->getArg(1)->getLocStart(),
1779 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001780 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00001781 return ExprError(Diag(TheCall->getLocStart(),
1782 diag::err_shufflevector_incompatible_vector)
1783 << SourceRange(TheCall->getArg(0)->getLocStart(),
1784 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001785 } else if (numElements != numResElements) {
1786 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001787 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001788 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001789 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001790 }
1791
1792 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001793 if (TheCall->getArg(i)->isTypeDependent() ||
1794 TheCall->getArg(i)->isValueDependent())
1795 continue;
1796
Nate Begeman37b6a572010-06-08 00:16:34 +00001797 llvm::APSInt Result(32);
1798 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1799 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001800 diag::err_shufflevector_nonconstant_argument)
1801 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001802
Craig Topper6f4f8082013-08-03 17:40:38 +00001803 // Allow -1 which will be translated to undef in the IR.
1804 if (Result.isSigned() && Result.isAllOnesValue())
1805 continue;
1806
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001807 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001808 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001809 diag::err_shufflevector_argument_too_large)
1810 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001811 }
1812
Chris Lattner5f9e2722011-07-23 10:55:15 +00001813 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001814
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001815 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001816 exprs.push_back(TheCall->getArg(i));
1817 TheCall->setArg(i, 0);
1818 }
1819
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001820 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001821 TheCall->getCallee()->getLocStart(),
1822 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001823}
Chris Lattner30ce3442007-12-19 23:59:04 +00001824
Hal Finkel414a1bd2013-09-18 03:29:45 +00001825/// SemaConvertVectorExpr - Handle __builtin_convertvector
1826ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1827 SourceLocation BuiltinLoc,
1828 SourceLocation RParenLoc) {
1829 ExprValueKind VK = VK_RValue;
1830 ExprObjectKind OK = OK_Ordinary;
1831 QualType DstTy = TInfo->getType();
1832 QualType SrcTy = E->getType();
1833
1834 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1835 return ExprError(Diag(BuiltinLoc,
1836 diag::err_convertvector_non_vector)
1837 << E->getSourceRange());
1838 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1839 return ExprError(Diag(BuiltinLoc,
1840 diag::err_convertvector_non_vector_type));
1841
1842 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1843 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1844 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1845 if (SrcElts != DstElts)
1846 return ExprError(Diag(BuiltinLoc,
1847 diag::err_convertvector_incompatible_vector)
1848 << E->getSourceRange());
1849 }
1850
1851 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1852 BuiltinLoc, RParenLoc));
1853
1854}
1855
Daniel Dunbar4493f792008-07-21 22:59:13 +00001856/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1857// This is declared to take (const void*, ...) and can take two
1858// optional constant int args.
1859bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001860 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001861
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001862 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001863 return Diag(TheCall->getLocEnd(),
1864 diag::err_typecheck_call_too_many_args_at_most)
1865 << 0 /*function call*/ << 3 << NumArgs
1866 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001867
1868 // Argument 0 is checked for us and the remaining arguments must be
1869 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001870 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001871 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001872
1873 // We can't check the value of a dependent argument.
1874 if (Arg->isTypeDependent() || Arg->isValueDependent())
1875 continue;
1876
Eli Friedman9aef7262009-12-04 00:30:06 +00001877 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001878 if (SemaBuiltinConstantArg(TheCall, i, Result))
1879 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Daniel Dunbar4493f792008-07-21 22:59:13 +00001881 // FIXME: gcc issues a warning and rewrites these to 0. These
1882 // seems especially odd for the third argument since the default
1883 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001884 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001885 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001886 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001887 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001888 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001889 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001890 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001891 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001892 }
1893 }
1894
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001895 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001896}
1897
Eric Christopher691ebc32010-04-17 02:26:23 +00001898/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1899/// TheCall is a constant expression.
1900bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1901 llvm::APSInt &Result) {
1902 Expr *Arg = TheCall->getArg(ArgNum);
1903 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1904 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1905
1906 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1907
1908 if (!Arg->isIntegerConstantExpr(Result, Context))
1909 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001910 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001911
Chris Lattner21fb98e2009-09-23 06:06:36 +00001912 return false;
1913}
1914
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001915/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1916/// int type). This simply type checks that type is one of the defined
1917/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001918// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001919bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001920 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001921
1922 // We can't check the value of a dependent argument.
1923 if (TheCall->getArg(1)->isTypeDependent() ||
1924 TheCall->getArg(1)->isValueDependent())
1925 return false;
1926
Eric Christopher691ebc32010-04-17 02:26:23 +00001927 // Check constant-ness first.
1928 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1929 return true;
1930
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001931 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001932 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001933 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1934 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001935 }
1936
1937 return false;
1938}
1939
Eli Friedman586d6a82009-05-03 06:04:26 +00001940/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001941/// This checks that val is a constant 1.
1942bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1943 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001944 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001945
Eric Christopher691ebc32010-04-17 02:26:23 +00001946 // TODO: This is less than ideal. Overload this to take a value.
1947 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1948 return true;
1949
1950 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001951 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1952 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1953
1954 return false;
1955}
1956
Richard Smith0e218972013-08-05 18:49:43 +00001957namespace {
1958enum StringLiteralCheckType {
1959 SLCT_NotALiteral,
1960 SLCT_UncheckedLiteral,
1961 SLCT_CheckedLiteral
1962};
1963}
1964
Richard Smith831421f2012-06-25 20:30:08 +00001965// Determine if an expression is a string literal or constant string.
1966// If this function returns false on the arguments to a function expecting a
1967// format string, we will usually need to emit a warning.
1968// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00001969static StringLiteralCheckType
1970checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1971 bool HasVAListArg, unsigned format_idx,
1972 unsigned firstDataArg, Sema::FormatStringType Type,
1973 Sema::VariadicCallType CallType, bool InFunctionCall,
1974 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001975 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001976 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001977 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001978
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001979 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001980
Richard Smith0e218972013-08-05 18:49:43 +00001981 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00001982 // Technically -Wformat-nonliteral does not warn about this case.
1983 // The behavior of printf and friends in this case is implementation
1984 // dependent. Ideally if the format string cannot be null then
1985 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00001986 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001987
Ted Kremenekd30ef872009-01-12 23:09:09 +00001988 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001989 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001990 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001991 // The expression is a literal if both sub-expressions were, and it was
1992 // completely checked only if both sub-expressions were checked.
1993 const AbstractConditionalOperator *C =
1994 cast<AbstractConditionalOperator>(E);
1995 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00001996 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001997 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00001998 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00001999 if (Left == SLCT_NotALiteral)
2000 return SLCT_NotALiteral;
2001 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00002002 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002003 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002004 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002005 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002006 }
2007
2008 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002009 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2010 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002011 }
2012
John McCall56ca35d2011-02-17 10:25:35 +00002013 case Stmt::OpaqueValueExprClass:
2014 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2015 E = src;
2016 goto tryAgain;
2017 }
Richard Smith831421f2012-06-25 20:30:08 +00002018 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00002019
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002020 case Stmt::PredefinedExprClass:
2021 // While __func__, etc., are technically not string literals, they
2022 // cannot contain format specifiers and thus are not a security
2023 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00002024 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002025
Ted Kremenek082d9362009-03-20 21:35:28 +00002026 case Stmt::DeclRefExprClass: {
2027 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Ted Kremenek082d9362009-03-20 21:35:28 +00002029 // As an exception, do not flag errors for variables binding to
2030 // const string literals.
2031 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2032 bool isConstant = false;
2033 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00002034
Richard Smith0e218972013-08-05 18:49:43 +00002035 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2036 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002037 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002038 isConstant = T.isConstant(S.Context) &&
2039 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002040 } else if (T->isObjCObjectPointerType()) {
2041 // In ObjC, there is usually no "const ObjectPointer" type,
2042 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002043 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002044 }
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Ted Kremenek082d9362009-03-20 21:35:28 +00002046 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002047 if (const Expr *Init = VD->getAnyInitializer()) {
2048 // Look through initializers like const char c[] = { "foo" }
2049 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2050 if (InitList->isStringLiteralInit())
2051 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2052 }
Richard Smith0e218972013-08-05 18:49:43 +00002053 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002054 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002055 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002056 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002057 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002058 }
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Anders Carlssond966a552009-06-28 19:55:58 +00002060 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2061 // special check to see if the format string is a function parameter
2062 // of the function calling the printf function. If the function
2063 // has an attribute indicating it is a printf-like function, then we
2064 // should suppress warnings concerning non-literals being used in a call
2065 // to a vprintf function. For example:
2066 //
2067 // void
2068 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2069 // va_list ap;
2070 // va_start(ap, fmt);
2071 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2072 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002073 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002074 if (HasVAListArg) {
2075 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2076 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2077 int PVIndex = PV->getFunctionScopeIndex() + 1;
2078 for (specific_attr_iterator<FormatAttr>
2079 i = ND->specific_attr_begin<FormatAttr>(),
2080 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2081 FormatAttr *PVFormat = *i;
2082 // adjust for implicit parameter
2083 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2084 if (MD->isInstance())
2085 ++PVIndex;
2086 // We also check if the formats are compatible.
2087 // We can't pass a 'scanf' string to a 'printf' function.
2088 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002089 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002090 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002091 }
2092 }
2093 }
2094 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002095 }
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Richard Smith831421f2012-06-25 20:30:08 +00002097 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002098 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002099
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002100 case Stmt::CallExprClass:
2101 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002102 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002103 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2104 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2105 unsigned ArgIndex = FA->getFormatIdx();
2106 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2107 if (MD->isInstance())
2108 --ArgIndex;
2109 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Richard Smith0e218972013-08-05 18:49:43 +00002111 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002112 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002113 Type, CallType, InFunctionCall,
2114 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002115 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2116 unsigned BuiltinID = FD->getBuiltinID();
2117 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2118 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2119 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002120 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002121 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002122 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002123 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002124 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002125 }
2126 }
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Richard Smith831421f2012-06-25 20:30:08 +00002128 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002129 }
Fariborz Jahanianc85832f2013-10-18 21:20:34 +00002130
2131 case Stmt::ObjCMessageExprClass: {
2132 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(E);
2133 if (const ObjCMethodDecl *MDecl = ME->getMethodDecl()) {
2134 if (const NamedDecl *ND = dyn_cast<NamedDecl>(MDecl)) {
2135 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2136 unsigned ArgIndex = FA->getFormatIdx();
2137 if (ArgIndex <= ME->getNumArgs()) {
2138 const Expr *Arg = ME->getArg(ArgIndex-1);
2139 return checkFormatStringExpr(S, Arg, Args,
2140 HasVAListArg, format_idx,
2141 firstDataArg, Type, CallType,
2142 InFunctionCall, CheckedVarArgs);
2143 }
2144 }
2145 }
2146 }
2147
2148 return SLCT_NotALiteral;
2149 }
2150
Ted Kremenek082d9362009-03-20 21:35:28 +00002151 case Stmt::ObjCStringLiteralClass:
2152 case Stmt::StringLiteralClass: {
2153 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002154
Ted Kremenek082d9362009-03-20 21:35:28 +00002155 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002156 StrE = ObjCFExpr->getString();
2157 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002158 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Ted Kremenekd30ef872009-01-12 23:09:09 +00002160 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002161 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2162 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002163 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002164 }
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Richard Smith831421f2012-06-25 20:30:08 +00002166 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002167 }
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Ted Kremenek082d9362009-03-20 21:35:28 +00002169 default:
Richard Smith831421f2012-06-25 20:30:08 +00002170 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002171 }
2172}
2173
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002174void
Mike Stump1eb44332009-09-09 15:08:12 +00002175Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00002176 const Expr * const *ExprArgs,
2177 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00002178 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2179 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002180 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00002181 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00002182
2183 // As a special case, transparent unions initialized with zero are
2184 // considered null for the purposes of the nonnull attribute.
2185 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2186 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2187 if (const CompoundLiteralExpr *CLE =
2188 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2189 if (const InitListExpr *ILE =
2190 dyn_cast<InitListExpr>(CLE->getInitializer()))
2191 ArgExpr = ILE->getInit(0);
2192 }
2193
2194 bool Result;
2195 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00002196 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002197 }
2198}
Ted Kremenekd30ef872009-01-12 23:09:09 +00002199
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002200Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002201 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002202 .Case("scanf", FST_Scanf)
2203 .Cases("printf", "printf0", FST_Printf)
2204 .Cases("NSString", "CFString", FST_NSString)
2205 .Case("strftime", FST_Strftime)
2206 .Case("strfmon", FST_Strfmon)
2207 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2208 .Default(FST_Unknown);
2209}
2210
Jordan Roseddcfbc92012-07-19 18:10:23 +00002211/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002212/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002213/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002214bool Sema::CheckFormatArguments(const FormatAttr *Format,
2215 ArrayRef<const Expr *> Args,
2216 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002217 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002218 SourceLocation Loc, SourceRange Range,
2219 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002220 FormatStringInfo FSI;
2221 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002222 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002223 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002224 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002225 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002226}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002227
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002228bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002229 bool HasVAListArg, unsigned format_idx,
2230 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002231 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002232 SourceLocation Loc, SourceRange Range,
2233 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002234 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002235 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002236 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002237 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002238 }
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002240 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Chris Lattner59907c42007-08-10 20:18:51 +00002242 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002243 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002244 // Dynamically generated format strings are difficult to
2245 // automatically vet at compile time. Requiring that format strings
2246 // are string literals: (1) permits the checking of format strings by
2247 // the compiler and thereby (2) can practically remove the source of
2248 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002249
Mike Stump1eb44332009-09-09 15:08:12 +00002250 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002251 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002252 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002253 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002254 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002255 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2256 format_idx, firstDataArg, Type, CallType,
2257 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002258 if (CT != SLCT_NotALiteral)
2259 // Literal format string found, check done!
2260 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002261
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002262 // Strftime is particular as it always uses a single 'time' argument,
2263 // so it is safe to pass a non-literal string.
2264 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002265 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002266
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002267 // Do not emit diag when the string param is a macro expansion and the
2268 // format is either NSString or CFString. This is a hack to prevent
2269 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2270 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002271 if (Type == FST_NSString &&
2272 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002273 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002274
Chris Lattner655f1412009-04-29 04:59:47 +00002275 // If there are no arguments specified, warn with -Wformat-security, otherwise
2276 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002277 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002278 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002279 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002280 << OrigFormatExpr->getSourceRange();
2281 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002282 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002283 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002284 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002285 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002286}
Ted Kremenek71895b92007-08-14 17:39:48 +00002287
Ted Kremeneke0e53132010-01-28 23:39:18 +00002288namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002289class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2290protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002291 Sema &S;
2292 const StringLiteral *FExpr;
2293 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002294 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002295 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002296 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002297 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002298 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002299 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002300 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002301 bool usesPositionalArgs;
2302 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002303 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002304 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002305 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002306public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002307 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002308 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002309 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002310 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002311 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002312 Sema::VariadicCallType callType,
2313 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002314 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002315 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2316 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002317 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002318 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002319 inFunctionCall(inFunctionCall), CallType(callType),
2320 CheckedVarArgs(CheckedVarArgs) {
2321 CoveredArgs.resize(numDataArgs);
2322 CoveredArgs.reset();
2323 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002324
Ted Kremenek07d161f2010-01-29 01:50:07 +00002325 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002326
Ted Kremenek826a3452010-07-16 02:11:22 +00002327 void HandleIncompleteSpecifier(const char *startSpecifier,
2328 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002329
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002330 void HandleInvalidLengthModifier(
2331 const analyze_format_string::FormatSpecifier &FS,
2332 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002333 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002334
Hans Wennborg76517422012-02-22 10:17:01 +00002335 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002336 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002337 const char *startSpecifier, unsigned specifierLen);
2338
2339 void HandleNonStandardConversionSpecifier(
2340 const analyze_format_string::ConversionSpecifier &CS,
2341 const char *startSpecifier, unsigned specifierLen);
2342
Hans Wennborgf8562642012-03-09 10:10:54 +00002343 virtual void HandlePosition(const char *startPos, unsigned posLen);
2344
Ted Kremenekefaff192010-02-27 01:41:03 +00002345 virtual void HandleInvalidPosition(const char *startSpecifier,
2346 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002347 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002348
2349 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2350
Ted Kremeneke0e53132010-01-28 23:39:18 +00002351 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002352
Richard Trieu55733de2011-10-28 00:41:25 +00002353 template <typename Range>
2354 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2355 const Expr *ArgumentExpr,
2356 PartialDiagnostic PDiag,
2357 SourceLocation StringLoc,
2358 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002359 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002360
Ted Kremenek826a3452010-07-16 02:11:22 +00002361protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002362 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2363 const char *startSpec,
2364 unsigned specifierLen,
2365 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002366
2367 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2368 const char *startSpec,
2369 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002370
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002371 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002372 CharSourceRange getSpecifierRange(const char *startSpecifier,
2373 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002374 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002375
Ted Kremenek0d277352010-01-29 01:06:55 +00002376 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002377
2378 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2379 const analyze_format_string::ConversionSpecifier &CS,
2380 const char *startSpecifier, unsigned specifierLen,
2381 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002382
2383 template <typename Range>
2384 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2385 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002386 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002387
2388 void CheckPositionalAndNonpositionalArgs(
2389 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002390};
2391}
2392
Ted Kremenek826a3452010-07-16 02:11:22 +00002393SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002394 return OrigFormatExpr->getSourceRange();
2395}
2396
Ted Kremenek826a3452010-07-16 02:11:22 +00002397CharSourceRange CheckFormatHandler::
2398getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002399 SourceLocation Start = getLocationOfByte(startSpecifier);
2400 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2401
2402 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002403 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002404
2405 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002406}
2407
Ted Kremenek826a3452010-07-16 02:11:22 +00002408SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002409 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002410}
2411
Ted Kremenek826a3452010-07-16 02:11:22 +00002412void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2413 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002414 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2415 getLocationOfByte(startSpecifier),
2416 /*IsStringLocation*/true,
2417 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002418}
2419
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002420void CheckFormatHandler::HandleInvalidLengthModifier(
2421 const analyze_format_string::FormatSpecifier &FS,
2422 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002423 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002424 using namespace analyze_format_string;
2425
2426 const LengthModifier &LM = FS.getLengthModifier();
2427 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2428
2429 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002430 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002431 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002432 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002433 getLocationOfByte(LM.getStart()),
2434 /*IsStringLocation*/true,
2435 getSpecifierRange(startSpecifier, specifierLen));
2436
2437 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2438 << FixedLM->toString()
2439 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2440
2441 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002442 FixItHint Hint;
2443 if (DiagID == diag::warn_format_nonsensical_length)
2444 Hint = FixItHint::CreateRemoval(LMRange);
2445
2446 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002447 getLocationOfByte(LM.getStart()),
2448 /*IsStringLocation*/true,
2449 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002450 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002451 }
2452}
2453
Hans Wennborg76517422012-02-22 10:17:01 +00002454void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002455 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002456 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002457 using namespace analyze_format_string;
2458
2459 const LengthModifier &LM = FS.getLengthModifier();
2460 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2461
2462 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002463 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002464 if (FixedLM) {
2465 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2466 << LM.toString() << 0,
2467 getLocationOfByte(LM.getStart()),
2468 /*IsStringLocation*/true,
2469 getSpecifierRange(startSpecifier, specifierLen));
2470
2471 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2472 << FixedLM->toString()
2473 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2474
2475 } else {
2476 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2477 << LM.toString() << 0,
2478 getLocationOfByte(LM.getStart()),
2479 /*IsStringLocation*/true,
2480 getSpecifierRange(startSpecifier, specifierLen));
2481 }
Hans Wennborg76517422012-02-22 10:17:01 +00002482}
2483
2484void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2485 const analyze_format_string::ConversionSpecifier &CS,
2486 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002487 using namespace analyze_format_string;
2488
2489 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002490 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002491 if (FixedCS) {
2492 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2493 << CS.toString() << /*conversion specifier*/1,
2494 getLocationOfByte(CS.getStart()),
2495 /*IsStringLocation*/true,
2496 getSpecifierRange(startSpecifier, specifierLen));
2497
2498 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2499 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2500 << FixedCS->toString()
2501 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2502 } else {
2503 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2504 << CS.toString() << /*conversion specifier*/1,
2505 getLocationOfByte(CS.getStart()),
2506 /*IsStringLocation*/true,
2507 getSpecifierRange(startSpecifier, specifierLen));
2508 }
Hans Wennborg76517422012-02-22 10:17:01 +00002509}
2510
Hans Wennborgf8562642012-03-09 10:10:54 +00002511void CheckFormatHandler::HandlePosition(const char *startPos,
2512 unsigned posLen) {
2513 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2514 getLocationOfByte(startPos),
2515 /*IsStringLocation*/true,
2516 getSpecifierRange(startPos, posLen));
2517}
2518
Ted Kremenekefaff192010-02-27 01:41:03 +00002519void
Ted Kremenek826a3452010-07-16 02:11:22 +00002520CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2521 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002522 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2523 << (unsigned) p,
2524 getLocationOfByte(startPos), /*IsStringLocation*/true,
2525 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002526}
2527
Ted Kremenek826a3452010-07-16 02:11:22 +00002528void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002529 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002530 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2531 getLocationOfByte(startPos),
2532 /*IsStringLocation*/true,
2533 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002534}
2535
Ted Kremenek826a3452010-07-16 02:11:22 +00002536void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002537 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002538 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002539 EmitFormatDiagnostic(
2540 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2541 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2542 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002543 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002544}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002545
Jordan Rose48716662012-07-19 18:10:08 +00002546// Note that this may return NULL if there was an error parsing or building
2547// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002548const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002549 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002550}
2551
2552void CheckFormatHandler::DoneProcessing() {
2553 // Does the number of data arguments exceed the number of
2554 // format conversions in the format string?
2555 if (!HasVAListArg) {
2556 // Find any arguments that weren't covered.
2557 CoveredArgs.flip();
2558 signed notCoveredArg = CoveredArgs.find_first();
2559 if (notCoveredArg >= 0) {
2560 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002561 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2562 SourceLocation Loc = E->getLocStart();
2563 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2564 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2565 Loc, /*IsStringLocation*/false,
2566 getFormatStringRange());
2567 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002568 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002569 }
2570 }
2571}
2572
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002573bool
2574CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2575 SourceLocation Loc,
2576 const char *startSpec,
2577 unsigned specifierLen,
2578 const char *csStart,
2579 unsigned csLen) {
2580
2581 bool keepGoing = true;
2582 if (argIndex < NumDataArgs) {
2583 // Consider the argument coverered, even though the specifier doesn't
2584 // make sense.
2585 CoveredArgs.set(argIndex);
2586 }
2587 else {
2588 // If argIndex exceeds the number of data arguments we
2589 // don't issue a warning because that is just a cascade of warnings (and
2590 // they may have intended '%%' anyway). We don't want to continue processing
2591 // the format string after this point, however, as we will like just get
2592 // gibberish when trying to match arguments.
2593 keepGoing = false;
2594 }
2595
Richard Trieu55733de2011-10-28 00:41:25 +00002596 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2597 << StringRef(csStart, csLen),
2598 Loc, /*IsStringLocation*/true,
2599 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002600
2601 return keepGoing;
2602}
2603
Richard Trieu55733de2011-10-28 00:41:25 +00002604void
2605CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2606 const char *startSpec,
2607 unsigned specifierLen) {
2608 EmitFormatDiagnostic(
2609 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2610 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2611}
2612
Ted Kremenek666a1972010-07-26 19:45:42 +00002613bool
2614CheckFormatHandler::CheckNumArgs(
2615 const analyze_format_string::FormatSpecifier &FS,
2616 const analyze_format_string::ConversionSpecifier &CS,
2617 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2618
2619 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002620 PartialDiagnostic PDiag = FS.usesPositionalArg()
2621 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2622 << (argIndex+1) << NumDataArgs)
2623 : S.PDiag(diag::warn_printf_insufficient_data_args);
2624 EmitFormatDiagnostic(
2625 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2626 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002627 return false;
2628 }
2629 return true;
2630}
2631
Richard Trieu55733de2011-10-28 00:41:25 +00002632template<typename Range>
2633void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2634 SourceLocation Loc,
2635 bool IsStringLocation,
2636 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002637 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002638 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002639 Loc, IsStringLocation, StringRange, FixIt);
2640}
2641
2642/// \brief If the format string is not within the funcion call, emit a note
2643/// so that the function call and string are in diagnostic messages.
2644///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002645/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002646/// call and only one diagnostic message will be produced. Otherwise, an
2647/// extra note will be emitted pointing to location of the format string.
2648///
2649/// \param ArgumentExpr the expression that is passed as the format string
2650/// argument in the function call. Used for getting locations when two
2651/// diagnostics are emitted.
2652///
2653/// \param PDiag the callee should already have provided any strings for the
2654/// diagnostic message. This function only adds locations and fixits
2655/// to diagnostics.
2656///
2657/// \param Loc primary location for diagnostic. If two diagnostics are
2658/// required, one will be at Loc and a new SourceLocation will be created for
2659/// the other one.
2660///
2661/// \param IsStringLocation if true, Loc points to the format string should be
2662/// used for the note. Otherwise, Loc points to the argument list and will
2663/// be used with PDiag.
2664///
2665/// \param StringRange some or all of the string to highlight. This is
2666/// templated so it can accept either a CharSourceRange or a SourceRange.
2667///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002668/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002669template<typename Range>
2670void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2671 const Expr *ArgumentExpr,
2672 PartialDiagnostic PDiag,
2673 SourceLocation Loc,
2674 bool IsStringLocation,
2675 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002676 ArrayRef<FixItHint> FixIt) {
2677 if (InFunctionCall) {
2678 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2679 D << StringRange;
2680 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2681 I != E; ++I) {
2682 D << *I;
2683 }
2684 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002685 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2686 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002687
2688 const Sema::SemaDiagnosticBuilder &Note =
2689 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2690 diag::note_format_string_defined);
2691
2692 Note << StringRange;
2693 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2694 I != E; ++I) {
2695 Note << *I;
2696 }
Richard Trieu55733de2011-10-28 00:41:25 +00002697 }
2698}
2699
Ted Kremenek826a3452010-07-16 02:11:22 +00002700//===--- CHECK: Printf format string checking ------------------------------===//
2701
2702namespace {
2703class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002704 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002705public:
2706 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2707 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002708 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002709 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002710 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002711 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002712 Sema::VariadicCallType CallType,
2713 llvm::SmallBitVector &CheckedVarArgs)
2714 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2715 numDataArgs, beg, hasVAListArg, Args,
2716 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2717 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002718 {}
2719
Ted Kremenek826a3452010-07-16 02:11:22 +00002720
2721 bool HandleInvalidPrintfConversionSpecifier(
2722 const analyze_printf::PrintfSpecifier &FS,
2723 const char *startSpecifier,
2724 unsigned specifierLen);
2725
2726 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2727 const char *startSpecifier,
2728 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002729 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2730 const char *StartSpecifier,
2731 unsigned SpecifierLen,
2732 const Expr *E);
2733
Ted Kremenek826a3452010-07-16 02:11:22 +00002734 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2735 const char *startSpecifier, unsigned specifierLen);
2736 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2737 const analyze_printf::OptionalAmount &Amt,
2738 unsigned type,
2739 const char *startSpecifier, unsigned specifierLen);
2740 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2741 const analyze_printf::OptionalFlag &flag,
2742 const char *startSpecifier, unsigned specifierLen);
2743 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2744 const analyze_printf::OptionalFlag &ignoredFlag,
2745 const analyze_printf::OptionalFlag &flag,
2746 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002747 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002748 const Expr *E, const CharSourceRange &CSR);
2749
Ted Kremenek826a3452010-07-16 02:11:22 +00002750};
2751}
2752
2753bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2754 const analyze_printf::PrintfSpecifier &FS,
2755 const char *startSpecifier,
2756 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002757 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002758 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002759
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002760 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2761 getLocationOfByte(CS.getStart()),
2762 startSpecifier, specifierLen,
2763 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002764}
2765
Ted Kremenek826a3452010-07-16 02:11:22 +00002766bool CheckPrintfHandler::HandleAmount(
2767 const analyze_format_string::OptionalAmount &Amt,
2768 unsigned k, const char *startSpecifier,
2769 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002770
2771 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002772 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002773 unsigned argIndex = Amt.getArgIndex();
2774 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002775 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2776 << k,
2777 getLocationOfByte(Amt.getStart()),
2778 /*IsStringLocation*/true,
2779 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002780 // Don't do any more checking. We will just emit
2781 // spurious errors.
2782 return false;
2783 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002784
Ted Kremenek0d277352010-01-29 01:06:55 +00002785 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002786 // Although not in conformance with C99, we also allow the argument to be
2787 // an 'unsigned int' as that is a reasonably safe case. GCC also
2788 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002789 CoveredArgs.set(argIndex);
2790 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002791 if (!Arg)
2792 return false;
2793
Ted Kremenek0d277352010-01-29 01:06:55 +00002794 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002795
Hans Wennborgf3749f42012-08-07 08:11:26 +00002796 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2797 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002798
Hans Wennborgf3749f42012-08-07 08:11:26 +00002799 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002800 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002801 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002802 << T << Arg->getSourceRange(),
2803 getLocationOfByte(Amt.getStart()),
2804 /*IsStringLocation*/true,
2805 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002806 // Don't do any more checking. We will just emit
2807 // spurious errors.
2808 return false;
2809 }
2810 }
2811 }
2812 return true;
2813}
Ted Kremenek0d277352010-01-29 01:06:55 +00002814
Tom Caree4ee9662010-06-17 19:00:27 +00002815void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002816 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002817 const analyze_printf::OptionalAmount &Amt,
2818 unsigned type,
2819 const char *startSpecifier,
2820 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002821 const analyze_printf::PrintfConversionSpecifier &CS =
2822 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002823
Richard Trieu55733de2011-10-28 00:41:25 +00002824 FixItHint fixit =
2825 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2826 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2827 Amt.getConstantLength()))
2828 : FixItHint();
2829
2830 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2831 << type << CS.toString(),
2832 getLocationOfByte(Amt.getStart()),
2833 /*IsStringLocation*/true,
2834 getSpecifierRange(startSpecifier, specifierLen),
2835 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002836}
2837
Ted Kremenek826a3452010-07-16 02:11:22 +00002838void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002839 const analyze_printf::OptionalFlag &flag,
2840 const char *startSpecifier,
2841 unsigned specifierLen) {
2842 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002843 const analyze_printf::PrintfConversionSpecifier &CS =
2844 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002845 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2846 << flag.toString() << CS.toString(),
2847 getLocationOfByte(flag.getPosition()),
2848 /*IsStringLocation*/true,
2849 getSpecifierRange(startSpecifier, specifierLen),
2850 FixItHint::CreateRemoval(
2851 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002852}
2853
2854void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002855 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002856 const analyze_printf::OptionalFlag &ignoredFlag,
2857 const analyze_printf::OptionalFlag &flag,
2858 const char *startSpecifier,
2859 unsigned specifierLen) {
2860 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002861 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2862 << ignoredFlag.toString() << flag.toString(),
2863 getLocationOfByte(ignoredFlag.getPosition()),
2864 /*IsStringLocation*/true,
2865 getSpecifierRange(startSpecifier, specifierLen),
2866 FixItHint::CreateRemoval(
2867 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002868}
2869
Richard Smith831421f2012-06-25 20:30:08 +00002870// Determines if the specified is a C++ class or struct containing
2871// a member with the specified name and kind (e.g. a CXXMethodDecl named
2872// "c_str()").
2873template<typename MemberKind>
2874static llvm::SmallPtrSet<MemberKind*, 1>
2875CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2876 const RecordType *RT = Ty->getAs<RecordType>();
2877 llvm::SmallPtrSet<MemberKind*, 1> Results;
2878
2879 if (!RT)
2880 return Results;
2881 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2882 if (!RD)
2883 return Results;
2884
2885 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2886 Sema::LookupMemberName);
2887
2888 // We just need to include all members of the right kind turned up by the
2889 // filter, at this point.
2890 if (S.LookupQualifiedName(R, RT->getDecl()))
2891 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2892 NamedDecl *decl = (*I)->getUnderlyingDecl();
2893 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2894 Results.insert(FK);
2895 }
2896 return Results;
2897}
2898
2899// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002900// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002901// Returns true when a c_str() conversion method is found.
2902bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002903 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002904 const CharSourceRange &CSR) {
2905 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2906
2907 MethodSet Results =
2908 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2909
2910 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2911 MI != ME; ++MI) {
2912 const CXXMethodDecl *Method = *MI;
2913 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002914 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002915 // FIXME: Suggest parens if the expression needs them.
2916 SourceLocation EndLoc =
2917 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2918 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2919 << "c_str()"
2920 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2921 return true;
2922 }
2923 }
2924
2925 return false;
2926}
2927
Ted Kremeneke0e53132010-01-28 23:39:18 +00002928bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002929CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002930 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002931 const char *startSpecifier,
2932 unsigned specifierLen) {
2933
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002934 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002935 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002936 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002937
Ted Kremenekbaa40062010-07-19 22:01:06 +00002938 if (FS.consumesDataArgument()) {
2939 if (atFirstArg) {
2940 atFirstArg = false;
2941 usesPositionalArgs = FS.usesPositionalArg();
2942 }
2943 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002944 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2945 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002946 return false;
2947 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002948 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002949
Ted Kremenekefaff192010-02-27 01:41:03 +00002950 // First check if the field width, precision, and conversion specifier
2951 // have matching data arguments.
2952 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2953 startSpecifier, specifierLen)) {
2954 return false;
2955 }
2956
2957 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2958 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002959 return false;
2960 }
2961
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002962 if (!CS.consumesDataArgument()) {
2963 // FIXME: Technically specifying a precision or field width here
2964 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002965 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002966 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002967
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002968 // Consume the argument.
2969 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002970 if (argIndex < NumDataArgs) {
2971 // The check to see if the argIndex is valid will come later.
2972 // We set the bit here because we may exit early from this
2973 // function if we encounter some other error.
2974 CoveredArgs.set(argIndex);
2975 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002976
2977 // Check for using an Objective-C specific conversion specifier
2978 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002979 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002980 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2981 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002982 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002983
Tom Caree4ee9662010-06-17 19:00:27 +00002984 // Check for invalid use of field width
2985 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002986 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002987 startSpecifier, specifierLen);
2988 }
2989
2990 // Check for invalid use of precision
2991 if (!FS.hasValidPrecision()) {
2992 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2993 startSpecifier, specifierLen);
2994 }
2995
2996 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002997 if (!FS.hasValidThousandsGroupingPrefix())
2998 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002999 if (!FS.hasValidLeadingZeros())
3000 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3001 if (!FS.hasValidPlusPrefix())
3002 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00003003 if (!FS.hasValidSpacePrefix())
3004 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003005 if (!FS.hasValidAlternativeForm())
3006 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3007 if (!FS.hasValidLeftJustified())
3008 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3009
3010 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00003011 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3012 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3013 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003014 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3015 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3016 startSpecifier, specifierLen);
3017
3018 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003019 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003020 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3021 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003022 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003023 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003024 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003025 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3026 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00003027
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003028 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3029 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3030
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003031 // The remaining checks depend on the data arguments.
3032 if (HasVAListArg)
3033 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003034
Ted Kremenek666a1972010-07-26 19:45:42 +00003035 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003036 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003037
Jordan Rose48716662012-07-19 18:10:08 +00003038 const Expr *Arg = getDataArg(argIndex);
3039 if (!Arg)
3040 return true;
3041
3042 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00003043}
3044
Jordan Roseec087352012-09-05 22:56:26 +00003045static bool requiresParensToAddCast(const Expr *E) {
3046 // FIXME: We should have a general way to reason about operator
3047 // precedence and whether parens are actually needed here.
3048 // Take care of a few common cases where they aren't.
3049 const Expr *Inside = E->IgnoreImpCasts();
3050 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3051 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3052
3053 switch (Inside->getStmtClass()) {
3054 case Stmt::ArraySubscriptExprClass:
3055 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003056 case Stmt::CharacterLiteralClass:
3057 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003058 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003059 case Stmt::FloatingLiteralClass:
3060 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003061 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003062 case Stmt::ObjCArrayLiteralClass:
3063 case Stmt::ObjCBoolLiteralExprClass:
3064 case Stmt::ObjCBoxedExprClass:
3065 case Stmt::ObjCDictionaryLiteralClass:
3066 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003067 case Stmt::ObjCIvarRefExprClass:
3068 case Stmt::ObjCMessageExprClass:
3069 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003070 case Stmt::ObjCStringLiteralClass:
3071 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003072 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003073 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003074 case Stmt::UnaryOperatorClass:
3075 return false;
3076 default:
3077 return true;
3078 }
3079}
3080
Richard Smith831421f2012-06-25 20:30:08 +00003081bool
3082CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3083 const char *StartSpecifier,
3084 unsigned SpecifierLen,
3085 const Expr *E) {
3086 using namespace analyze_format_string;
3087 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003088 // Now type check the data expression that matches the
3089 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003090 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3091 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003092 if (!AT.isValid())
3093 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003094
Jordan Rose448ac3e2012-12-05 18:44:40 +00003095 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003096 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3097 ExprTy = TET->getUnderlyingExpr()->getType();
3098 }
3099
Jordan Rose448ac3e2012-12-05 18:44:40 +00003100 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003101 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003102
Jordan Rose614a8652012-09-05 22:56:19 +00003103 // Look through argument promotions for our error message's reported type.
3104 // This includes the integral and floating promotions, but excludes array
3105 // and function pointer decay; seeing that an argument intended to be a
3106 // string has type 'char [6]' is probably more confusing than 'char *'.
3107 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3108 if (ICE->getCastKind() == CK_IntegralCast ||
3109 ICE->getCastKind() == CK_FloatingCast) {
3110 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003111 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003112
3113 // Check if we didn't match because of an implicit cast from a 'char'
3114 // or 'short' to an 'int'. This is done because printf is a varargs
3115 // function.
3116 if (ICE->getType() == S.Context.IntTy ||
3117 ICE->getType() == S.Context.UnsignedIntTy) {
3118 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003119 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003120 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003121 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003122 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003123 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3124 // Special case for 'a', which has type 'int' in C.
3125 // Note, however, that we do /not/ want to treat multibyte constants like
3126 // 'MooV' as characters! This form is deprecated but still exists.
3127 if (ExprTy == S.Context.IntTy)
3128 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3129 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003130 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003131
Jordan Rose2cd34402012-12-05 18:44:49 +00003132 // %C in an Objective-C context prints a unichar, not a wchar_t.
3133 // If the argument is an integer of some kind, believe the %C and suggest
3134 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003135 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003136 if (ObjCContext &&
3137 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3138 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3139 !ExprTy->isCharType()) {
3140 // 'unichar' is defined as a typedef of unsigned short, but we should
3141 // prefer using the typedef if it is visible.
3142 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenek656465d2013-10-15 05:25:17 +00003143
3144 // While we are here, check if the value is an IntegerLiteral that happens
3145 // to be within the valid range.
3146 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3147 const llvm::APInt &V = IL->getValue();
3148 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3149 return true;
3150 }
3151
Jordan Rose2cd34402012-12-05 18:44:49 +00003152 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3153 Sema::LookupOrdinaryName);
3154 if (S.LookupName(Result, S.getCurScope())) {
3155 NamedDecl *ND = Result.getFoundDecl();
3156 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3157 if (TD->getUnderlyingType() == IntendedTy)
3158 IntendedTy = S.Context.getTypedefType(TD);
3159 }
3160 }
3161 }
3162
3163 // Special-case some of Darwin's platform-independence types by suggesting
3164 // casts to primitive types that are known to be large enough.
3165 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00003166 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00003167 // Use a 'while' to peel off layers of typedefs.
3168 QualType TyTy = IntendedTy;
3169 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00003170 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00003171 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00003172 .Case("NSInteger", S.Context.LongTy)
3173 .Case("NSUInteger", S.Context.UnsignedLongTy)
3174 .Case("SInt32", S.Context.IntTy)
3175 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00003176 .Default(QualType());
3177
3178 if (!CastTy.isNull()) {
3179 ShouldNotPrintDirectly = true;
3180 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00003181 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00003182 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00003183 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00003184 }
3185 }
3186
Jordan Rose614a8652012-09-05 22:56:19 +00003187 // We may be able to offer a FixItHint if it is a supported type.
3188 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003189 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003190 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003191
Jordan Rose614a8652012-09-05 22:56:19 +00003192 if (success) {
3193 // Get the fix string from the fixed format specifier
3194 SmallString<16> buf;
3195 llvm::raw_svector_ostream os(buf);
3196 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003197
Jordan Roseec087352012-09-05 22:56:26 +00003198 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3199
Jordan Rose2cd34402012-12-05 18:44:49 +00003200 if (IntendedTy == ExprTy) {
3201 // In this case, the specifier is wrong and should be changed to match
3202 // the argument.
3203 EmitFormatDiagnostic(
3204 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3205 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3206 << E->getSourceRange(),
3207 E->getLocStart(),
3208 /*IsStringLocation*/false,
3209 SpecRange,
3210 FixItHint::CreateReplacement(SpecRange, os.str()));
3211
3212 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003213 // The canonical type for formatting this value is different from the
3214 // actual type of the expression. (This occurs, for example, with Darwin's
3215 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3216 // should be printed as 'long' for 64-bit compatibility.)
3217 // Rather than emitting a normal format/argument mismatch, we want to
3218 // add a cast to the recommended type (and correct the format string
3219 // if necessary).
3220 SmallString<16> CastBuf;
3221 llvm::raw_svector_ostream CastFix(CastBuf);
3222 CastFix << "(";
3223 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3224 CastFix << ")";
3225
3226 SmallVector<FixItHint,4> Hints;
3227 if (!AT.matchesType(S.Context, IntendedTy))
3228 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3229
3230 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3231 // If there's already a cast present, just replace it.
3232 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3233 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3234
3235 } else if (!requiresParensToAddCast(E)) {
3236 // If the expression has high enough precedence,
3237 // just write the C-style cast.
3238 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3239 CastFix.str()));
3240 } else {
3241 // Otherwise, add parens around the expression as well as the cast.
3242 CastFix << "(";
3243 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3244 CastFix.str()));
3245
3246 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3247 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3248 }
3249
Jordan Rose2cd34402012-12-05 18:44:49 +00003250 if (ShouldNotPrintDirectly) {
3251 // The expression has a type that should not be printed directly.
3252 // We extract the name from the typedef because we don't want to show
3253 // the underlying type in the diagnostic.
3254 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00003255
Jordan Rose2cd34402012-12-05 18:44:49 +00003256 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3257 << Name << IntendedTy
3258 << E->getSourceRange(),
3259 E->getLocStart(), /*IsStringLocation=*/false,
3260 SpecRange, Hints);
3261 } else {
3262 // In this case, the expression could be printed using a different
3263 // specifier, but we've decided that the specifier is probably correct
3264 // and we should cast instead. Just use the normal warning message.
3265 EmitFormatDiagnostic(
3266 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3267 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3268 << E->getSourceRange(),
3269 E->getLocStart(), /*IsStringLocation*/false,
3270 SpecRange, Hints);
3271 }
Jordan Roseec087352012-09-05 22:56:26 +00003272 }
Jordan Rose614a8652012-09-05 22:56:19 +00003273 } else {
3274 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3275 SpecifierLen);
3276 // Since the warning for passing non-POD types to variadic functions
3277 // was deferred until now, we emit a warning for non-POD
3278 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003279 switch (S.isValidVarArgType(ExprTy)) {
3280 case Sema::VAK_Valid:
3281 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003282 EmitFormatDiagnostic(
Richard Smith0e218972013-08-05 18:49:43 +00003283 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3284 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3285 << CSR
3286 << E->getSourceRange(),
3287 E->getLocStart(), /*IsStringLocation*/false, CSR);
3288 break;
3289
3290 case Sema::VAK_Undefined:
3291 EmitFormatDiagnostic(
3292 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003293 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003294 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003295 << CallType
3296 << AT.getRepresentativeTypeName(S.Context)
3297 << CSR
3298 << E->getSourceRange(),
3299 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose614a8652012-09-05 22:56:19 +00003300 checkForCStrMembers(AT, E, CSR);
Richard Smith0e218972013-08-05 18:49:43 +00003301 break;
3302
3303 case Sema::VAK_Invalid:
3304 if (ExprTy->isObjCObjectType())
3305 EmitFormatDiagnostic(
3306 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3307 << S.getLangOpts().CPlusPlus11
3308 << ExprTy
3309 << CallType
3310 << AT.getRepresentativeTypeName(S.Context)
3311 << CSR
3312 << E->getSourceRange(),
3313 E->getLocStart(), /*IsStringLocation*/false, CSR);
3314 else
3315 // FIXME: If this is an initializer list, suggest removing the braces
3316 // or inserting a cast to the target type.
3317 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3318 << isa<InitListExpr>(E) << ExprTy << CallType
3319 << AT.getRepresentativeTypeName(S.Context)
3320 << E->getSourceRange();
3321 break;
3322 }
3323
3324 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3325 "format string specifier index out of range");
3326 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003327 }
3328
Ted Kremeneke0e53132010-01-28 23:39:18 +00003329 return true;
3330}
3331
Ted Kremenek826a3452010-07-16 02:11:22 +00003332//===--- CHECK: Scanf format string checking ------------------------------===//
3333
3334namespace {
3335class CheckScanfHandler : public CheckFormatHandler {
3336public:
3337 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3338 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003339 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003340 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003341 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003342 Sema::VariadicCallType CallType,
3343 llvm::SmallBitVector &CheckedVarArgs)
3344 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3345 numDataArgs, beg, hasVAListArg,
3346 Args, formatIdx, inFunctionCall, CallType,
3347 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003348 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003349
3350 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3351 const char *startSpecifier,
3352 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003353
3354 bool HandleInvalidScanfConversionSpecifier(
3355 const analyze_scanf::ScanfSpecifier &FS,
3356 const char *startSpecifier,
3357 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003358
3359 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003360};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003361}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003362
Ted Kremenekb7c21012010-07-16 18:28:03 +00003363void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3364 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003365 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3366 getLocationOfByte(end), /*IsStringLocation*/true,
3367 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003368}
3369
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003370bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3371 const analyze_scanf::ScanfSpecifier &FS,
3372 const char *startSpecifier,
3373 unsigned specifierLen) {
3374
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003375 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003376 FS.getConversionSpecifier();
3377
3378 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3379 getLocationOfByte(CS.getStart()),
3380 startSpecifier, specifierLen,
3381 CS.getStart(), CS.getLength());
3382}
3383
Ted Kremenek826a3452010-07-16 02:11:22 +00003384bool CheckScanfHandler::HandleScanfSpecifier(
3385 const analyze_scanf::ScanfSpecifier &FS,
3386 const char *startSpecifier,
3387 unsigned specifierLen) {
3388
3389 using namespace analyze_scanf;
3390 using namespace analyze_format_string;
3391
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003392 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003393
Ted Kremenekbaa40062010-07-19 22:01:06 +00003394 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3395 // be used to decide if we are using positional arguments consistently.
3396 if (FS.consumesDataArgument()) {
3397 if (atFirstArg) {
3398 atFirstArg = false;
3399 usesPositionalArgs = FS.usesPositionalArg();
3400 }
3401 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003402 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3403 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003404 return false;
3405 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003406 }
3407
3408 // Check if the field with is non-zero.
3409 const OptionalAmount &Amt = FS.getFieldWidth();
3410 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3411 if (Amt.getConstantAmount() == 0) {
3412 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3413 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003414 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3415 getLocationOfByte(Amt.getStart()),
3416 /*IsStringLocation*/true, R,
3417 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003418 }
3419 }
3420
3421 if (!FS.consumesDataArgument()) {
3422 // FIXME: Technically specifying a precision or field width here
3423 // makes no sense. Worth issuing a warning at some point.
3424 return true;
3425 }
3426
3427 // Consume the argument.
3428 unsigned argIndex = FS.getArgIndex();
3429 if (argIndex < NumDataArgs) {
3430 // The check to see if the argIndex is valid will come later.
3431 // We set the bit here because we may exit early from this
3432 // function if we encounter some other error.
3433 CoveredArgs.set(argIndex);
3434 }
3435
Ted Kremenek1e51c202010-07-20 20:04:47 +00003436 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003437 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003438 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3439 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003440 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003441 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003442 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003443 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3444 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003445
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003446 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3447 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3448
Ted Kremenek826a3452010-07-16 02:11:22 +00003449 // The remaining checks depend on the data arguments.
3450 if (HasVAListArg)
3451 return true;
3452
Ted Kremenek666a1972010-07-26 19:45:42 +00003453 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003454 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003455
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003456 // Check that the argument type matches the format specifier.
3457 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003458 if (!Ex)
3459 return true;
3460
Hans Wennborg58e1e542012-08-07 08:59:46 +00003461 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3462 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003463 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003464 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003465 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003466
3467 if (success) {
3468 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003469 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003470 llvm::raw_svector_ostream os(buf);
3471 fixedFS.toString(os);
3472
3473 EmitFormatDiagnostic(
3474 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003475 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003476 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003477 Ex->getLocStart(),
3478 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003479 getSpecifierRange(startSpecifier, specifierLen),
3480 FixItHint::CreateReplacement(
3481 getSpecifierRange(startSpecifier, specifierLen),
3482 os.str()));
3483 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003484 EmitFormatDiagnostic(
3485 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003486 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003487 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003488 Ex->getLocStart(),
3489 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003490 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003491 }
3492 }
3493
Ted Kremenek826a3452010-07-16 02:11:22 +00003494 return true;
3495}
3496
3497void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003498 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003499 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003500 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003501 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00003502 bool inFunctionCall, VariadicCallType CallType,
3503 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003504
Ted Kremeneke0e53132010-01-28 23:39:18 +00003505 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003506 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003507 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003508 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003509 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3510 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003511 return;
3512 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003513
Ted Kremeneke0e53132010-01-28 23:39:18 +00003514 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003515 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003516 const char *Str = StrRef.data();
3517 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003518 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003519
Ted Kremeneke0e53132010-01-28 23:39:18 +00003520 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003521 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003522 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003523 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003524 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3525 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003526 return;
3527 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003528
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003529 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003530 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003531 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003532 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003533 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003534
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003535 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003536 getLangOpts(),
3537 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003538 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003539 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003540 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003541 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003542 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003543
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003544 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003545 getLangOpts(),
3546 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003547 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003548 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003549}
3550
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003551//===--- CHECK: Standard memory functions ---------------------------------===//
3552
Douglas Gregor2a053a32011-05-03 20:05:22 +00003553/// \brief Determine whether the given type is a dynamic class type (e.g.,
3554/// whether it has a vtable).
3555static bool isDynamicClassType(QualType T) {
3556 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3557 if (CXXRecordDecl *Definition = Record->getDefinition())
3558 if (Definition->isDynamicClass())
3559 return true;
3560
3561 return false;
3562}
3563
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003564/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003565/// otherwise returns NULL.
3566static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003567 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003568 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3569 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3570 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003571
Chandler Carruth000d4282011-06-16 09:09:40 +00003572 return 0;
3573}
3574
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003575/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003576static QualType getSizeOfArgType(const Expr* E) {
3577 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3578 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3579 if (SizeOf->getKind() == clang::UETT_SizeOf)
3580 return SizeOf->getTypeOfArgument();
3581
3582 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003583}
3584
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003585/// \brief Check for dangerous or invalid arguments to memset().
3586///
Chandler Carruth929f0132011-06-03 06:23:57 +00003587/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003588/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3589/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003590///
3591/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003592void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003593 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003594 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003595 assert(BId != 0);
3596
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003597 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003598 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003599 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003600 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003601 return;
3602
Anna Zaks0a151a12012-01-17 00:37:07 +00003603 unsigned LastArg = (BId == Builtin::BImemset ||
3604 BId == Builtin::BIstrndup ? 1 : 2);
3605 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003606 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003607
3608 // We have special checking when the length is a sizeof expression.
3609 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3610 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3611 llvm::FoldingSetNodeID SizeOfArgID;
3612
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003613 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3614 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003615 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003616
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003617 QualType DestTy = Dest->getType();
3618 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3619 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003620
Chandler Carruth000d4282011-06-16 09:09:40 +00003621 // Never warn about void type pointers. This can be used to suppress
3622 // false positives.
3623 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003624 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003625
Chandler Carruth000d4282011-06-16 09:09:40 +00003626 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3627 // actually comparing the expressions for equality. Because computing the
3628 // expression IDs can be expensive, we only do this if the diagnostic is
3629 // enabled.
3630 if (SizeOfArg &&
3631 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3632 SizeOfArg->getExprLoc())) {
3633 // We only compute IDs for expressions if the warning is enabled, and
3634 // cache the sizeof arg's ID.
3635 if (SizeOfArgID == llvm::FoldingSetNodeID())
3636 SizeOfArg->Profile(SizeOfArgID, Context, true);
3637 llvm::FoldingSetNodeID DestID;
3638 Dest->Profile(DestID, Context, true);
3639 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003640 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3641 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003642 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003643 StringRef ReadableName = FnName->getName();
3644
Chandler Carruth000d4282011-06-16 09:09:40 +00003645 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003646 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003647 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003648 if (!PointeeTy->isIncompleteType() &&
3649 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003650 ActionIdx = 2; // If the pointee's size is sizeof(char),
3651 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003652
3653 // If the function is defined as a builtin macro, do not show macro
3654 // expansion.
3655 SourceLocation SL = SizeOfArg->getExprLoc();
3656 SourceRange DSR = Dest->getSourceRange();
3657 SourceRange SSR = SizeOfArg->getSourceRange();
3658 SourceManager &SM = PP.getSourceManager();
3659
3660 if (SM.isMacroArgExpansion(SL)) {
3661 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3662 SL = SM.getSpellingLoc(SL);
3663 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3664 SM.getSpellingLoc(DSR.getEnd()));
3665 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3666 SM.getSpellingLoc(SSR.getEnd()));
3667 }
3668
Anna Zaks90c78322012-05-30 23:14:52 +00003669 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003670 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003671 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003672 << PointeeTy
3673 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003674 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003675 << SSR);
3676 DiagRuntimeBehavior(SL, SizeOfArg,
3677 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3678 << ActionIdx
3679 << SSR);
3680
Chandler Carruth000d4282011-06-16 09:09:40 +00003681 break;
3682 }
3683 }
3684
3685 // Also check for cases where the sizeof argument is the exact same
3686 // type as the memory argument, and where it points to a user-defined
3687 // record type.
3688 if (SizeOfArgTy != QualType()) {
3689 if (PointeeTy->isRecordType() &&
3690 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3691 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3692 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3693 << FnName << SizeOfArgTy << ArgIdx
3694 << PointeeTy << Dest->getSourceRange()
3695 << LenExpr->getSourceRange());
3696 break;
3697 }
Nico Webere4a1c642011-06-14 16:14:58 +00003698 }
3699
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003700 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003701 if (isDynamicClassType(PointeeTy)) {
3702
3703 unsigned OperationType = 0;
3704 // "overwritten" if we're warning about the destination for any call
3705 // but memcmp; otherwise a verb appropriate to the call.
3706 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3707 if (BId == Builtin::BImemcpy)
3708 OperationType = 1;
3709 else if(BId == Builtin::BImemmove)
3710 OperationType = 2;
3711 else if (BId == Builtin::BImemcmp)
3712 OperationType = 3;
3713 }
3714
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003715 DiagRuntimeBehavior(
3716 Dest->getExprLoc(), Dest,
3717 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003718 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003719 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003720 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003721 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003722 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3723 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003724 DiagRuntimeBehavior(
3725 Dest->getExprLoc(), Dest,
3726 PDiag(diag::warn_arc_object_memaccess)
3727 << ArgIdx << FnName << PointeeTy
3728 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003729 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003730 continue;
John McCallf85e1932011-06-15 23:02:42 +00003731
3732 DiagRuntimeBehavior(
3733 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003734 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003735 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3736 break;
3737 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003738 }
3739}
3740
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003741// A little helper routine: ignore addition and subtraction of integer literals.
3742// This intentionally does not ignore all integer constant expressions because
3743// we don't want to remove sizeof().
3744static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3745 Ex = Ex->IgnoreParenCasts();
3746
3747 for (;;) {
3748 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3749 if (!BO || !BO->isAdditiveOp())
3750 break;
3751
3752 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3753 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3754
3755 if (isa<IntegerLiteral>(RHS))
3756 Ex = LHS;
3757 else if (isa<IntegerLiteral>(LHS))
3758 Ex = RHS;
3759 else
3760 break;
3761 }
3762
3763 return Ex;
3764}
3765
Anna Zaks0f38ace2012-08-08 21:42:23 +00003766static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3767 ASTContext &Context) {
3768 // Only handle constant-sized or VLAs, but not flexible members.
3769 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3770 // Only issue the FIXIT for arrays of size > 1.
3771 if (CAT->getSize().getSExtValue() <= 1)
3772 return false;
3773 } else if (!Ty->isVariableArrayType()) {
3774 return false;
3775 }
3776 return true;
3777}
3778
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003779// Warn if the user has made the 'size' argument to strlcpy or strlcat
3780// be the size of the source, instead of the destination.
3781void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3782 IdentifierInfo *FnName) {
3783
3784 // Don't crash if the user has the wrong number of arguments
3785 if (Call->getNumArgs() != 3)
3786 return;
3787
3788 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3789 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3790 const Expr *CompareWithSrc = NULL;
3791
3792 // Look for 'strlcpy(dst, x, sizeof(x))'
3793 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3794 CompareWithSrc = Ex;
3795 else {
3796 // Look for 'strlcpy(dst, x, strlen(x))'
3797 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003798 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003799 && SizeCall->getNumArgs() == 1)
3800 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3801 }
3802 }
3803
3804 if (!CompareWithSrc)
3805 return;
3806
3807 // Determine if the argument to sizeof/strlen is equal to the source
3808 // argument. In principle there's all kinds of things you could do
3809 // here, for instance creating an == expression and evaluating it with
3810 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3811 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3812 if (!SrcArgDRE)
3813 return;
3814
3815 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3816 if (!CompareWithSrcDRE ||
3817 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3818 return;
3819
3820 const Expr *OriginalSizeArg = Call->getArg(2);
3821 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3822 << OriginalSizeArg->getSourceRange() << FnName;
3823
3824 // Output a FIXIT hint if the destination is an array (rather than a
3825 // pointer to an array). This could be enhanced to handle some
3826 // pointers if we know the actual size, like if DstArg is 'array+2'
3827 // we could say 'sizeof(array)-2'.
3828 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003829 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003830 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003831
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003832 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003833 llvm::raw_svector_ostream OS(sizeString);
3834 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003835 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003836 OS << ")";
3837
3838 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3839 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3840 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003841}
3842
Anna Zaksc36bedc2012-02-01 19:08:57 +00003843/// Check if two expressions refer to the same declaration.
3844static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3845 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3846 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3847 return D1->getDecl() == D2->getDecl();
3848 return false;
3849}
3850
3851static const Expr *getStrlenExprArg(const Expr *E) {
3852 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3853 const FunctionDecl *FD = CE->getDirectCallee();
3854 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3855 return 0;
3856 return CE->getArg(0)->IgnoreParenCasts();
3857 }
3858 return 0;
3859}
3860
3861// Warn on anti-patterns as the 'size' argument to strncat.
3862// The correct size argument should look like following:
3863// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3864void Sema::CheckStrncatArguments(const CallExpr *CE,
3865 IdentifierInfo *FnName) {
3866 // Don't crash if the user has the wrong number of arguments.
3867 if (CE->getNumArgs() < 3)
3868 return;
3869 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3870 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3871 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3872
3873 // Identify common expressions, which are wrongly used as the size argument
3874 // to strncat and may lead to buffer overflows.
3875 unsigned PatternType = 0;
3876 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3877 // - sizeof(dst)
3878 if (referToTheSameDecl(SizeOfArg, DstArg))
3879 PatternType = 1;
3880 // - sizeof(src)
3881 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3882 PatternType = 2;
3883 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3884 if (BE->getOpcode() == BO_Sub) {
3885 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3886 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3887 // - sizeof(dst) - strlen(dst)
3888 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3889 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3890 PatternType = 1;
3891 // - sizeof(src) - (anything)
3892 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3893 PatternType = 2;
3894 }
3895 }
3896
3897 if (PatternType == 0)
3898 return;
3899
Anna Zaksafdb0412012-02-03 01:27:37 +00003900 // Generate the diagnostic.
3901 SourceLocation SL = LenArg->getLocStart();
3902 SourceRange SR = LenArg->getSourceRange();
3903 SourceManager &SM = PP.getSourceManager();
3904
3905 // If the function is defined as a builtin macro, do not show macro expansion.
3906 if (SM.isMacroArgExpansion(SL)) {
3907 SL = SM.getSpellingLoc(SL);
3908 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3909 SM.getSpellingLoc(SR.getEnd()));
3910 }
3911
Anna Zaks0f38ace2012-08-08 21:42:23 +00003912 // Check if the destination is an array (rather than a pointer to an array).
3913 QualType DstTy = DstArg->getType();
3914 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3915 Context);
3916 if (!isKnownSizeArray) {
3917 if (PatternType == 1)
3918 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3919 else
3920 Diag(SL, diag::warn_strncat_src_size) << SR;
3921 return;
3922 }
3923
Anna Zaksc36bedc2012-02-01 19:08:57 +00003924 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003925 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003926 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003927 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003928
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003929 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003930 llvm::raw_svector_ostream OS(sizeString);
3931 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003932 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003933 OS << ") - ";
3934 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003935 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003936 OS << ") - 1";
3937
Anna Zaksafdb0412012-02-03 01:27:37 +00003938 Diag(SL, diag::note_strncat_wrong_size)
3939 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003940}
3941
Ted Kremenek06de2762007-08-17 16:46:58 +00003942//===--- CHECK: Return Address of Stack Variable --------------------------===//
3943
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003944static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3945 Decl *ParentDecl);
3946static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3947 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003948
3949/// CheckReturnStackAddr - Check if a return statement returns the address
3950/// of a stack variable.
3951void
3952Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3953 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003954
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003955 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003956 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003957
3958 // Perform checking for returned stack addresses, local blocks,
3959 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003960 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003961 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003962 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003963 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003964 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003965 }
3966
3967 if (stackE == 0)
3968 return; // Nothing suspicious was found.
3969
3970 SourceLocation diagLoc;
3971 SourceRange diagRange;
3972 if (refVars.empty()) {
3973 diagLoc = stackE->getLocStart();
3974 diagRange = stackE->getSourceRange();
3975 } else {
3976 // We followed through a reference variable. 'stackE' contains the
3977 // problematic expression but we will warn at the return statement pointing
3978 // at the reference variable. We will later display the "trail" of
3979 // reference variables using notes.
3980 diagLoc = refVars[0]->getLocStart();
3981 diagRange = refVars[0]->getSourceRange();
3982 }
3983
3984 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3985 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3986 : diag::warn_ret_stack_addr)
3987 << DR->getDecl()->getDeclName() << diagRange;
3988 } else if (isa<BlockExpr>(stackE)) { // local block.
3989 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3990 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3991 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3992 } else { // local temporary.
3993 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3994 : diag::warn_ret_local_temp_addr)
3995 << diagRange;
3996 }
3997
3998 // Display the "trail" of reference variables that we followed until we
3999 // found the problematic expression using notes.
4000 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4001 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4002 // If this var binds to another reference var, show the range of the next
4003 // var, otherwise the var binds to the problematic expression, in which case
4004 // show the range of the expression.
4005 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4006 : stackE->getSourceRange();
4007 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4008 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00004009 }
4010}
4011
4012/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4013/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004014/// to a location on the stack, a local block, an address of a label, or a
4015/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00004016/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004017/// encounter a subexpression that (1) clearly does not lead to one of the
4018/// above problematic expressions (2) is something we cannot determine leads to
4019/// a problematic expression based on such local checking.
4020///
4021/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4022/// the expression that they point to. Such variables are added to the
4023/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00004024///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004025/// EvalAddr processes expressions that are pointers that are used as
4026/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004027/// At the base case of the recursion is a check for the above problematic
4028/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00004029///
4030/// This implementation handles:
4031///
4032/// * pointer-to-pointer casts
4033/// * implicit conversions from array references to pointers
4034/// * taking the address of fields
4035/// * arbitrary interplay between "&" and "*" operators
4036/// * pointer arithmetic from an address of a stack variable
4037/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004038static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4039 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004040 if (E->isTypeDependent())
Craig Topperb61c2942013-08-02 05:10:31 +00004041 return NULL;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004042
Ted Kremenek06de2762007-08-17 16:46:58 +00004043 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00004044 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00004045 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004046 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004047 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00004048
Peter Collingbournef111d932011-04-15 00:35:48 +00004049 E = E->IgnoreParens();
4050
Ted Kremenek06de2762007-08-17 16:46:58 +00004051 // Our "symbolic interpreter" is just a dispatch off the currently
4052 // viewed AST node. We then recursively traverse the AST by calling
4053 // EvalAddr and EvalVal appropriately.
4054 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004055 case Stmt::DeclRefExprClass: {
4056 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4057
4058 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4059 // If this is a reference variable, follow through to the expression that
4060 // it points to.
4061 if (V->hasLocalStorage() &&
4062 V->getType()->isReferenceType() && V->hasInit()) {
4063 // Add the reference variable to the "trail".
4064 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004065 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004066 }
4067
4068 return NULL;
4069 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004070
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004071 case Stmt::UnaryOperatorClass: {
4072 // The only unary operator that make sense to handle here
4073 // is AddrOf. All others don't make sense as pointers.
4074 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004075
John McCall2de56d12010-08-25 11:45:40 +00004076 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004077 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004078 else
Ted Kremenek06de2762007-08-17 16:46:58 +00004079 return NULL;
4080 }
Mike Stump1eb44332009-09-09 15:08:12 +00004081
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004082 case Stmt::BinaryOperatorClass: {
4083 // Handle pointer arithmetic. All other binary operators are not valid
4084 // in this context.
4085 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00004086 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00004087
John McCall2de56d12010-08-25 11:45:40 +00004088 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004089 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00004090
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004091 Expr *Base = B->getLHS();
4092
4093 // Determine which argument is the real pointer base. It could be
4094 // the RHS argument instead of the LHS.
4095 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00004096
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004097 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004098 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004099 }
Steve Naroff61f40a22008-09-10 19:17:48 +00004100
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004101 // For conditional operators we need to see if either the LHS or RHS are
4102 // valid DeclRefExpr*s. If one of them is valid, we return it.
4103 case Stmt::ConditionalOperatorClass: {
4104 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004105
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004106 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004107 if (Expr *lhsExpr = C->getLHS()) {
4108 // In C++, we can have a throw-expression, which has 'void' type.
4109 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004110 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004111 return LHS;
4112 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004113
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004114 // In C++, we can have a throw-expression, which has 'void' type.
4115 if (C->getRHS()->getType()->isVoidType())
4116 return NULL;
4117
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004118 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004119 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004120
4121 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004122 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004123 return E; // local block.
4124 return NULL;
4125
4126 case Stmt::AddrLabelExprClass:
4127 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004128
John McCall80ee6e82011-11-10 05:35:25 +00004129 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004130 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4131 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004132
Ted Kremenek54b52742008-08-07 00:49:01 +00004133 // For casts, we need to handle conversions from arrays to
4134 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004135 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004136 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004137 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004138 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004139 case Stmt::CXXStaticCastExprClass:
4140 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004141 case Stmt::CXXConstCastExprClass:
4142 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004143 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4144 switch (cast<CastExpr>(E)->getCastKind()) {
4145 case CK_BitCast:
4146 case CK_LValueToRValue:
4147 case CK_NoOp:
4148 case CK_BaseToDerived:
4149 case CK_DerivedToBase:
4150 case CK_UncheckedDerivedToBase:
4151 case CK_Dynamic:
4152 case CK_CPointerToObjCPointerCast:
4153 case CK_BlockPointerToObjCPointerCast:
4154 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004155 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004156
4157 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004158 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004159
4160 default:
4161 return 0;
4162 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004163 }
Mike Stump1eb44332009-09-09 15:08:12 +00004164
Douglas Gregor03e80032011-06-21 17:03:29 +00004165 case Stmt::MaterializeTemporaryExprClass:
4166 if (Expr *Result = EvalAddr(
4167 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004168 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004169 return Result;
4170
4171 return E;
4172
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004173 // Everything else: we simply don't reason about them.
4174 default:
4175 return NULL;
4176 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004177}
Mike Stump1eb44332009-09-09 15:08:12 +00004178
Ted Kremenek06de2762007-08-17 16:46:58 +00004179
4180/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4181/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004182static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4183 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004184do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004185 // We should only be called for evaluating non-pointer expressions, or
4186 // expressions with a pointer type that are not used as references but instead
4187 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00004188
Ted Kremenek06de2762007-08-17 16:46:58 +00004189 // Our "symbolic interpreter" is just a dispatch off the currently
4190 // viewed AST node. We then recursively traverse the AST by calling
4191 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00004192
4193 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00004194 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004195 case Stmt::ImplicitCastExprClass: {
4196 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00004197 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004198 E = IE->getSubExpr();
4199 continue;
4200 }
4201 return NULL;
4202 }
4203
John McCall80ee6e82011-11-10 05:35:25 +00004204 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004205 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004206
Douglas Gregora2813ce2009-10-23 18:54:35 +00004207 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004208 // When we hit a DeclRefExpr we are looking at code that refers to a
4209 // variable's name. If it's not a reference variable we check if it has
4210 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00004211 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004212
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004213 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4214 // Check if it refers to itself, e.g. "int& i = i;".
4215 if (V == ParentDecl)
4216 return DR;
4217
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004218 if (V->hasLocalStorage()) {
4219 if (!V->getType()->isReferenceType())
4220 return DR;
4221
4222 // Reference variable, follow through to the expression that
4223 // it points to.
4224 if (V->hasInit()) {
4225 // Add the reference variable to the "trail".
4226 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004227 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004228 }
4229 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004230 }
Mike Stump1eb44332009-09-09 15:08:12 +00004231
Ted Kremenek06de2762007-08-17 16:46:58 +00004232 return NULL;
4233 }
Mike Stump1eb44332009-09-09 15:08:12 +00004234
Ted Kremenek06de2762007-08-17 16:46:58 +00004235 case Stmt::UnaryOperatorClass: {
4236 // The only unary operator that make sense to handle here
4237 // is Deref. All others don't resolve to a "name." This includes
4238 // handling all sorts of rvalues passed to a unary operator.
4239 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004240
John McCall2de56d12010-08-25 11:45:40 +00004241 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004242 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004243
4244 return NULL;
4245 }
Mike Stump1eb44332009-09-09 15:08:12 +00004246
Ted Kremenek06de2762007-08-17 16:46:58 +00004247 case Stmt::ArraySubscriptExprClass: {
4248 // Array subscripts are potential references to data on the stack. We
4249 // retrieve the DeclRefExpr* for the array variable if it indeed
4250 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004251 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004252 }
Mike Stump1eb44332009-09-09 15:08:12 +00004253
Ted Kremenek06de2762007-08-17 16:46:58 +00004254 case Stmt::ConditionalOperatorClass: {
4255 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004256 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00004257 ConditionalOperator *C = cast<ConditionalOperator>(E);
4258
Anders Carlsson39073232007-11-30 19:04:31 +00004259 // Handle the GNU extension for missing LHS.
4260 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004261 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00004262 return LHS;
4263
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004264 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004265 }
Mike Stump1eb44332009-09-09 15:08:12 +00004266
Ted Kremenek06de2762007-08-17 16:46:58 +00004267 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00004268 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00004269 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004270
Ted Kremenek06de2762007-08-17 16:46:58 +00004271 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00004272 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00004273 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00004274
4275 // Check whether the member type is itself a reference, in which case
4276 // we're not going to refer to the member, but to what the member refers to.
4277 if (M->getMemberDecl()->getType()->isReferenceType())
4278 return NULL;
4279
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004280 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004281 }
Mike Stump1eb44332009-09-09 15:08:12 +00004282
Douglas Gregor03e80032011-06-21 17:03:29 +00004283 case Stmt::MaterializeTemporaryExprClass:
4284 if (Expr *Result = EvalVal(
4285 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004286 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004287 return Result;
4288
4289 return E;
4290
Ted Kremenek06de2762007-08-17 16:46:58 +00004291 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004292 // Check that we don't return or take the address of a reference to a
4293 // temporary. This is only useful in C++.
4294 if (!E->isTypeDependent() && E->isRValue())
4295 return E;
4296
4297 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00004298 return NULL;
4299 }
Ted Kremenek68957a92010-08-04 20:01:07 +00004300} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00004301}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004302
4303//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4304
4305/// Check for comparisons of floating point operands using != and ==.
4306/// Issue a warning if these are no self-comparisons, as they are not likely
4307/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00004308void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00004309 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4310 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004311
4312 // Special case: check for x == x (which is OK).
4313 // Do not emit warnings for such cases.
4314 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4315 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4316 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004317 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004318
4319
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004320 // Special case: check for comparisons against literals that can be exactly
4321 // represented by APFloat. In such cases, do not emit a warning. This
4322 // is a heuristic: often comparison against such literals are used to
4323 // detect if a value in a variable has not changed. This clearly can
4324 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004325 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4326 if (FLL->isExact())
4327 return;
4328 } else
4329 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4330 if (FLR->isExact())
4331 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004332
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004333 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004334 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4335 if (CL->isBuiltinCall())
4336 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004337
David Blaikie980343b2012-07-16 20:47:22 +00004338 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4339 if (CR->isBuiltinCall())
4340 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004341
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004342 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004343 Diag(Loc, diag::warn_floatingpoint_eq)
4344 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004345}
John McCallba26e582010-01-04 23:21:16 +00004346
John McCallf2370c92010-01-06 05:24:50 +00004347//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4348//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004349
John McCallf2370c92010-01-06 05:24:50 +00004350namespace {
John McCallba26e582010-01-04 23:21:16 +00004351
John McCallf2370c92010-01-06 05:24:50 +00004352/// Structure recording the 'active' range of an integer-valued
4353/// expression.
4354struct IntRange {
4355 /// The number of bits active in the int.
4356 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004357
John McCallf2370c92010-01-06 05:24:50 +00004358 /// True if the int is known not to have negative values.
4359 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004360
John McCallf2370c92010-01-06 05:24:50 +00004361 IntRange(unsigned Width, bool NonNegative)
4362 : Width(Width), NonNegative(NonNegative)
4363 {}
John McCallba26e582010-01-04 23:21:16 +00004364
John McCall1844a6e2010-11-10 23:38:19 +00004365 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004366 static IntRange forBoolType() {
4367 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004368 }
4369
John McCall1844a6e2010-11-10 23:38:19 +00004370 /// Returns the range of an opaque value of the given integral type.
4371 static IntRange forValueOfType(ASTContext &C, QualType T) {
4372 return forValueOfCanonicalType(C,
4373 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004374 }
4375
John McCall1844a6e2010-11-10 23:38:19 +00004376 /// Returns the range of an opaque value of a canonical integral type.
4377 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004378 assert(T->isCanonicalUnqualified());
4379
4380 if (const VectorType *VT = dyn_cast<VectorType>(T))
4381 T = VT->getElementType().getTypePtr();
4382 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4383 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004384
David Majnemerf9eaf982013-06-07 22:07:20 +00004385 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004386 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004387 EnumDecl *Enum = ET->getDecl();
4388 if (!Enum->isCompleteDefinition())
4389 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004390
David Majnemerf9eaf982013-06-07 22:07:20 +00004391 unsigned NumPositive = Enum->getNumPositiveBits();
4392 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004393
David Majnemerf9eaf982013-06-07 22:07:20 +00004394 if (NumNegative == 0)
4395 return IntRange(NumPositive, true/*NonNegative*/);
4396 else
4397 return IntRange(std::max(NumPositive + 1, NumNegative),
4398 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004399 }
John McCallf2370c92010-01-06 05:24:50 +00004400
4401 const BuiltinType *BT = cast<BuiltinType>(T);
4402 assert(BT->isInteger());
4403
4404 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4405 }
4406
John McCall1844a6e2010-11-10 23:38:19 +00004407 /// Returns the "target" range of a canonical integral type, i.e.
4408 /// the range of values expressible in the type.
4409 ///
4410 /// This matches forValueOfCanonicalType except that enums have the
4411 /// full range of their type, not the range of their enumerators.
4412 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4413 assert(T->isCanonicalUnqualified());
4414
4415 if (const VectorType *VT = dyn_cast<VectorType>(T))
4416 T = VT->getElementType().getTypePtr();
4417 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4418 T = CT->getElementType().getTypePtr();
4419 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004420 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004421
4422 const BuiltinType *BT = cast<BuiltinType>(T);
4423 assert(BT->isInteger());
4424
4425 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4426 }
4427
4428 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004429 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004430 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004431 L.NonNegative && R.NonNegative);
4432 }
4433
John McCall1844a6e2010-11-10 23:38:19 +00004434 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004435 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004436 return IntRange(std::min(L.Width, R.Width),
4437 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004438 }
4439};
4440
Ted Kremenek0692a192012-01-31 05:37:37 +00004441static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4442 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004443 if (value.isSigned() && value.isNegative())
4444 return IntRange(value.getMinSignedBits(), false);
4445
4446 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004447 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004448
4449 // isNonNegative() just checks the sign bit without considering
4450 // signedness.
4451 return IntRange(value.getActiveBits(), true);
4452}
4453
Ted Kremenek0692a192012-01-31 05:37:37 +00004454static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4455 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004456 if (result.isInt())
4457 return GetValueRange(C, result.getInt(), MaxWidth);
4458
4459 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004460 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4461 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4462 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4463 R = IntRange::join(R, El);
4464 }
John McCallf2370c92010-01-06 05:24:50 +00004465 return R;
4466 }
4467
4468 if (result.isComplexInt()) {
4469 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4470 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4471 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004472 }
4473
4474 // This can happen with lossless casts to intptr_t of "based" lvalues.
4475 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004476 // FIXME: The only reason we need to pass the type in here is to get
4477 // the sign right on this one case. It would be nice if APValue
4478 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004479 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004480 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004481}
John McCallf2370c92010-01-06 05:24:50 +00004482
Eli Friedman09bddcf2013-07-08 20:20:06 +00004483static QualType GetExprType(Expr *E) {
4484 QualType Ty = E->getType();
4485 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4486 Ty = AtomicRHS->getValueType();
4487 return Ty;
4488}
4489
John McCallf2370c92010-01-06 05:24:50 +00004490/// Pseudo-evaluate the given integer expression, estimating the
4491/// range of values it might take.
4492///
4493/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004494static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004495 E = E->IgnoreParens();
4496
4497 // Try a full evaluation first.
4498 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004499 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004500 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004501
4502 // I think we only want to look through implicit casts here; if the
4503 // user has an explicit widening cast, we should treat the value as
4504 // being of the new, wider type.
4505 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004506 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004507 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4508
Eli Friedman09bddcf2013-07-08 20:20:06 +00004509 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004510
John McCall2de56d12010-08-25 11:45:40 +00004511 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004512
John McCallf2370c92010-01-06 05:24:50 +00004513 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004514 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004515 return OutputTypeRange;
4516
4517 IntRange SubRange
4518 = GetExprRange(C, CE->getSubExpr(),
4519 std::min(MaxWidth, OutputTypeRange.Width));
4520
4521 // Bail out if the subexpr's range is as wide as the cast type.
4522 if (SubRange.Width >= OutputTypeRange.Width)
4523 return OutputTypeRange;
4524
4525 // Otherwise, we take the smaller width, and we're non-negative if
4526 // either the output type or the subexpr is.
4527 return IntRange(SubRange.Width,
4528 SubRange.NonNegative || OutputTypeRange.NonNegative);
4529 }
4530
4531 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4532 // If we can fold the condition, just take that operand.
4533 bool CondResult;
4534 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4535 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4536 : CO->getFalseExpr(),
4537 MaxWidth);
4538
4539 // Otherwise, conservatively merge.
4540 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4541 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4542 return IntRange::join(L, R);
4543 }
4544
4545 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4546 switch (BO->getOpcode()) {
4547
4548 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004549 case BO_LAnd:
4550 case BO_LOr:
4551 case BO_LT:
4552 case BO_GT:
4553 case BO_LE:
4554 case BO_GE:
4555 case BO_EQ:
4556 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004557 return IntRange::forBoolType();
4558
John McCall862ff872011-07-13 06:35:24 +00004559 // The type of the assignments is the type of the LHS, so the RHS
4560 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004561 case BO_MulAssign:
4562 case BO_DivAssign:
4563 case BO_RemAssign:
4564 case BO_AddAssign:
4565 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004566 case BO_XorAssign:
4567 case BO_OrAssign:
4568 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00004569 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00004570
John McCall862ff872011-07-13 06:35:24 +00004571 // Simple assignments just pass through the RHS, which will have
4572 // been coerced to the LHS type.
4573 case BO_Assign:
4574 // TODO: bitfields?
4575 return GetExprRange(C, BO->getRHS(), MaxWidth);
4576
John McCallf2370c92010-01-06 05:24:50 +00004577 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004578 case BO_PtrMemD:
4579 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004580 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004581
John McCall60fad452010-01-06 22:07:33 +00004582 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004583 case BO_And:
4584 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004585 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4586 GetExprRange(C, BO->getRHS(), MaxWidth));
4587
John McCallf2370c92010-01-06 05:24:50 +00004588 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004589 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004590 // ...except that we want to treat '1 << (blah)' as logically
4591 // positive. It's an important idiom.
4592 if (IntegerLiteral *I
4593 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4594 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004595 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00004596 return IntRange(R.Width, /*NonNegative*/ true);
4597 }
4598 }
4599 // fallthrough
4600
John McCall2de56d12010-08-25 11:45:40 +00004601 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004602 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004603
John McCall60fad452010-01-06 22:07:33 +00004604 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004605 case BO_Shr:
4606 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004607 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4608
4609 // If the shift amount is a positive constant, drop the width by
4610 // that much.
4611 llvm::APSInt shift;
4612 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4613 shift.isNonNegative()) {
4614 unsigned zext = shift.getZExtValue();
4615 if (zext >= L.Width)
4616 L.Width = (L.NonNegative ? 0 : 1);
4617 else
4618 L.Width -= zext;
4619 }
4620
4621 return L;
4622 }
4623
4624 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004625 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004626 return GetExprRange(C, BO->getRHS(), MaxWidth);
4627
John McCall60fad452010-01-06 22:07:33 +00004628 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004629 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004630 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00004631 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004632 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004633
John McCall00fe7612011-07-14 22:39:48 +00004634 // The width of a division result is mostly determined by the size
4635 // of the LHS.
4636 case BO_Div: {
4637 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004638 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004639 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4640
4641 // If the divisor is constant, use that.
4642 llvm::APSInt divisor;
4643 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4644 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4645 if (log2 >= L.Width)
4646 L.Width = (L.NonNegative ? 0 : 1);
4647 else
4648 L.Width = std::min(L.Width - log2, MaxWidth);
4649 return L;
4650 }
4651
4652 // Otherwise, just use the LHS's width.
4653 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4654 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4655 }
4656
4657 // The result of a remainder can't be larger than the result of
4658 // either side.
4659 case BO_Rem: {
4660 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004661 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004662 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4663 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4664
4665 IntRange meet = IntRange::meet(L, R);
4666 meet.Width = std::min(meet.Width, MaxWidth);
4667 return meet;
4668 }
4669
4670 // The default behavior is okay for these.
4671 case BO_Mul:
4672 case BO_Add:
4673 case BO_Xor:
4674 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004675 break;
4676 }
4677
John McCall00fe7612011-07-14 22:39:48 +00004678 // The default case is to treat the operation as if it were closed
4679 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004680 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4681 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4682 return IntRange::join(L, R);
4683 }
4684
4685 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4686 switch (UO->getOpcode()) {
4687 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004688 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004689 return IntRange::forBoolType();
4690
4691 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004692 case UO_Deref:
4693 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00004694 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004695
4696 default:
4697 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4698 }
4699 }
4700
Ted Kremenek728a1fb2013-10-14 18:55:27 +00004701 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4702 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4703
John McCall993f43f2013-05-06 21:39:12 +00004704 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004705 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004706 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004707
Eli Friedman09bddcf2013-07-08 20:20:06 +00004708 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004709}
John McCall51313c32010-01-04 23:31:57 +00004710
Ted Kremenek0692a192012-01-31 05:37:37 +00004711static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004712 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00004713}
4714
John McCall51313c32010-01-04 23:31:57 +00004715/// Checks whether the given value, which currently has the given
4716/// source semantics, has the same value when coerced through the
4717/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004718static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4719 const llvm::fltSemantics &Src,
4720 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004721 llvm::APFloat truncated = value;
4722
4723 bool ignored;
4724 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4725 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4726
4727 return truncated.bitwiseIsEqual(value);
4728}
4729
4730/// Checks whether the given value, which currently has the given
4731/// source semantics, has the same value when coerced through the
4732/// target semantics.
4733///
4734/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004735static bool IsSameFloatAfterCast(const APValue &value,
4736 const llvm::fltSemantics &Src,
4737 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004738 if (value.isFloat())
4739 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4740
4741 if (value.isVector()) {
4742 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4743 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4744 return false;
4745 return true;
4746 }
4747
4748 assert(value.isComplexFloat());
4749 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4750 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4751}
4752
Ted Kremenek0692a192012-01-31 05:37:37 +00004753static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004754
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004755static bool IsZero(Sema &S, Expr *E) {
4756 // Suppress cases where we are comparing against an enum constant.
4757 if (const DeclRefExpr *DR =
4758 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4759 if (isa<EnumConstantDecl>(DR->getDecl()))
4760 return false;
4761
4762 // Suppress cases where the '0' value is expanded from a macro.
4763 if (E->getLocStart().isMacroID())
4764 return false;
4765
John McCall323ed742010-05-06 08:58:33 +00004766 llvm::APSInt Value;
4767 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4768}
4769
John McCall372e1032010-10-06 00:25:24 +00004770static bool HasEnumType(Expr *E) {
4771 // Strip off implicit integral promotions.
4772 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004773 if (ICE->getCastKind() != CK_IntegralCast &&
4774 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004775 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004776 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004777 }
4778
4779 return E->getType()->isEnumeralType();
4780}
4781
Ted Kremenek0692a192012-01-31 05:37:37 +00004782static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieucbc19872013-11-01 21:47:19 +00004783 // Disable warning in template instantiations.
4784 if (!S.ActiveTemplateInstantiations.empty())
4785 return;
4786
John McCall2de56d12010-08-25 11:45:40 +00004787 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004788 if (E->isValueDependent())
4789 return;
4790
John McCall2de56d12010-08-25 11:45:40 +00004791 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004792 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004793 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004794 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004795 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004796 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004797 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004798 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004799 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004800 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004801 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004802 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004803 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004804 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004805 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004806 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4807 }
4808}
4809
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004810static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004811 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004812 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004813 bool RhsConstant) {
Richard Trieu311cb2b2013-11-01 21:19:43 +00004814 // Disable warning in template instantiations.
4815 if (!S.ActiveTemplateInstantiations.empty())
4816 return;
4817
Richard Trieu526e6272012-11-14 22:50:24 +00004818 // 0 values are handled later by CheckTrivialUnsignedComparison().
4819 if (Value == 0)
4820 return;
4821
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004822 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004823 QualType OtherT = Other->getType();
4824 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004825 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004826 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004827 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004828 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004829 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004830
4831 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004832 bool CommonSigned = CommonT->isSignedIntegerType();
4833
4834 bool EqualityOnly = false;
4835
4836 // TODO: Investigate using GetExprRange() to get tighter bounds on
4837 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004838 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004839 unsigned OtherWidth = OtherRange.Width;
4840
4841 if (CommonSigned) {
4842 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004843 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004844 // Check that the constant is representable in type OtherT.
4845 if (ConstantSigned) {
4846 if (OtherWidth >= Value.getMinSignedBits())
4847 return;
4848 } else { // !ConstantSigned
4849 if (OtherWidth >= Value.getActiveBits() + 1)
4850 return;
4851 }
4852 } else { // !OtherSigned
4853 // Check that the constant is representable in type OtherT.
4854 // Negative values are out of range.
4855 if (ConstantSigned) {
4856 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4857 return;
4858 } else { // !ConstantSigned
4859 if (OtherWidth >= Value.getActiveBits())
4860 return;
4861 }
4862 }
4863 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004864 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004865 if (OtherWidth >= Value.getActiveBits())
4866 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004867 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004868 // Check to see if the constant is representable in OtherT.
4869 if (OtherWidth > Value.getActiveBits())
4870 return;
4871 // Check to see if the constant is equivalent to a negative value
4872 // cast to CommonT.
4873 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004874 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004875 return;
4876 // The constant value rests between values that OtherT can represent after
4877 // conversion. Relational comparison still works, but equality
4878 // comparisons will be tautological.
4879 EqualityOnly = true;
4880 } else { // OtherSigned && ConstantSigned
4881 assert(0 && "Two signed types converted to unsigned types.");
4882 }
4883 }
4884
4885 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4886
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004887 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004888 if (op == BO_EQ || op == BO_NE) {
4889 IsTrue = op == BO_NE;
4890 } else if (EqualityOnly) {
4891 return;
4892 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004893 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004894 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004895 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004896 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004897 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004898 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004899 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004900 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004901 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004902 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004903
4904 // If this is a comparison to an enum constant, include that
4905 // constant in the diagnostic.
4906 const EnumConstantDecl *ED = 0;
4907 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4908 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4909
4910 SmallString<64> PrettySourceValue;
4911 llvm::raw_svector_ostream OS(PrettySourceValue);
4912 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004913 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004914 else
4915 OS << Value;
4916
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004917 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004918 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004919 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004920}
4921
John McCall323ed742010-05-06 08:58:33 +00004922/// Analyze the operands of the given comparison. Implements the
4923/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004924static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004925 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4926 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004927}
John McCall51313c32010-01-04 23:31:57 +00004928
John McCallba26e582010-01-04 23:21:16 +00004929/// \brief Implements -Wsign-compare.
4930///
Richard Trieudd225092011-09-15 21:56:47 +00004931/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004932static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004933 // The type the comparison is being performed in.
4934 QualType T = E->getLHS()->getType();
4935 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4936 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004937 if (E->isValueDependent())
4938 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004939
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004940 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4941 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004942
4943 bool IsComparisonConstant = false;
4944
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004945 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004946 // of 'true' or 'false'.
4947 if (T->isIntegralType(S.Context)) {
4948 llvm::APSInt RHSValue;
4949 bool IsRHSIntegralLiteral =
4950 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4951 llvm::APSInt LHSValue;
4952 bool IsLHSIntegralLiteral =
4953 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4954 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4955 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4956 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4957 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4958 else
4959 IsComparisonConstant =
4960 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004961 } else if (!T->hasUnsignedIntegerRepresentation())
4962 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004963
John McCall323ed742010-05-06 08:58:33 +00004964 // We don't do anything special if this isn't an unsigned integral
4965 // comparison: we're only interested in integral comparisons, and
4966 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004967 //
4968 // We also don't care about value-dependent expressions or expressions
4969 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004970 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004971 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004972
John McCall323ed742010-05-06 08:58:33 +00004973 // Check to see if one of the (unmodified) operands is of different
4974 // signedness.
4975 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004976 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4977 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004978 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004979 signedOperand = LHS;
4980 unsignedOperand = RHS;
4981 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4982 signedOperand = RHS;
4983 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004984 } else {
John McCall323ed742010-05-06 08:58:33 +00004985 CheckTrivialUnsignedComparison(S, E);
4986 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004987 }
4988
John McCall323ed742010-05-06 08:58:33 +00004989 // Otherwise, calculate the effective range of the signed operand.
4990 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004991
John McCall323ed742010-05-06 08:58:33 +00004992 // Go ahead and analyze implicit conversions in the operands. Note
4993 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004994 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4995 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004996
John McCall323ed742010-05-06 08:58:33 +00004997 // If the signed range is non-negative, -Wsign-compare won't fire,
4998 // but we should still check for comparisons which are always true
4999 // or false.
5000 if (signedRange.NonNegative)
5001 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00005002
5003 // For (in)equality comparisons, if the unsigned operand is a
5004 // constant which cannot collide with a overflowed signed operand,
5005 // then reinterpreting the signed operand as unsigned will not
5006 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00005007 if (E->isEqualityOp()) {
5008 unsigned comparisonWidth = S.Context.getIntWidth(T);
5009 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00005010
John McCall323ed742010-05-06 08:58:33 +00005011 // We should never be unable to prove that the unsigned operand is
5012 // non-negative.
5013 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5014
5015 if (unsignedRange.Width < comparisonWidth)
5016 return;
5017 }
5018
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00005019 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5020 S.PDiag(diag::warn_mixed_sign_comparison)
5021 << LHS->getType() << RHS->getType()
5022 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00005023}
5024
John McCall15d7d122010-11-11 03:21:53 +00005025/// Analyzes an attempt to assign the given value to a bitfield.
5026///
5027/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00005028static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5029 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00005030 assert(Bitfield->isBitField());
5031 if (Bitfield->isInvalidDecl())
5032 return false;
5033
John McCall91b60142010-11-11 05:33:51 +00005034 // White-list bool bitfields.
5035 if (Bitfield->getType()->isBooleanType())
5036 return false;
5037
Douglas Gregor46ff3032011-02-04 13:09:01 +00005038 // Ignore value- or type-dependent expressions.
5039 if (Bitfield->getBitWidth()->isValueDependent() ||
5040 Bitfield->getBitWidth()->isTypeDependent() ||
5041 Init->isValueDependent() ||
5042 Init->isTypeDependent())
5043 return false;
5044
John McCall15d7d122010-11-11 03:21:53 +00005045 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5046
Richard Smith80d4b552011-12-28 19:48:30 +00005047 llvm::APSInt Value;
5048 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00005049 return false;
5050
John McCall15d7d122010-11-11 03:21:53 +00005051 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005052 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00005053
5054 if (OriginalWidth <= FieldWidth)
5055 return false;
5056
Eli Friedman3a643af2012-01-26 23:11:39 +00005057 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005058 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00005059 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00005060
Eli Friedman3a643af2012-01-26 23:11:39 +00005061 // Check whether the stored value is equal to the original value.
5062 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00005063 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00005064 return false;
5065
Eli Friedman3a643af2012-01-26 23:11:39 +00005066 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00005067 // therefore don't strictly fit into a signed bitfield of width 1.
5068 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00005069 return false;
5070
John McCall15d7d122010-11-11 03:21:53 +00005071 std::string PrettyValue = Value.toString(10);
5072 std::string PrettyTrunc = TruncatedValue.toString(10);
5073
5074 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5075 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5076 << Init->getSourceRange();
5077
5078 return true;
5079}
5080
John McCallbeb22aa2010-11-09 23:24:47 +00005081/// Analyze the given simple or compound assignment for warning-worthy
5082/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00005083static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00005084 // Just recurse on the LHS.
5085 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5086
5087 // We want to recurse on the RHS as normal unless we're assigning to
5088 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00005089 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005090 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00005091 E->getOperatorLoc())) {
5092 // Recurse, ignoring any implicit conversions on the RHS.
5093 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5094 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00005095 }
5096 }
5097
5098 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5099}
5100
John McCall51313c32010-01-04 23:31:57 +00005101/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005102static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005103 SourceLocation CContext, unsigned diag,
5104 bool pruneControlFlow = false) {
5105 if (pruneControlFlow) {
5106 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5107 S.PDiag(diag)
5108 << SourceType << T << E->getSourceRange()
5109 << SourceRange(CContext));
5110 return;
5111 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005112 S.Diag(E->getExprLoc(), diag)
5113 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5114}
5115
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005116/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005117static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005118 SourceLocation CContext, unsigned diag,
5119 bool pruneControlFlow = false) {
5120 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005121}
5122
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005123/// Diagnose an implicit cast from a literal expression. Does not warn when the
5124/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005125void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5126 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005127 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005128 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005129 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00005130 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5131 T->hasUnsignedIntegerRepresentation());
5132 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00005133 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005134 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00005135 return;
5136
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005137 // FIXME: Force the precision of the source value down so we don't print
5138 // digits which are usually useless (we don't really care here if we
5139 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5140 // would automatically print the shortest representation, but it's a bit
5141 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00005142 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005143 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5144 precision = (precision * 59 + 195) / 196;
5145 Value.toString(PrettySourceValue, precision);
5146
David Blaikiede7e7b82012-05-15 17:18:27 +00005147 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00005148 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5149 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5150 else
David Blaikiede7e7b82012-05-15 17:18:27 +00005151 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00005152
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005153 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00005154 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5155 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00005156}
5157
John McCall091f23f2010-11-09 22:22:12 +00005158std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5159 if (!Range.Width) return "0";
5160
5161 llvm::APSInt ValueInRange = Value;
5162 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00005163 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00005164 return ValueInRange.toString(10);
5165}
5166
Hans Wennborg88617a22012-08-28 15:44:30 +00005167static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5168 if (!isa<ImplicitCastExpr>(Ex))
5169 return false;
5170
5171 Expr *InnerE = Ex->IgnoreParenImpCasts();
5172 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5173 const Type *Source =
5174 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5175 if (Target->isDependentType())
5176 return false;
5177
5178 const BuiltinType *FloatCandidateBT =
5179 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5180 const Type *BoolCandidateType = ToBool ? Target : Source;
5181
5182 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5183 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5184}
5185
5186void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5187 SourceLocation CC) {
5188 unsigned NumArgs = TheCall->getNumArgs();
5189 for (unsigned i = 0; i < NumArgs; ++i) {
5190 Expr *CurrA = TheCall->getArg(i);
5191 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5192 continue;
5193
5194 bool IsSwapped = ((i > 0) &&
5195 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5196 IsSwapped |= ((i < (NumArgs - 1)) &&
5197 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5198 if (IsSwapped) {
5199 // Warn on this floating-point to bool conversion.
5200 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5201 CurrA->getType(), CC,
5202 diag::warn_impcast_floating_point_to_bool);
5203 }
5204 }
5205}
5206
John McCall323ed742010-05-06 08:58:33 +00005207void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005208 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00005209 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00005210
John McCall323ed742010-05-06 08:58:33 +00005211 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5212 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5213 if (Source == Target) return;
5214 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00005215
Chandler Carruth108f7562011-07-26 05:40:03 +00005216 // If the conversion context location is invalid don't complain. We also
5217 // don't want to emit a warning if the issue occurs from the expansion of
5218 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5219 // delay this check as long as possible. Once we detect we are in that
5220 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00005221 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00005222 return;
5223
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005224 // Diagnose implicit casts to bool.
5225 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5226 if (isa<StringLiteral>(E))
5227 // Warn on string literal to bool. Checks for string literals in logical
5228 // expressions, for instances, assert(0 && "error here"), is prevented
5229 // by a check in AnalyzeImplicitConversions().
5230 return DiagnoseImpCast(S, E, T, CC,
5231 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00005232 if (Source->isFunctionType()) {
5233 // Warn on function to bool. Checks free functions and static member
5234 // functions. Weakly imported functions are excluded from the check,
5235 // since it's common to test their value to check whether the linker
5236 // found a definition for them.
5237 ValueDecl *D = 0;
5238 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5239 D = R->getDecl();
5240 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5241 D = M->getMemberDecl();
5242 }
5243
5244 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00005245 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5246 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5247 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00005248 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5249 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5250 QualType ReturnType;
5251 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00005252 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00005253 if (!ReturnType.isNull()
5254 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5255 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5256 << FixItHint::CreateInsertion(
5257 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00005258 return;
5259 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00005260 }
5261 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005262 }
John McCall51313c32010-01-04 23:31:57 +00005263
5264 // Strip vector types.
5265 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005266 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005267 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005268 return;
John McCallb4eb64d2010-10-08 02:01:28 +00005269 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005270 }
Chris Lattnerb792b302011-06-14 04:51:15 +00005271
5272 // If the vector cast is cast between two vectors of the same size, it is
5273 // a bitcast, not a conversion.
5274 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5275 return;
John McCall51313c32010-01-04 23:31:57 +00005276
5277 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5278 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5279 }
5280
5281 // Strip complex types.
5282 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005283 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005284 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005285 return;
5286
John McCallb4eb64d2010-10-08 02:01:28 +00005287 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005288 }
John McCall51313c32010-01-04 23:31:57 +00005289
5290 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5291 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5292 }
5293
5294 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5295 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5296
5297 // If the source is floating point...
5298 if (SourceBT && SourceBT->isFloatingPoint()) {
5299 // ...and the target is floating point...
5300 if (TargetBT && TargetBT->isFloatingPoint()) {
5301 // ...then warn if we're dropping FP rank.
5302
5303 // Builtin FP kinds are ordered by increasing FP rank.
5304 if (SourceBT->getKind() > TargetBT->getKind()) {
5305 // Don't warn about float constants that are precisely
5306 // representable in the target type.
5307 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005308 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00005309 // Value might be a float, a float vector, or a float complex.
5310 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00005311 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5312 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00005313 return;
5314 }
5315
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005316 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005317 return;
5318
John McCallb4eb64d2010-10-08 02:01:28 +00005319 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00005320 }
5321 return;
5322 }
5323
Ted Kremenekef9ff882011-03-10 20:03:42 +00005324 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00005325 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005326 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005327 return;
5328
Chandler Carrutha5b93322011-02-17 11:05:49 +00005329 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00005330 // We also want to warn on, e.g., "int i = -1.234"
5331 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5332 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5333 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5334
Chandler Carruthf65076e2011-04-10 08:36:24 +00005335 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5336 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005337 } else {
5338 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5339 }
5340 }
John McCall51313c32010-01-04 23:31:57 +00005341
Hans Wennborg88617a22012-08-28 15:44:30 +00005342 // If the target is bool, warn if expr is a function or method call.
5343 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5344 isa<CallExpr>(E)) {
5345 // Check last argument of function call to see if it is an
5346 // implicit cast from a type matching the type the result
5347 // is being cast to.
5348 CallExpr *CEx = cast<CallExpr>(E);
5349 unsigned NumArgs = CEx->getNumArgs();
5350 if (NumArgs > 0) {
5351 Expr *LastA = CEx->getArg(NumArgs - 1);
5352 Expr *InnerE = LastA->IgnoreParenImpCasts();
5353 const Type *InnerType =
5354 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5355 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5356 // Warn on this floating-point to bool conversion
5357 DiagnoseImpCast(S, E, T, CC,
5358 diag::warn_impcast_floating_point_to_bool);
5359 }
5360 }
5361 }
John McCall51313c32010-01-04 23:31:57 +00005362 return;
5363 }
5364
Richard Trieu1838ca52011-05-29 19:59:02 +00005365 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005366 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005367 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005368 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005369 SourceLocation Loc = E->getSourceRange().getBegin();
5370 if (Loc.isMacroID())
5371 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005372 if (!Loc.isMacroID() || CC.isMacroID())
5373 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5374 << T << clang::SourceRange(CC)
Richard Smith8adf8372013-09-20 00:27:40 +00005375 << FixItHint::CreateReplacement(Loc,
5376 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieu1838ca52011-05-29 19:59:02 +00005377 }
5378
David Blaikieb26331b2012-06-19 21:19:06 +00005379 if (!Source->isIntegerType() || !Target->isIntegerType())
5380 return;
5381
David Blaikiebe0ee872012-05-15 16:56:36 +00005382 // TODO: remove this early return once the false positives for constant->bool
5383 // in templates, macros, etc, are reduced or removed.
5384 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5385 return;
5386
John McCall323ed742010-05-06 08:58:33 +00005387 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005388 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005389
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005390 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005391 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005392 // TODO: this should happen for bitfield stores, too.
5393 llvm::APSInt Value(32);
5394 if (E->isIntegerConstantExpr(Value, S.Context)) {
5395 if (S.SourceMgr.isInSystemMacro(CC))
5396 return;
5397
John McCall091f23f2010-11-09 22:22:12 +00005398 std::string PrettySourceValue = Value.toString(10);
5399 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005400
Ted Kremenek5e745da2011-10-22 02:37:33 +00005401 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5402 S.PDiag(diag::warn_impcast_integer_precision_constant)
5403 << PrettySourceValue << PrettyTargetValue
5404 << E->getType() << T << E->getSourceRange()
5405 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005406 return;
5407 }
5408
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005409 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5410 if (S.SourceMgr.isInSystemMacro(CC))
5411 return;
5412
David Blaikie37050842012-04-12 22:40:54 +00005413 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005414 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5415 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005416 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005417 }
5418
5419 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5420 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5421 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005422
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005423 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005424 return;
5425
John McCall323ed742010-05-06 08:58:33 +00005426 unsigned DiagID = diag::warn_impcast_integer_sign;
5427
5428 // Traditionally, gcc has warned about this under -Wsign-compare.
5429 // We also want to warn about it in -Wconversion.
5430 // So if -Wconversion is off, use a completely identical diagnostic
5431 // in the sign-compare group.
5432 // The conditional-checking code will
5433 if (ICContext) {
5434 DiagID = diag::warn_impcast_integer_sign_conditional;
5435 *ICContext = true;
5436 }
5437
John McCallb4eb64d2010-10-08 02:01:28 +00005438 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005439 }
5440
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005441 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005442 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5443 // type, to give us better diagnostics.
5444 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005445 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005446 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5447 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5448 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5449 SourceType = S.Context.getTypeDeclType(Enum);
5450 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5451 }
5452 }
5453
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005454 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5455 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005456 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5457 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005458 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005459 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005460 return;
5461
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005462 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005463 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005464 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005465
John McCall51313c32010-01-04 23:31:57 +00005466 return;
5467}
5468
David Blaikie9fb1ac52012-05-15 21:57:38 +00005469void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5470 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005471
5472void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005473 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005474 E = E->IgnoreParenImpCasts();
5475
5476 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005477 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005478
John McCallb4eb64d2010-10-08 02:01:28 +00005479 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005480 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005481 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005482 return;
5483}
5484
David Blaikie9fb1ac52012-05-15 21:57:38 +00005485void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5486 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005487 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005488
5489 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005490 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5491 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005492
5493 // If -Wconversion would have warned about either of the candidates
5494 // for a signedness conversion to the context type...
5495 if (!Suspicious) return;
5496
5497 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005498 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5499 CC))
John McCall323ed742010-05-06 08:58:33 +00005500 return;
5501
John McCall323ed742010-05-06 08:58:33 +00005502 // ...then check whether it would have warned about either of the
5503 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005504 if (E->getType() == T) return;
5505
5506 Suspicious = false;
5507 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5508 E->getType(), CC, &Suspicious);
5509 if (!Suspicious)
5510 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005511 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005512}
5513
5514/// AnalyzeImplicitConversions - Find and report any interesting
5515/// implicit conversions in the given expression. There are a couple
5516/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005517void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005518 QualType T = OrigE->getType();
5519 Expr *E = OrigE->IgnoreParenImpCasts();
5520
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005521 if (E->isTypeDependent() || E->isValueDependent())
5522 return;
5523
John McCall323ed742010-05-06 08:58:33 +00005524 // For conditional operators, we analyze the arguments as if they
5525 // were being fed directly into the output.
5526 if (isa<ConditionalOperator>(E)) {
5527 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005528 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005529 return;
5530 }
5531
Hans Wennborg88617a22012-08-28 15:44:30 +00005532 // Check implicit argument conversions for function calls.
5533 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5534 CheckImplicitArgumentConversions(S, Call, CC);
5535
John McCall323ed742010-05-06 08:58:33 +00005536 // Go ahead and check any implicit conversions we might have skipped.
5537 // The non-canonical typecheck is just an optimization;
5538 // CheckImplicitConversion will filter out dead implicit conversions.
5539 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005540 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005541
5542 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005543
5544 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005545 if (POE->getResultExpr())
5546 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005547 }
5548
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005549 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5550 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5551
John McCall323ed742010-05-06 08:58:33 +00005552 // Skip past explicit casts.
5553 if (isa<ExplicitCastExpr>(E)) {
5554 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005555 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005556 }
5557
John McCallbeb22aa2010-11-09 23:24:47 +00005558 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5559 // Do a somewhat different check with comparison operators.
5560 if (BO->isComparisonOp())
5561 return AnalyzeComparison(S, BO);
5562
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005563 // And with simple assignments.
5564 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005565 return AnalyzeAssignment(S, BO);
5566 }
John McCall323ed742010-05-06 08:58:33 +00005567
5568 // These break the otherwise-useful invariant below. Fortunately,
5569 // we don't really need to recurse into them, because any internal
5570 // expressions should have been analyzed already when they were
5571 // built into statements.
5572 if (isa<StmtExpr>(E)) return;
5573
5574 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005575 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005576
5577 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005578 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005579 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5580 bool IsLogicalOperator = BO && BO->isLogicalOp();
5581 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005582 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005583 if (!ChildExpr)
5584 continue;
5585
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005586 if (IsLogicalOperator &&
5587 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5588 // Ignore checking string literals that are in logical operators.
5589 continue;
5590 AnalyzeImplicitConversions(S, ChildExpr, CC);
5591 }
John McCall323ed742010-05-06 08:58:33 +00005592}
5593
5594} // end anonymous namespace
5595
5596/// Diagnoses "dangerous" implicit conversions within the given
5597/// expression (which is a full expression). Implements -Wconversion
5598/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005599///
5600/// \param CC the "context" location of the implicit conversion, i.e.
5601/// the most location of the syntactic entity requiring the implicit
5602/// conversion
5603void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005604 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005605 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005606 return;
5607
5608 // Don't diagnose for value- or type-dependent expressions.
5609 if (E->isTypeDependent() || E->isValueDependent())
5610 return;
5611
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005612 // Check for array bounds violations in cases where the check isn't triggered
5613 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5614 // ArraySubscriptExpr is on the RHS of a variable initialization.
5615 CheckArrayAccess(E);
5616
John McCallb4eb64d2010-10-08 02:01:28 +00005617 // This is not the right CC for (e.g.) a variable initialization.
5618 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005619}
5620
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005621/// Diagnose when expression is an integer constant expression and its evaluation
5622/// results in integer overflow
5623void Sema::CheckForIntOverflow (Expr *E) {
Richard Smith00043292013-11-05 22:23:30 +00005624 if (isa<BinaryOperator>(E->IgnoreParens()))
5625 E->EvaluateForOverflow(Context);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005626}
5627
Richard Smith6c3af3d2013-01-17 01:17:56 +00005628namespace {
5629/// \brief Visitor for expressions which looks for unsequenced operations on the
5630/// same object.
5631class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005632 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5633
Richard Smith6c3af3d2013-01-17 01:17:56 +00005634 /// \brief A tree of sequenced regions within an expression. Two regions are
5635 /// unsequenced if one is an ancestor or a descendent of the other. When we
5636 /// finish processing an expression with sequencing, such as a comma
5637 /// expression, we fold its tree nodes into its parent, since they are
5638 /// unsequenced with respect to nodes we will visit later.
5639 class SequenceTree {
5640 struct Value {
5641 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5642 unsigned Parent : 31;
5643 bool Merged : 1;
5644 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00005645 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005646
5647 public:
5648 /// \brief A region within an expression which may be sequenced with respect
5649 /// to some other region.
5650 class Seq {
5651 explicit Seq(unsigned N) : Index(N) {}
5652 unsigned Index;
5653 friend class SequenceTree;
5654 public:
5655 Seq() : Index(0) {}
5656 };
5657
5658 SequenceTree() { Values.push_back(Value(0)); }
5659 Seq root() const { return Seq(0); }
5660
5661 /// \brief Create a new sequence of operations, which is an unsequenced
5662 /// subset of \p Parent. This sequence of operations is sequenced with
5663 /// respect to other children of \p Parent.
5664 Seq allocate(Seq Parent) {
5665 Values.push_back(Value(Parent.Index));
5666 return Seq(Values.size() - 1);
5667 }
5668
5669 /// \brief Merge a sequence of operations into its parent.
5670 void merge(Seq S) {
5671 Values[S.Index].Merged = true;
5672 }
5673
5674 /// \brief Determine whether two operations are unsequenced. This operation
5675 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5676 /// should have been merged into its parent as appropriate.
5677 bool isUnsequenced(Seq Cur, Seq Old) {
5678 unsigned C = representative(Cur.Index);
5679 unsigned Target = representative(Old.Index);
5680 while (C >= Target) {
5681 if (C == Target)
5682 return true;
5683 C = Values[C].Parent;
5684 }
5685 return false;
5686 }
5687
5688 private:
5689 /// \brief Pick a representative for a sequence.
5690 unsigned representative(unsigned K) {
5691 if (Values[K].Merged)
5692 // Perform path compression as we go.
5693 return Values[K].Parent = representative(Values[K].Parent);
5694 return K;
5695 }
5696 };
5697
5698 /// An object for which we can track unsequenced uses.
5699 typedef NamedDecl *Object;
5700
5701 /// Different flavors of object usage which we track. We only track the
5702 /// least-sequenced usage of each kind.
5703 enum UsageKind {
5704 /// A read of an object. Multiple unsequenced reads are OK.
5705 UK_Use,
5706 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005707 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005708 UK_ModAsValue,
5709 /// A modification of an object which is not sequenced before the value
5710 /// computation of the expression, such as n++.
5711 UK_ModAsSideEffect,
5712
5713 UK_Count = UK_ModAsSideEffect + 1
5714 };
5715
5716 struct Usage {
5717 Usage() : Use(0), Seq() {}
5718 Expr *Use;
5719 SequenceTree::Seq Seq;
5720 };
5721
5722 struct UsageInfo {
5723 UsageInfo() : Diagnosed(false) {}
5724 Usage Uses[UK_Count];
5725 /// Have we issued a diagnostic for this variable already?
5726 bool Diagnosed;
5727 };
5728 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5729
5730 Sema &SemaRef;
5731 /// Sequenced regions within the expression.
5732 SequenceTree Tree;
5733 /// Declaration modifications and references which we have seen.
5734 UsageInfoMap UsageMap;
5735 /// The region we are currently within.
5736 SequenceTree::Seq Region;
5737 /// Filled in with declarations which were modified as a side-effect
5738 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00005739 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005740 /// Expressions to check later. We defer checking these to reduce
5741 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00005742 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005743
5744 /// RAII object wrapping the visitation of a sequenced subexpression of an
5745 /// expression. At the end of this process, the side-effects of the evaluation
5746 /// become sequenced with respect to the value computation of the result, so
5747 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5748 /// UK_ModAsValue.
5749 struct SequencedSubexpression {
5750 SequencedSubexpression(SequenceChecker &Self)
5751 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5752 Self.ModAsSideEffect = &ModAsSideEffect;
5753 }
5754 ~SequencedSubexpression() {
5755 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5756 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5757 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5758 Self.addUsage(U, ModAsSideEffect[I].first,
5759 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5760 }
5761 Self.ModAsSideEffect = OldModAsSideEffect;
5762 }
5763
5764 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00005765 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5766 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005767 };
5768
Richard Smith67470052013-06-20 22:21:56 +00005769 /// RAII object wrapping the visitation of a subexpression which we might
5770 /// choose to evaluate as a constant. If any subexpression is evaluated and
5771 /// found to be non-constant, this allows us to suppress the evaluation of
5772 /// the outer expression.
5773 class EvaluationTracker {
5774 public:
5775 EvaluationTracker(SequenceChecker &Self)
5776 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5777 Self.EvalTracker = this;
5778 }
5779 ~EvaluationTracker() {
5780 Self.EvalTracker = Prev;
5781 if (Prev)
5782 Prev->EvalOK &= EvalOK;
5783 }
5784
5785 bool evaluate(const Expr *E, bool &Result) {
5786 if (!EvalOK || E->isValueDependent())
5787 return false;
5788 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5789 return EvalOK;
5790 }
5791
5792 private:
5793 SequenceChecker &Self;
5794 EvaluationTracker *Prev;
5795 bool EvalOK;
5796 } *EvalTracker;
5797
Richard Smith6c3af3d2013-01-17 01:17:56 +00005798 /// \brief Find the object which is produced by the specified expression,
5799 /// if any.
5800 Object getObject(Expr *E, bool Mod) const {
5801 E = E->IgnoreParenCasts();
5802 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5803 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5804 return getObject(UO->getSubExpr(), Mod);
5805 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5806 if (BO->getOpcode() == BO_Comma)
5807 return getObject(BO->getRHS(), Mod);
5808 if (Mod && BO->isAssignmentOp())
5809 return getObject(BO->getLHS(), Mod);
5810 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5811 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5812 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5813 return ME->getMemberDecl();
5814 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5815 // FIXME: If this is a reference, map through to its value.
5816 return DRE->getDecl();
5817 return 0;
5818 }
5819
5820 /// \brief Note that an object was modified or used by an expression.
5821 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5822 Usage &U = UI.Uses[UK];
5823 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5824 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5825 ModAsSideEffect->push_back(std::make_pair(O, U));
5826 U.Use = Ref;
5827 U.Seq = Region;
5828 }
5829 }
5830 /// \brief Check whether a modification or use conflicts with a prior usage.
5831 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5832 bool IsModMod) {
5833 if (UI.Diagnosed)
5834 return;
5835
5836 const Usage &U = UI.Uses[OtherKind];
5837 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5838 return;
5839
5840 Expr *Mod = U.Use;
5841 Expr *ModOrUse = Ref;
5842 if (OtherKind == UK_Use)
5843 std::swap(Mod, ModOrUse);
5844
5845 SemaRef.Diag(Mod->getExprLoc(),
5846 IsModMod ? diag::warn_unsequenced_mod_mod
5847 : diag::warn_unsequenced_mod_use)
5848 << O << SourceRange(ModOrUse->getExprLoc());
5849 UI.Diagnosed = true;
5850 }
5851
5852 void notePreUse(Object O, Expr *Use) {
5853 UsageInfo &U = UsageMap[O];
5854 // Uses conflict with other modifications.
5855 checkUsage(O, U, Use, UK_ModAsValue, false);
5856 }
5857 void notePostUse(Object O, Expr *Use) {
5858 UsageInfo &U = UsageMap[O];
5859 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5860 addUsage(U, O, Use, UK_Use);
5861 }
5862
5863 void notePreMod(Object O, Expr *Mod) {
5864 UsageInfo &U = UsageMap[O];
5865 // Modifications conflict with other modifications and with uses.
5866 checkUsage(O, U, Mod, UK_ModAsValue, true);
5867 checkUsage(O, U, Mod, UK_Use, false);
5868 }
5869 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5870 UsageInfo &U = UsageMap[O];
5871 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5872 addUsage(U, O, Use, UK);
5873 }
5874
5875public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00005876 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5877 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5878 WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005879 Visit(E);
5880 }
5881
5882 void VisitStmt(Stmt *S) {
5883 // Skip all statements which aren't expressions for now.
5884 }
5885
5886 void VisitExpr(Expr *E) {
5887 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005888 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005889 }
5890
5891 void VisitCastExpr(CastExpr *E) {
5892 Object O = Object();
5893 if (E->getCastKind() == CK_LValueToRValue)
5894 O = getObject(E->getSubExpr(), false);
5895
5896 if (O)
5897 notePreUse(O, E);
5898 VisitExpr(E);
5899 if (O)
5900 notePostUse(O, E);
5901 }
5902
5903 void VisitBinComma(BinaryOperator *BO) {
5904 // C++11 [expr.comma]p1:
5905 // Every value computation and side effect associated with the left
5906 // expression is sequenced before every value computation and side
5907 // effect associated with the right expression.
5908 SequenceTree::Seq LHS = Tree.allocate(Region);
5909 SequenceTree::Seq RHS = Tree.allocate(Region);
5910 SequenceTree::Seq OldRegion = Region;
5911
5912 {
5913 SequencedSubexpression SeqLHS(*this);
5914 Region = LHS;
5915 Visit(BO->getLHS());
5916 }
5917
5918 Region = RHS;
5919 Visit(BO->getRHS());
5920
5921 Region = OldRegion;
5922
5923 // Forget that LHS and RHS are sequenced. They are both unsequenced
5924 // with respect to other stuff.
5925 Tree.merge(LHS);
5926 Tree.merge(RHS);
5927 }
5928
5929 void VisitBinAssign(BinaryOperator *BO) {
5930 // The modification is sequenced after the value computation of the LHS
5931 // and RHS, so check it before inspecting the operands and update the
5932 // map afterwards.
5933 Object O = getObject(BO->getLHS(), true);
5934 if (!O)
5935 return VisitExpr(BO);
5936
5937 notePreMod(O, BO);
5938
5939 // C++11 [expr.ass]p7:
5940 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5941 // only once.
5942 //
5943 // Therefore, for a compound assignment operator, O is considered used
5944 // everywhere except within the evaluation of E1 itself.
5945 if (isa<CompoundAssignOperator>(BO))
5946 notePreUse(O, BO);
5947
5948 Visit(BO->getLHS());
5949
5950 if (isa<CompoundAssignOperator>(BO))
5951 notePostUse(O, BO);
5952
5953 Visit(BO->getRHS());
5954
Richard Smith418dd3e2013-06-26 23:16:51 +00005955 // C++11 [expr.ass]p1:
5956 // the assignment is sequenced [...] before the value computation of the
5957 // assignment expression.
5958 // C11 6.5.16/3 has no such rule.
5959 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5960 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005961 }
5962 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5963 VisitBinAssign(CAO);
5964 }
5965
5966 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5967 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5968 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5969 Object O = getObject(UO->getSubExpr(), true);
5970 if (!O)
5971 return VisitExpr(UO);
5972
5973 notePreMod(O, UO);
5974 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005975 // C++11 [expr.pre.incr]p1:
5976 // the expression ++x is equivalent to x+=1
5977 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5978 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005979 }
5980
5981 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5982 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5983 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5984 Object O = getObject(UO->getSubExpr(), true);
5985 if (!O)
5986 return VisitExpr(UO);
5987
5988 notePreMod(O, UO);
5989 Visit(UO->getSubExpr());
5990 notePostMod(O, UO, UK_ModAsSideEffect);
5991 }
5992
5993 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5994 void VisitBinLOr(BinaryOperator *BO) {
5995 // The side-effects of the LHS of an '&&' are sequenced before the
5996 // value computation of the RHS, and hence before the value computation
5997 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5998 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00005999 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006000 {
6001 SequencedSubexpression Sequenced(*this);
6002 Visit(BO->getLHS());
6003 }
6004
6005 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006006 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006007 if (!Result)
6008 Visit(BO->getRHS());
6009 } else {
6010 // Check for unsequenced operations in the RHS, treating it as an
6011 // entirely separate evaluation.
6012 //
6013 // FIXME: If there are operations in the RHS which are unsequenced
6014 // with respect to operations outside the RHS, and those operations
6015 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00006016 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006017 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006018 }
6019 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00006020 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006021 {
6022 SequencedSubexpression Sequenced(*this);
6023 Visit(BO->getLHS());
6024 }
6025
6026 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006027 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006028 if (Result)
6029 Visit(BO->getRHS());
6030 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006031 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006032 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006033 }
6034
6035 // Only visit the condition, unless we can be sure which subexpression will
6036 // be chosen.
6037 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00006038 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00006039 {
6040 SequencedSubexpression Sequenced(*this);
6041 Visit(CO->getCond());
6042 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006043
6044 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006045 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00006046 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006047 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006048 WorkList.push_back(CO->getTrueExpr());
6049 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006050 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006051 }
6052
Richard Smith0c0b3902013-06-30 10:40:20 +00006053 void VisitCallExpr(CallExpr *CE) {
6054 // C++11 [intro.execution]p15:
6055 // When calling a function [...], every value computation and side effect
6056 // associated with any argument expression, or with the postfix expression
6057 // designating the called function, is sequenced before execution of every
6058 // expression or statement in the body of the function [and thus before
6059 // the value computation of its result].
6060 SequencedSubexpression Sequenced(*this);
6061 Base::VisitCallExpr(CE);
6062
6063 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6064 }
6065
Richard Smith6c3af3d2013-01-17 01:17:56 +00006066 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00006067 // This is a call, so all subexpressions are sequenced before the result.
6068 SequencedSubexpression Sequenced(*this);
6069
Richard Smith6c3af3d2013-01-17 01:17:56 +00006070 if (!CCE->isListInitialization())
6071 return VisitExpr(CCE);
6072
6073 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006074 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006075 SequenceTree::Seq Parent = Region;
6076 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6077 E = CCE->arg_end();
6078 I != E; ++I) {
6079 Region = Tree.allocate(Parent);
6080 Elts.push_back(Region);
6081 Visit(*I);
6082 }
6083
6084 // Forget that the initializers are sequenced.
6085 Region = Parent;
6086 for (unsigned I = 0; I < Elts.size(); ++I)
6087 Tree.merge(Elts[I]);
6088 }
6089
6090 void VisitInitListExpr(InitListExpr *ILE) {
6091 if (!SemaRef.getLangOpts().CPlusPlus11)
6092 return VisitExpr(ILE);
6093
6094 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006095 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006096 SequenceTree::Seq Parent = Region;
6097 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6098 Expr *E = ILE->getInit(I);
6099 if (!E) continue;
6100 Region = Tree.allocate(Parent);
6101 Elts.push_back(Region);
6102 Visit(E);
6103 }
6104
6105 // Forget that the initializers are sequenced.
6106 Region = Parent;
6107 for (unsigned I = 0; I < Elts.size(); ++I)
6108 Tree.merge(Elts[I]);
6109 }
6110};
6111}
6112
6113void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00006114 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00006115 WorkList.push_back(E);
6116 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00006117 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00006118 SequenceChecker(*this, Item, WorkList);
6119 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006120}
6121
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006122void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6123 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006124 CheckImplicitConversions(E, CheckLoc);
6125 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006126 if (!IsConstexpr && !E->isValueDependent())
6127 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006128}
6129
John McCall15d7d122010-11-11 03:21:53 +00006130void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6131 FieldDecl *BitField,
6132 Expr *Init) {
6133 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6134}
6135
Mike Stumpf8c49212010-01-21 03:59:47 +00006136/// CheckParmsForFunctionDef - Check that the parameters of the given
6137/// function are appropriate for the definition of a function. This
6138/// takes care of any checks that cannot be performed on the
6139/// declaration itself, e.g., that the types of each of the function
6140/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00006141bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6142 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00006143 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006144 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00006145 for (; P != PEnd; ++P) {
6146 ParmVarDecl *Param = *P;
6147
Mike Stumpf8c49212010-01-21 03:59:47 +00006148 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6149 // function declarator that is part of a function definition of
6150 // that function shall not have incomplete type.
6151 //
6152 // This is also C++ [dcl.fct]p6.
6153 if (!Param->isInvalidDecl() &&
6154 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00006155 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006156 Param->setInvalidDecl();
6157 HasInvalidParm = true;
6158 }
6159
6160 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6161 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00006162 if (CheckParameterNames &&
6163 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00006164 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006165 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00006166 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00006167
6168 // C99 6.7.5.3p12:
6169 // If the function declarator is not part of a definition of that
6170 // function, parameters may have incomplete type and may use the [*]
6171 // notation in their sequences of declarator specifiers to specify
6172 // variable length array types.
6173 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006174 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00006175 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00006176 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00006177 // information is added for it.
6178 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006179 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00006180 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006181 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00006182 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006183
6184 // MSVC destroys objects passed by value in the callee. Therefore a
6185 // function definition which takes such a parameter must be able to call the
6186 // object's destructor.
6187 if (getLangOpts().CPlusPlus &&
6188 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6189 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6190 FinalizeVarWithDestructor(Param, RT);
6191 }
Mike Stumpf8c49212010-01-21 03:59:47 +00006192 }
6193
6194 return HasInvalidParm;
6195}
John McCallb7f4ffe2010-08-12 21:44:57 +00006196
6197/// CheckCastAlign - Implements -Wcast-align, which warns when a
6198/// pointer cast increases the alignment requirements.
6199void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6200 // This is actually a lot of work to potentially be doing on every
6201 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006202 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6203 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00006204 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00006205 return;
6206
6207 // Ignore dependent types.
6208 if (T->isDependentType() || Op->getType()->isDependentType())
6209 return;
6210
6211 // Require that the destination be a pointer type.
6212 const PointerType *DestPtr = T->getAs<PointerType>();
6213 if (!DestPtr) return;
6214
6215 // If the destination has alignment 1, we're done.
6216 QualType DestPointee = DestPtr->getPointeeType();
6217 if (DestPointee->isIncompleteType()) return;
6218 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6219 if (DestAlign.isOne()) return;
6220
6221 // Require that the source be a pointer type.
6222 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6223 if (!SrcPtr) return;
6224 QualType SrcPointee = SrcPtr->getPointeeType();
6225
6226 // Whitelist casts from cv void*. We already implicitly
6227 // whitelisted casts to cv void*, since they have alignment 1.
6228 // Also whitelist casts involving incomplete types, which implicitly
6229 // includes 'void'.
6230 if (SrcPointee->isIncompleteType()) return;
6231
6232 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6233 if (SrcAlign >= DestAlign) return;
6234
6235 Diag(TRange.getBegin(), diag::warn_cast_align)
6236 << Op->getType() << T
6237 << static_cast<unsigned>(SrcAlign.getQuantity())
6238 << static_cast<unsigned>(DestAlign.getQuantity())
6239 << TRange << Op->getSourceRange();
6240}
6241
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006242static const Type* getElementType(const Expr *BaseExpr) {
6243 const Type* EltType = BaseExpr->getType().getTypePtr();
6244 if (EltType->isAnyPointerType())
6245 return EltType->getPointeeType().getTypePtr();
6246 else if (EltType->isArrayType())
6247 return EltType->getBaseElementTypeUnsafe();
6248 return EltType;
6249}
6250
Chandler Carruthc2684342011-08-05 09:10:50 +00006251/// \brief Check whether this array fits the idiom of a size-one tail padded
6252/// array member of a struct.
6253///
6254/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6255/// commonly used to emulate flexible arrays in C89 code.
6256static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6257 const NamedDecl *ND) {
6258 if (Size != 1 || !ND) return false;
6259
6260 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6261 if (!FD) return false;
6262
6263 // Don't consider sizes resulting from macro expansions or template argument
6264 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00006265
6266 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006267 while (TInfo) {
6268 TypeLoc TL = TInfo->getTypeLoc();
6269 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00006270 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6271 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006272 TInfo = TDL->getTypeSourceInfo();
6273 continue;
6274 }
David Blaikie39e6ab42013-02-18 22:06:02 +00006275 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6276 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00006277 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6278 return false;
6279 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006280 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00006281 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006282
6283 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00006284 if (!RD) return false;
6285 if (RD->isUnion()) return false;
6286 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6287 if (!CRD->isStandardLayout()) return false;
6288 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006289
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00006290 // See if this is the last field decl in the record.
6291 const Decl *D = FD;
6292 while ((D = D->getNextDeclInContext()))
6293 if (isa<FieldDecl>(D))
6294 return false;
6295 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00006296}
6297
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006298void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006299 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00006300 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00006301 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006302 if (IndexExpr->isValueDependent())
6303 return;
6304
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00006305 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006306 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00006307 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006308 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00006309 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00006310 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00006311
Chandler Carruth34064582011-02-17 20:55:08 +00006312 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006313 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00006314 return;
Richard Smith25b009a2011-12-16 19:31:14 +00006315 if (IndexNegated)
6316 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006317
Chandler Carruthba447122011-08-05 08:07:29 +00006318 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00006319 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6320 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00006321 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00006322 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00006323
Ted Kremenek9e060ca2011-02-23 23:06:04 +00006324 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00006325 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00006326 if (!size.isStrictlyPositive())
6327 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006328
6329 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00006330 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006331 // Make sure we're comparing apples to apples when comparing index to size
6332 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6333 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00006334 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00006335 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006336 if (ptrarith_typesize != array_typesize) {
6337 // There's a cast to a different size type involved
6338 uint64_t ratio = array_typesize / ptrarith_typesize;
6339 // TODO: Be smarter about handling cases where array_typesize is not a
6340 // multiple of ptrarith_typesize
6341 if (ptrarith_typesize * ratio == array_typesize)
6342 size *= llvm::APInt(size.getBitWidth(), ratio);
6343 }
6344 }
6345
Chandler Carruth34064582011-02-17 20:55:08 +00006346 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006347 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006348 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006349 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006350
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006351 // For array subscripting the index must be less than size, but for pointer
6352 // arithmetic also allow the index (offset) to be equal to size since
6353 // computing the next address after the end of the array is legal and
6354 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006355 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006356 return;
6357
6358 // Also don't warn for arrays of size 1 which are members of some
6359 // structure. These are often used to approximate flexible arrays in C89
6360 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006361 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006362 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006363
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006364 // Suppress the warning if the subscript expression (as identified by the
6365 // ']' location) and the index expression are both from macro expansions
6366 // within a system header.
6367 if (ASE) {
6368 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6369 ASE->getRBracketLoc());
6370 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6371 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6372 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00006373 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006374 return;
6375 }
6376 }
6377
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006378 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006379 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006380 DiagID = diag::warn_array_index_exceeds_bounds;
6381
6382 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6383 PDiag(DiagID) << index.toString(10, true)
6384 << size.toString(10, true)
6385 << (unsigned)size.getLimitedValue(~0U)
6386 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006387 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006388 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006389 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006390 DiagID = diag::warn_ptr_arith_precedes_bounds;
6391 if (index.isNegative()) index = -index;
6392 }
6393
6394 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6395 PDiag(DiagID) << index.toString(10, true)
6396 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006397 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006398
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006399 if (!ND) {
6400 // Try harder to find a NamedDecl to point at in the note.
6401 while (const ArraySubscriptExpr *ASE =
6402 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6403 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6404 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6405 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6406 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6407 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6408 }
6409
Chandler Carruth35001ca2011-02-17 21:10:52 +00006410 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006411 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6412 PDiag(diag::note_array_index_out_of_bounds)
6413 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006414}
6415
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006416void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006417 int AllowOnePastEnd = 0;
6418 while (expr) {
6419 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006420 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006421 case Stmt::ArraySubscriptExprClass: {
6422 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006423 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006424 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006425 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006426 }
6427 case Stmt::UnaryOperatorClass: {
6428 // Only unwrap the * and & unary operators
6429 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6430 expr = UO->getSubExpr();
6431 switch (UO->getOpcode()) {
6432 case UO_AddrOf:
6433 AllowOnePastEnd++;
6434 break;
6435 case UO_Deref:
6436 AllowOnePastEnd--;
6437 break;
6438 default:
6439 return;
6440 }
6441 break;
6442 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006443 case Stmt::ConditionalOperatorClass: {
6444 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6445 if (const Expr *lhs = cond->getLHS())
6446 CheckArrayAccess(lhs);
6447 if (const Expr *rhs = cond->getRHS())
6448 CheckArrayAccess(rhs);
6449 return;
6450 }
6451 default:
6452 return;
6453 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006454 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006455}
John McCallf85e1932011-06-15 23:02:42 +00006456
6457//===--- CHECK: Objective-C retain cycles ----------------------------------//
6458
6459namespace {
6460 struct RetainCycleOwner {
6461 RetainCycleOwner() : Variable(0), Indirect(false) {}
6462 VarDecl *Variable;
6463 SourceRange Range;
6464 SourceLocation Loc;
6465 bool Indirect;
6466
6467 void setLocsFrom(Expr *e) {
6468 Loc = e->getExprLoc();
6469 Range = e->getSourceRange();
6470 }
6471 };
6472}
6473
6474/// Consider whether capturing the given variable can possibly lead to
6475/// a retain cycle.
6476static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006477 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006478 // lifetime. In MRR, it's captured strongly if the variable is
6479 // __block and has an appropriate type.
6480 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6481 return false;
6482
6483 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006484 if (ref)
6485 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006486 return true;
6487}
6488
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006489static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006490 while (true) {
6491 e = e->IgnoreParens();
6492 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6493 switch (cast->getCastKind()) {
6494 case CK_BitCast:
6495 case CK_LValueBitCast:
6496 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006497 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006498 e = cast->getSubExpr();
6499 continue;
6500
John McCallf85e1932011-06-15 23:02:42 +00006501 default:
6502 return false;
6503 }
6504 }
6505
6506 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6507 ObjCIvarDecl *ivar = ref->getDecl();
6508 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6509 return false;
6510
6511 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006512 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006513 return false;
6514
6515 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6516 owner.Indirect = true;
6517 return true;
6518 }
6519
6520 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6521 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6522 if (!var) return false;
6523 return considerVariable(var, ref, owner);
6524 }
6525
John McCallf85e1932011-06-15 23:02:42 +00006526 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6527 if (member->isArrow()) return false;
6528
6529 // Don't count this as an indirect ownership.
6530 e = member->getBase();
6531 continue;
6532 }
6533
John McCall4b9c2d22011-11-06 09:01:30 +00006534 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6535 // Only pay attention to pseudo-objects on property references.
6536 ObjCPropertyRefExpr *pre
6537 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6538 ->IgnoreParens());
6539 if (!pre) return false;
6540 if (pre->isImplicitProperty()) return false;
6541 ObjCPropertyDecl *property = pre->getExplicitProperty();
6542 if (!property->isRetaining() &&
6543 !(property->getPropertyIvarDecl() &&
6544 property->getPropertyIvarDecl()->getType()
6545 .getObjCLifetime() == Qualifiers::OCL_Strong))
6546 return false;
6547
6548 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006549 if (pre->isSuperReceiver()) {
6550 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6551 if (!owner.Variable)
6552 return false;
6553 owner.Loc = pre->getLocation();
6554 owner.Range = pre->getSourceRange();
6555 return true;
6556 }
John McCall4b9c2d22011-11-06 09:01:30 +00006557 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6558 ->getSourceExpr());
6559 continue;
6560 }
6561
John McCallf85e1932011-06-15 23:02:42 +00006562 // Array ivars?
6563
6564 return false;
6565 }
6566}
6567
6568namespace {
6569 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6570 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6571 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6572 Variable(variable), Capturer(0) {}
6573
6574 VarDecl *Variable;
6575 Expr *Capturer;
6576
6577 void VisitDeclRefExpr(DeclRefExpr *ref) {
6578 if (ref->getDecl() == Variable && !Capturer)
6579 Capturer = ref;
6580 }
6581
John McCallf85e1932011-06-15 23:02:42 +00006582 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6583 if (Capturer) return;
6584 Visit(ref->getBase());
6585 if (Capturer && ref->isFreeIvar())
6586 Capturer = ref;
6587 }
6588
6589 void VisitBlockExpr(BlockExpr *block) {
6590 // Look inside nested blocks
6591 if (block->getBlockDecl()->capturesVariable(Variable))
6592 Visit(block->getBlockDecl()->getBody());
6593 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006594
6595 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6596 if (Capturer) return;
6597 if (OVE->getSourceExpr())
6598 Visit(OVE->getSourceExpr());
6599 }
John McCallf85e1932011-06-15 23:02:42 +00006600 };
6601}
6602
6603/// Check whether the given argument is a block which captures a
6604/// variable.
6605static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6606 assert(owner.Variable && owner.Loc.isValid());
6607
6608 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006609
6610 // Look through [^{...} copy] and Block_copy(^{...}).
6611 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6612 Selector Cmd = ME->getSelector();
6613 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6614 e = ME->getInstanceReceiver();
6615 if (!e)
6616 return 0;
6617 e = e->IgnoreParenCasts();
6618 }
6619 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6620 if (CE->getNumArgs() == 1) {
6621 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006622 if (Fn) {
6623 const IdentifierInfo *FnI = Fn->getIdentifier();
6624 if (FnI && FnI->isStr("_Block_copy")) {
6625 e = CE->getArg(0)->IgnoreParenCasts();
6626 }
6627 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006628 }
6629 }
6630
John McCallf85e1932011-06-15 23:02:42 +00006631 BlockExpr *block = dyn_cast<BlockExpr>(e);
6632 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6633 return 0;
6634
6635 FindCaptureVisitor visitor(S.Context, owner.Variable);
6636 visitor.Visit(block->getBlockDecl()->getBody());
6637 return visitor.Capturer;
6638}
6639
6640static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6641 RetainCycleOwner &owner) {
6642 assert(capturer);
6643 assert(owner.Variable && owner.Loc.isValid());
6644
6645 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6646 << owner.Variable << capturer->getSourceRange();
6647 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6648 << owner.Indirect << owner.Range;
6649}
6650
6651/// Check for a keyword selector that starts with the word 'add' or
6652/// 'set'.
6653static bool isSetterLikeSelector(Selector sel) {
6654 if (sel.isUnarySelector()) return false;
6655
Chris Lattner5f9e2722011-07-23 10:55:15 +00006656 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006657 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006658 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006659 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006660 else if (str.startswith("add")) {
6661 // Specially whitelist 'addOperationWithBlock:'.
6662 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6663 return false;
6664 str = str.substr(3);
6665 }
John McCallf85e1932011-06-15 23:02:42 +00006666 else
6667 return false;
6668
6669 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006670 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006671}
6672
6673/// Check a message send to see if it's likely to cause a retain cycle.
6674void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6675 // Only check instance methods whose selector looks like a setter.
6676 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6677 return;
6678
6679 // Try to find a variable that the receiver is strongly owned by.
6680 RetainCycleOwner owner;
6681 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006682 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006683 return;
6684 } else {
6685 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6686 owner.Variable = getCurMethodDecl()->getSelfDecl();
6687 owner.Loc = msg->getSuperLoc();
6688 owner.Range = msg->getSuperLoc();
6689 }
6690
6691 // Check whether the receiver is captured by any of the arguments.
6692 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6693 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6694 return diagnoseRetainCycle(*this, capturer, owner);
6695}
6696
6697/// Check a property assign to see if it's likely to cause a retain cycle.
6698void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6699 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006700 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006701 return;
6702
6703 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6704 diagnoseRetainCycle(*this, capturer, owner);
6705}
6706
Jordan Rosee10f4d32012-09-15 02:48:31 +00006707void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6708 RetainCycleOwner Owner;
6709 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6710 return;
6711
6712 // Because we don't have an expression for the variable, we have to set the
6713 // location explicitly here.
6714 Owner.Loc = Var->getLocation();
6715 Owner.Range = Var->getSourceRange();
6716
6717 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6718 diagnoseRetainCycle(*this, Capturer, Owner);
6719}
6720
Ted Kremenek9d084012012-12-21 08:04:28 +00006721static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6722 Expr *RHS, bool isProperty) {
6723 // Check if RHS is an Objective-C object literal, which also can get
6724 // immediately zapped in a weak reference. Note that we explicitly
6725 // allow ObjCStringLiterals, since those are designed to never really die.
6726 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006727
Ted Kremenekd3292c82012-12-21 22:46:35 +00006728 // This enum needs to match with the 'select' in
6729 // warn_objc_arc_literal_assign (off-by-1).
6730 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6731 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6732 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006733
6734 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006735 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006736 << (isProperty ? 0 : 1)
6737 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006738
6739 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006740}
6741
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006742static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6743 Qualifiers::ObjCLifetime LT,
6744 Expr *RHS, bool isProperty) {
6745 // Strip off any implicit cast added to get to the one ARC-specific.
6746 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6747 if (cast->getCastKind() == CK_ARCConsumeObject) {
6748 S.Diag(Loc, diag::warn_arc_retained_assign)
6749 << (LT == Qualifiers::OCL_ExplicitNone)
6750 << (isProperty ? 0 : 1)
6751 << RHS->getSourceRange();
6752 return true;
6753 }
6754 RHS = cast->getSubExpr();
6755 }
6756
6757 if (LT == Qualifiers::OCL_Weak &&
6758 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6759 return true;
6760
6761 return false;
6762}
6763
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006764bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6765 QualType LHS, Expr *RHS) {
6766 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6767
6768 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6769 return false;
6770
6771 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6772 return true;
6773
6774 return false;
6775}
6776
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006777void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6778 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006779 QualType LHSType;
6780 // PropertyRef on LHS type need be directly obtained from
6781 // its declaration as it has a PsuedoType.
6782 ObjCPropertyRefExpr *PRE
6783 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6784 if (PRE && !PRE->isImplicitProperty()) {
6785 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6786 if (PD)
6787 LHSType = PD->getType();
6788 }
6789
6790 if (LHSType.isNull())
6791 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006792
6793 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6794
6795 if (LT == Qualifiers::OCL_Weak) {
6796 DiagnosticsEngine::Level Level =
6797 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6798 if (Level != DiagnosticsEngine::Ignored)
6799 getCurFunction()->markSafeWeakUse(LHS);
6800 }
6801
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006802 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6803 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006804
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006805 // FIXME. Check for other life times.
6806 if (LT != Qualifiers::OCL_None)
6807 return;
6808
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006809 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006810 if (PRE->isImplicitProperty())
6811 return;
6812 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6813 if (!PD)
6814 return;
6815
Bill Wendlingad017fa2012-12-20 19:22:21 +00006816 unsigned Attributes = PD->getPropertyAttributes();
6817 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006818 // when 'assign' attribute was not explicitly specified
6819 // by user, ignore it and rely on property type itself
6820 // for lifetime info.
6821 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6822 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6823 LHSType->isObjCRetainableType())
6824 return;
6825
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006826 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006827 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006828 Diag(Loc, diag::warn_arc_retained_property_assign)
6829 << RHS->getSourceRange();
6830 return;
6831 }
6832 RHS = cast->getSubExpr();
6833 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006834 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006835 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006836 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6837 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006838 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006839 }
6840}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006841
6842//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6843
6844namespace {
6845bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6846 SourceLocation StmtLoc,
6847 const NullStmt *Body) {
6848 // Do not warn if the body is a macro that expands to nothing, e.g:
6849 //
6850 // #define CALL(x)
6851 // if (condition)
6852 // CALL(0);
6853 //
6854 if (Body->hasLeadingEmptyMacro())
6855 return false;
6856
6857 // Get line numbers of statement and body.
6858 bool StmtLineInvalid;
6859 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6860 &StmtLineInvalid);
6861 if (StmtLineInvalid)
6862 return false;
6863
6864 bool BodyLineInvalid;
6865 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6866 &BodyLineInvalid);
6867 if (BodyLineInvalid)
6868 return false;
6869
6870 // Warn if null statement and body are on the same line.
6871 if (StmtLine != BodyLine)
6872 return false;
6873
6874 return true;
6875}
6876} // Unnamed namespace
6877
6878void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6879 const Stmt *Body,
6880 unsigned DiagID) {
6881 // Since this is a syntactic check, don't emit diagnostic for template
6882 // instantiations, this just adds noise.
6883 if (CurrentInstantiationScope)
6884 return;
6885
6886 // The body should be a null statement.
6887 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6888 if (!NBody)
6889 return;
6890
6891 // Do the usual checks.
6892 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6893 return;
6894
6895 Diag(NBody->getSemiLoc(), DiagID);
6896 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6897}
6898
6899void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6900 const Stmt *PossibleBody) {
6901 assert(!CurrentInstantiationScope); // Ensured by caller
6902
6903 SourceLocation StmtLoc;
6904 const Stmt *Body;
6905 unsigned DiagID;
6906 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6907 StmtLoc = FS->getRParenLoc();
6908 Body = FS->getBody();
6909 DiagID = diag::warn_empty_for_body;
6910 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6911 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6912 Body = WS->getBody();
6913 DiagID = diag::warn_empty_while_body;
6914 } else
6915 return; // Neither `for' nor `while'.
6916
6917 // The body should be a null statement.
6918 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6919 if (!NBody)
6920 return;
6921
6922 // Skip expensive checks if diagnostic is disabled.
6923 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6924 DiagnosticsEngine::Ignored)
6925 return;
6926
6927 // Do the usual checks.
6928 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6929 return;
6930
6931 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6932 // noise level low, emit diagnostics only if for/while is followed by a
6933 // CompoundStmt, e.g.:
6934 // for (int i = 0; i < n; i++);
6935 // {
6936 // a(i);
6937 // }
6938 // or if for/while is followed by a statement with more indentation
6939 // than for/while itself:
6940 // for (int i = 0; i < n; i++);
6941 // a(i);
6942 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6943 if (!ProbableTypo) {
6944 bool BodyColInvalid;
6945 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6946 PossibleBody->getLocStart(),
6947 &BodyColInvalid);
6948 if (BodyColInvalid)
6949 return;
6950
6951 bool StmtColInvalid;
6952 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6953 S->getLocStart(),
6954 &StmtColInvalid);
6955 if (StmtColInvalid)
6956 return;
6957
6958 if (BodyCol > StmtCol)
6959 ProbableTypo = true;
6960 }
6961
6962 if (ProbableTypo) {
6963 Diag(NBody->getSemiLoc(), DiagID);
6964 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6965 }
6966}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006967
6968//===--- Layout compatibility ----------------------------------------------//
6969
6970namespace {
6971
6972bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6973
6974/// \brief Check if two enumeration types are layout-compatible.
6975bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6976 // C++11 [dcl.enum] p8:
6977 // Two enumeration types are layout-compatible if they have the same
6978 // underlying type.
6979 return ED1->isComplete() && ED2->isComplete() &&
6980 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6981}
6982
6983/// \brief Check if two fields are layout-compatible.
6984bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6985 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6986 return false;
6987
6988 if (Field1->isBitField() != Field2->isBitField())
6989 return false;
6990
6991 if (Field1->isBitField()) {
6992 // Make sure that the bit-fields are the same length.
6993 unsigned Bits1 = Field1->getBitWidthValue(C);
6994 unsigned Bits2 = Field2->getBitWidthValue(C);
6995
6996 if (Bits1 != Bits2)
6997 return false;
6998 }
6999
7000 return true;
7001}
7002
7003/// \brief Check if two standard-layout structs are layout-compatible.
7004/// (C++11 [class.mem] p17)
7005bool isLayoutCompatibleStruct(ASTContext &C,
7006 RecordDecl *RD1,
7007 RecordDecl *RD2) {
7008 // If both records are C++ classes, check that base classes match.
7009 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7010 // If one of records is a CXXRecordDecl we are in C++ mode,
7011 // thus the other one is a CXXRecordDecl, too.
7012 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7013 // Check number of base classes.
7014 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7015 return false;
7016
7017 // Check the base classes.
7018 for (CXXRecordDecl::base_class_const_iterator
7019 Base1 = D1CXX->bases_begin(),
7020 BaseEnd1 = D1CXX->bases_end(),
7021 Base2 = D2CXX->bases_begin();
7022 Base1 != BaseEnd1;
7023 ++Base1, ++Base2) {
7024 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7025 return false;
7026 }
7027 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7028 // If only RD2 is a C++ class, it should have zero base classes.
7029 if (D2CXX->getNumBases() > 0)
7030 return false;
7031 }
7032
7033 // Check the fields.
7034 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7035 Field2End = RD2->field_end(),
7036 Field1 = RD1->field_begin(),
7037 Field1End = RD1->field_end();
7038 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7039 if (!isLayoutCompatible(C, *Field1, *Field2))
7040 return false;
7041 }
7042 if (Field1 != Field1End || Field2 != Field2End)
7043 return false;
7044
7045 return true;
7046}
7047
7048/// \brief Check if two standard-layout unions are layout-compatible.
7049/// (C++11 [class.mem] p18)
7050bool isLayoutCompatibleUnion(ASTContext &C,
7051 RecordDecl *RD1,
7052 RecordDecl *RD2) {
7053 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7054 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7055 Field2End = RD2->field_end();
7056 Field2 != Field2End; ++Field2) {
7057 UnmatchedFields.insert(*Field2);
7058 }
7059
7060 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7061 Field1End = RD1->field_end();
7062 Field1 != Field1End; ++Field1) {
7063 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7064 I = UnmatchedFields.begin(),
7065 E = UnmatchedFields.end();
7066
7067 for ( ; I != E; ++I) {
7068 if (isLayoutCompatible(C, *Field1, *I)) {
7069 bool Result = UnmatchedFields.erase(*I);
7070 (void) Result;
7071 assert(Result);
7072 break;
7073 }
7074 }
7075 if (I == E)
7076 return false;
7077 }
7078
7079 return UnmatchedFields.empty();
7080}
7081
7082bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7083 if (RD1->isUnion() != RD2->isUnion())
7084 return false;
7085
7086 if (RD1->isUnion())
7087 return isLayoutCompatibleUnion(C, RD1, RD2);
7088 else
7089 return isLayoutCompatibleStruct(C, RD1, RD2);
7090}
7091
7092/// \brief Check if two types are layout-compatible in C++11 sense.
7093bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7094 if (T1.isNull() || T2.isNull())
7095 return false;
7096
7097 // C++11 [basic.types] p11:
7098 // If two types T1 and T2 are the same type, then T1 and T2 are
7099 // layout-compatible types.
7100 if (C.hasSameType(T1, T2))
7101 return true;
7102
7103 T1 = T1.getCanonicalType().getUnqualifiedType();
7104 T2 = T2.getCanonicalType().getUnqualifiedType();
7105
7106 const Type::TypeClass TC1 = T1->getTypeClass();
7107 const Type::TypeClass TC2 = T2->getTypeClass();
7108
7109 if (TC1 != TC2)
7110 return false;
7111
7112 if (TC1 == Type::Enum) {
7113 return isLayoutCompatible(C,
7114 cast<EnumType>(T1)->getDecl(),
7115 cast<EnumType>(T2)->getDecl());
7116 } else if (TC1 == Type::Record) {
7117 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7118 return false;
7119
7120 return isLayoutCompatible(C,
7121 cast<RecordType>(T1)->getDecl(),
7122 cast<RecordType>(T2)->getDecl());
7123 }
7124
7125 return false;
7126}
7127}
7128
7129//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7130
7131namespace {
7132/// \brief Given a type tag expression find the type tag itself.
7133///
7134/// \param TypeExpr Type tag expression, as it appears in user's code.
7135///
7136/// \param VD Declaration of an identifier that appears in a type tag.
7137///
7138/// \param MagicValue Type tag magic value.
7139bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7140 const ValueDecl **VD, uint64_t *MagicValue) {
7141 while(true) {
7142 if (!TypeExpr)
7143 return false;
7144
7145 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7146
7147 switch (TypeExpr->getStmtClass()) {
7148 case Stmt::UnaryOperatorClass: {
7149 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7150 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7151 TypeExpr = UO->getSubExpr();
7152 continue;
7153 }
7154 return false;
7155 }
7156
7157 case Stmt::DeclRefExprClass: {
7158 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7159 *VD = DRE->getDecl();
7160 return true;
7161 }
7162
7163 case Stmt::IntegerLiteralClass: {
7164 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7165 llvm::APInt MagicValueAPInt = IL->getValue();
7166 if (MagicValueAPInt.getActiveBits() <= 64) {
7167 *MagicValue = MagicValueAPInt.getZExtValue();
7168 return true;
7169 } else
7170 return false;
7171 }
7172
7173 case Stmt::BinaryConditionalOperatorClass:
7174 case Stmt::ConditionalOperatorClass: {
7175 const AbstractConditionalOperator *ACO =
7176 cast<AbstractConditionalOperator>(TypeExpr);
7177 bool Result;
7178 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7179 if (Result)
7180 TypeExpr = ACO->getTrueExpr();
7181 else
7182 TypeExpr = ACO->getFalseExpr();
7183 continue;
7184 }
7185 return false;
7186 }
7187
7188 case Stmt::BinaryOperatorClass: {
7189 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7190 if (BO->getOpcode() == BO_Comma) {
7191 TypeExpr = BO->getRHS();
7192 continue;
7193 }
7194 return false;
7195 }
7196
7197 default:
7198 return false;
7199 }
7200 }
7201}
7202
7203/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7204///
7205/// \param TypeExpr Expression that specifies a type tag.
7206///
7207/// \param MagicValues Registered magic values.
7208///
7209/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7210/// kind.
7211///
7212/// \param TypeInfo Information about the corresponding C type.
7213///
7214/// \returns true if the corresponding C type was found.
7215bool GetMatchingCType(
7216 const IdentifierInfo *ArgumentKind,
7217 const Expr *TypeExpr, const ASTContext &Ctx,
7218 const llvm::DenseMap<Sema::TypeTagMagicValue,
7219 Sema::TypeTagData> *MagicValues,
7220 bool &FoundWrongKind,
7221 Sema::TypeTagData &TypeInfo) {
7222 FoundWrongKind = false;
7223
7224 // Variable declaration that has type_tag_for_datatype attribute.
7225 const ValueDecl *VD = NULL;
7226
7227 uint64_t MagicValue;
7228
7229 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7230 return false;
7231
7232 if (VD) {
7233 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7234 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7235 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7236 I != E; ++I) {
7237 if (I->getArgumentKind() != ArgumentKind) {
7238 FoundWrongKind = true;
7239 return false;
7240 }
7241 TypeInfo.Type = I->getMatchingCType();
7242 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7243 TypeInfo.MustBeNull = I->getMustBeNull();
7244 return true;
7245 }
7246 return false;
7247 }
7248
7249 if (!MagicValues)
7250 return false;
7251
7252 llvm::DenseMap<Sema::TypeTagMagicValue,
7253 Sema::TypeTagData>::const_iterator I =
7254 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7255 if (I == MagicValues->end())
7256 return false;
7257
7258 TypeInfo = I->second;
7259 return true;
7260}
7261} // unnamed namespace
7262
7263void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7264 uint64_t MagicValue, QualType Type,
7265 bool LayoutCompatible,
7266 bool MustBeNull) {
7267 if (!TypeTagForDatatypeMagicValues)
7268 TypeTagForDatatypeMagicValues.reset(
7269 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7270
7271 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7272 (*TypeTagForDatatypeMagicValues)[Magic] =
7273 TypeTagData(Type, LayoutCompatible, MustBeNull);
7274}
7275
7276namespace {
7277bool IsSameCharType(QualType T1, QualType T2) {
7278 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7279 if (!BT1)
7280 return false;
7281
7282 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7283 if (!BT2)
7284 return false;
7285
7286 BuiltinType::Kind T1Kind = BT1->getKind();
7287 BuiltinType::Kind T2Kind = BT2->getKind();
7288
7289 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7290 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7291 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7292 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7293}
7294} // unnamed namespace
7295
7296void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7297 const Expr * const *ExprArgs) {
7298 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7299 bool IsPointerAttr = Attr->getIsPointer();
7300
7301 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7302 bool FoundWrongKind;
7303 TypeTagData TypeInfo;
7304 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7305 TypeTagForDatatypeMagicValues.get(),
7306 FoundWrongKind, TypeInfo)) {
7307 if (FoundWrongKind)
7308 Diag(TypeTagExpr->getExprLoc(),
7309 diag::warn_type_tag_for_datatype_wrong_kind)
7310 << TypeTagExpr->getSourceRange();
7311 return;
7312 }
7313
7314 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7315 if (IsPointerAttr) {
7316 // Skip implicit cast of pointer to `void *' (as a function argument).
7317 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00007318 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00007319 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007320 ArgumentExpr = ICE->getSubExpr();
7321 }
7322 QualType ArgumentType = ArgumentExpr->getType();
7323
7324 // Passing a `void*' pointer shouldn't trigger a warning.
7325 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7326 return;
7327
7328 if (TypeInfo.MustBeNull) {
7329 // Type tag with matching void type requires a null pointer.
7330 if (!ArgumentExpr->isNullPointerConstant(Context,
7331 Expr::NPC_ValueDependentIsNotNull)) {
7332 Diag(ArgumentExpr->getExprLoc(),
7333 diag::warn_type_safety_null_pointer_required)
7334 << ArgumentKind->getName()
7335 << ArgumentExpr->getSourceRange()
7336 << TypeTagExpr->getSourceRange();
7337 }
7338 return;
7339 }
7340
7341 QualType RequiredType = TypeInfo.Type;
7342 if (IsPointerAttr)
7343 RequiredType = Context.getPointerType(RequiredType);
7344
7345 bool mismatch = false;
7346 if (!TypeInfo.LayoutCompatible) {
7347 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7348
7349 // C++11 [basic.fundamental] p1:
7350 // Plain char, signed char, and unsigned char are three distinct types.
7351 //
7352 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7353 // char' depending on the current char signedness mode.
7354 if (mismatch)
7355 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7356 RequiredType->getPointeeType())) ||
7357 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7358 mismatch = false;
7359 } else
7360 if (IsPointerAttr)
7361 mismatch = !isLayoutCompatible(Context,
7362 ArgumentType->getPointeeType(),
7363 RequiredType->getPointeeType());
7364 else
7365 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7366
7367 if (mismatch)
7368 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7369 << ArgumentType << ArgumentKind->getName()
7370 << TypeInfo.LayoutCompatible << RequiredType
7371 << ArgumentExpr->getSourceRange()
7372 << TypeTagExpr->getSourceRange();
7373}