blob: 4e0e76b20dd6397eb23773e5ddcb00136bc139f9 [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"
35#include "llvm/ADT/BitVector.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SmallString.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;
559
560 TheCall->setArg(0, ValArg.get());
561 return false;
562}
563
Nate Begeman26a31422010-06-08 02:47:44 +0000564bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000565 llvm::APSInt Result;
566
Tim Northover09df2b02013-07-16 09:47:53 +0000567 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
568 BuiltinID == ARM::BI__builtin_arm_strex) {
569 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
570 }
571
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000572 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000573 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000574 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000575 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000576 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000577#define GET_NEON_OVERLOAD_CHECK
578#include "clang/Basic/arm_neon.inc"
579#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000580 }
581
Nate Begeman0d15c532010-06-13 04:47:52 +0000582 // For NEON intrinsics which are overloaded on vector element type, validate
583 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000584 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000585 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000586 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000587 return true;
588
Bob Wilsonda95f732011-11-08 01:16:11 +0000589 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000590 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000591 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000592 << TheCall->getArg(ImmArg)->getSourceRange();
593 }
594
Bob Wilson46482552011-11-16 21:32:23 +0000595 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000596 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000597 Expr *Arg = TheCall->getArg(PtrArgNum);
598 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
599 Arg = ICE->getSubExpr();
600 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
601 QualType RHSTy = RHS.get()->getType();
602 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
603 if (HasConstPtr)
604 EltTy = EltTy.withConst();
605 QualType LHSTy = Context.getPointerType(EltTy);
606 AssignConvertType ConvTy;
607 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
608 if (RHS.isInvalid())
609 return true;
610 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
611 RHS.get(), AA_Assigning))
612 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000613 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000614
Nate Begeman0d15c532010-06-13 04:47:52 +0000615 // For NEON intrinsics which take an immediate value as part of the
616 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000617 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000618 switch (BuiltinID) {
619 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000620 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
621 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000622 case ARM::BI__builtin_arm_vcvtr_f:
623 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000624#define GET_NEON_IMMEDIATE_CHECK
625#include "clang/Basic/arm_neon.inc"
626#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000627 };
628
Douglas Gregor592a4232012-06-29 01:05:22 +0000629 // We can't check the value of a dependent argument.
630 if (TheCall->getArg(i)->isTypeDependent() ||
631 TheCall->getArg(i)->isValueDependent())
632 return false;
633
Nate Begeman61eecf52010-06-14 05:21:25 +0000634 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000635 if (SemaBuiltinConstantArg(TheCall, i, Result))
636 return true;
637
Nate Begeman61eecf52010-06-14 05:21:25 +0000638 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000639 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000640 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000641 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000642 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000643
Nate Begeman99c40bb2010-08-03 21:32:34 +0000644 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000645 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000646}
Daniel Dunbarde454282008-10-02 18:44:07 +0000647
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000648bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
649 unsigned i = 0, l = 0, u = 0;
650 switch (BuiltinID) {
651 default: return false;
652 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
653 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000654 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
655 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
656 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
657 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
658 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000659 };
660
661 // We can't check the value of a dependent argument.
662 if (TheCall->getArg(i)->isTypeDependent() ||
663 TheCall->getArg(i)->isValueDependent())
664 return false;
665
666 // Check that the immediate argument is actually a constant.
667 llvm::APSInt Result;
668 if (SemaBuiltinConstantArg(TheCall, i, Result))
669 return true;
670
671 // Range check against the upper/lower values for this instruction.
672 unsigned Val = Result.getZExtValue();
673 if (Val < l || Val > u)
674 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
675 << l << u << TheCall->getArg(i)->getSourceRange();
676
677 return false;
678}
679
Richard Smith831421f2012-06-25 20:30:08 +0000680/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
681/// parameter with the FormatAttr's correct format_idx and firstDataArg.
682/// Returns true when the format fits the function and the FormatStringInfo has
683/// been populated.
684bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
685 FormatStringInfo *FSI) {
686 FSI->HasVAListArg = Format->getFirstArg() == 0;
687 FSI->FormatIdx = Format->getFormatIdx() - 1;
688 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000689
Richard Smith831421f2012-06-25 20:30:08 +0000690 // The way the format attribute works in GCC, the implicit this argument
691 // of member functions is counted. However, it doesn't appear in our own
692 // lists, so decrement format_idx in that case.
693 if (IsCXXMember) {
694 if(FSI->FormatIdx == 0)
695 return false;
696 --FSI->FormatIdx;
697 if (FSI->FirstDataArg != 0)
698 --FSI->FirstDataArg;
699 }
700 return true;
701}
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Richard Smith831421f2012-06-25 20:30:08 +0000703/// Handles the checks for format strings, non-POD arguments to vararg
704/// functions, and NULL arguments passed to non-NULL parameters.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000705void Sema::checkCall(NamedDecl *FDecl,
706 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000707 unsigned NumProtoArgs,
708 bool IsMemberFunction,
709 SourceLocation Loc,
710 SourceRange Range,
711 VariadicCallType CallType) {
Jordan Rose66360e22012-10-02 01:49:54 +0000712 if (CurContext->isDependentContext())
713 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000714
Ted Kremenekc82faca2010-09-09 04:33:05 +0000715 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000716 bool HandledFormatString = false;
Richard Trieu0538f0e2013-06-22 00:20:41 +0000717 if (FDecl)
718 for (specific_attr_iterator<FormatAttr>
719 I = FDecl->specific_attr_begin<FormatAttr>(),
720 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
721 if (CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc,
722 Range))
723 HandledFormatString = true;
Richard Smith831421f2012-06-25 20:30:08 +0000724
725 // Refuse POD arguments that weren't caught by the format string
726 // checks above.
727 if (!HandledFormatString && CallType != VariadicDoesNotApply)
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000728 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000729 // Args[ArgIdx] can be null in malformed code.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000730 if (const Expr *Arg = Args[ArgIdx])
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000731 variadicArgumentPODCheck(Arg, CallType);
732 }
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Richard Trieu0538f0e2013-06-22 00:20:41 +0000734 if (FDecl) {
735 for (specific_attr_iterator<NonNullAttr>
736 I = FDecl->specific_attr_begin<NonNullAttr>(),
737 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
738 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000739
Richard Trieu0538f0e2013-06-22 00:20:41 +0000740 // Type safety checking.
741 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
742 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
743 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
744 i != e; ++i) {
745 CheckArgumentWithTypeTag(*i, Args.data());
746 }
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000747 }
Richard Smith831421f2012-06-25 20:30:08 +0000748}
749
750/// CheckConstructorCall - Check a constructor call for correctness and safety
751/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000752void Sema::CheckConstructorCall(FunctionDecl *FDecl,
753 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000754 const FunctionProtoType *Proto,
755 SourceLocation Loc) {
756 VariadicCallType CallType =
757 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000758 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000759 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
760}
761
762/// CheckFunctionCall - Check a direct function call for various correctness
763/// and safety properties not strictly enforced by the C type system.
764bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
765 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000766 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
767 isa<CXXMethodDecl>(FDecl);
768 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
769 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000770 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
771 TheCall->getCallee());
772 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000773 Expr** Args = TheCall->getArgs();
774 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000775 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000776 // If this is a call to a member operator, hide the first argument
777 // from checkCall.
778 // FIXME: Our choice of AST representation here is less than ideal.
779 ++Args;
780 --NumArgs;
781 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000782 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
783 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000784 IsMemberFunction, TheCall->getRParenLoc(),
785 TheCall->getCallee()->getSourceRange(), CallType);
786
787 IdentifierInfo *FnInfo = FDecl->getIdentifier();
788 // None of the checks below are needed for functions that don't have
789 // simple names (e.g., C++ conversion functions).
790 if (!FnInfo)
791 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000792
Anna Zaks0a151a12012-01-17 00:37:07 +0000793 unsigned CMId = FDecl->getMemoryFunctionKind();
794 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000795 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000796
Anna Zaksd9b859a2012-01-13 21:52:01 +0000797 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000798 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000799 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000800 else if (CMId == Builtin::BIstrncat)
801 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000802 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000803 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000804
Anders Carlssond406bf02009-08-16 01:56:34 +0000805 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000806}
807
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000808bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000809 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000810 VariadicCallType CallType =
811 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000812
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000813 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000814 /*IsMemberFunction=*/false,
815 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000816
817 return false;
818}
819
Richard Trieuf462b012013-06-20 21:03:13 +0000820bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
821 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000822 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
823 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000824 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000826 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000827 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000828 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Richard Trieuf462b012013-06-20 21:03:13 +0000830 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000831 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000832 CallType = VariadicDoesNotApply;
833 } else if (Ty->isBlockPointerType()) {
834 CallType = VariadicBlock;
835 } else { // Ty->isFunctionPointerType()
836 CallType = VariadicFunction;
837 }
Richard Smith831421f2012-06-25 20:30:08 +0000838 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000839
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000840 checkCall(NDecl,
841 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
842 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000843 NumProtoArgs, /*IsMemberFunction=*/false,
844 TheCall->getRParenLoc(),
845 TheCall->getCallee()->getSourceRange(), CallType);
846
Anders Carlssond406bf02009-08-16 01:56:34 +0000847 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000848}
849
Richard Trieu0538f0e2013-06-22 00:20:41 +0000850/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
851/// such as function pointers returned from functions.
852bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
853 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
854 TheCall->getCallee());
855 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
856
857 checkCall(/*FDecl=*/0,
858 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
859 TheCall->getNumArgs()),
860 NumProtoArgs, /*IsMemberFunction=*/false,
861 TheCall->getRParenLoc(),
862 TheCall->getCallee()->getSourceRange(), CallType);
863
864 return false;
865}
866
Richard Smithff34d402012-04-12 05:08:17 +0000867ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
868 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000869 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
870 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000871
Richard Smithff34d402012-04-12 05:08:17 +0000872 // All these operations take one of the following forms:
873 enum {
874 // C __c11_atomic_init(A *, C)
875 Init,
876 // C __c11_atomic_load(A *, int)
877 Load,
878 // void __atomic_load(A *, CP, int)
879 Copy,
880 // C __c11_atomic_add(A *, M, int)
881 Arithmetic,
882 // C __atomic_exchange_n(A *, CP, int)
883 Xchg,
884 // void __atomic_exchange(A *, C *, CP, int)
885 GNUXchg,
886 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
887 C11CmpXchg,
888 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
889 GNUCmpXchg
890 } Form = Init;
891 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
892 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
893 // where:
894 // C is an appropriate type,
895 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
896 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
897 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
898 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000899
Richard Smithff34d402012-04-12 05:08:17 +0000900 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
901 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
902 && "need to update code for modified C11 atomics");
903 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
904 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
905 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
906 Op == AtomicExpr::AO__atomic_store_n ||
907 Op == AtomicExpr::AO__atomic_exchange_n ||
908 Op == AtomicExpr::AO__atomic_compare_exchange_n;
909 bool IsAddSub = false;
910
911 switch (Op) {
912 case AtomicExpr::AO__c11_atomic_init:
913 Form = Init;
914 break;
915
916 case AtomicExpr::AO__c11_atomic_load:
917 case AtomicExpr::AO__atomic_load_n:
918 Form = Load;
919 break;
920
921 case AtomicExpr::AO__c11_atomic_store:
922 case AtomicExpr::AO__atomic_load:
923 case AtomicExpr::AO__atomic_store:
924 case AtomicExpr::AO__atomic_store_n:
925 Form = Copy;
926 break;
927
928 case AtomicExpr::AO__c11_atomic_fetch_add:
929 case AtomicExpr::AO__c11_atomic_fetch_sub:
930 case AtomicExpr::AO__atomic_fetch_add:
931 case AtomicExpr::AO__atomic_fetch_sub:
932 case AtomicExpr::AO__atomic_add_fetch:
933 case AtomicExpr::AO__atomic_sub_fetch:
934 IsAddSub = true;
935 // Fall through.
936 case AtomicExpr::AO__c11_atomic_fetch_and:
937 case AtomicExpr::AO__c11_atomic_fetch_or:
938 case AtomicExpr::AO__c11_atomic_fetch_xor:
939 case AtomicExpr::AO__atomic_fetch_and:
940 case AtomicExpr::AO__atomic_fetch_or:
941 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000942 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000943 case AtomicExpr::AO__atomic_and_fetch:
944 case AtomicExpr::AO__atomic_or_fetch:
945 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000946 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000947 Form = Arithmetic;
948 break;
949
950 case AtomicExpr::AO__c11_atomic_exchange:
951 case AtomicExpr::AO__atomic_exchange_n:
952 Form = Xchg;
953 break;
954
955 case AtomicExpr::AO__atomic_exchange:
956 Form = GNUXchg;
957 break;
958
959 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
960 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
961 Form = C11CmpXchg;
962 break;
963
964 case AtomicExpr::AO__atomic_compare_exchange:
965 case AtomicExpr::AO__atomic_compare_exchange_n:
966 Form = GNUCmpXchg;
967 break;
968 }
969
970 // Check we have the right number of arguments.
971 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000972 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000973 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000974 << TheCall->getCallee()->getSourceRange();
975 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000976 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
977 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000978 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000979 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000980 << TheCall->getCallee()->getSourceRange();
981 return ExprError();
982 }
983
Richard Smithff34d402012-04-12 05:08:17 +0000984 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000985 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000986 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
987 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
988 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000989 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000990 << Ptr->getType() << Ptr->getSourceRange();
991 return ExprError();
992 }
993
Richard Smithff34d402012-04-12 05:08:17 +0000994 // For a __c11 builtin, this should be a pointer to an _Atomic type.
995 QualType AtomTy = pointerType->getPointeeType(); // 'A'
996 QualType ValType = AtomTy; // 'C'
997 if (IsC11) {
998 if (!AtomTy->isAtomicType()) {
999 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1000 << Ptr->getType() << Ptr->getSourceRange();
1001 return ExprError();
1002 }
Richard Smithbc57b102012-09-15 06:09:58 +00001003 if (AtomTy.isConstQualified()) {
1004 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1005 << Ptr->getType() << Ptr->getSourceRange();
1006 return ExprError();
1007 }
Richard Smithff34d402012-04-12 05:08:17 +00001008 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001009 }
Eli Friedman276b0612011-10-11 02:20:01 +00001010
Richard Smithff34d402012-04-12 05:08:17 +00001011 // For an arithmetic operation, the implied arithmetic must be well-formed.
1012 if (Form == Arithmetic) {
1013 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1014 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1015 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1016 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1017 return ExprError();
1018 }
1019 if (!IsAddSub && !ValType->isIntegerType()) {
1020 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1021 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1022 return ExprError();
1023 }
1024 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1025 // For __atomic_*_n operations, the value type must be a scalar integral or
1026 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001027 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001028 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1029 return ExprError();
1030 }
1031
1032 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
1033 // For GNU atomics, require a trivially-copyable type. This is not part of
1034 // the GNU atomics specification, but we enforce it for sanity.
1035 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001036 << Ptr->getType() << Ptr->getSourceRange();
1037 return ExprError();
1038 }
1039
Richard Smithff34d402012-04-12 05:08:17 +00001040 // FIXME: For any builtin other than a load, the ValType must not be
1041 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001042
1043 switch (ValType.getObjCLifetime()) {
1044 case Qualifiers::OCL_None:
1045 case Qualifiers::OCL_ExplicitNone:
1046 // okay
1047 break;
1048
1049 case Qualifiers::OCL_Weak:
1050 case Qualifiers::OCL_Strong:
1051 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001052 // FIXME: Can this happen? By this point, ValType should be known
1053 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001054 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1055 << ValType << Ptr->getSourceRange();
1056 return ExprError();
1057 }
1058
1059 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001060 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001061 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001062 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001063 ResultType = Context.BoolTy;
1064
Richard Smithff34d402012-04-12 05:08:17 +00001065 // The type of a parameter passed 'by value'. In the GNU atomics, such
1066 // arguments are actually passed as pointers.
1067 QualType ByValType = ValType; // 'CP'
1068 if (!IsC11 && !IsN)
1069 ByValType = Ptr->getType();
1070
Eli Friedman276b0612011-10-11 02:20:01 +00001071 // The first argument --- the pointer --- has a fixed type; we
1072 // deduce the types of the rest of the arguments accordingly. Walk
1073 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001074 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001075 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001076 if (i < NumVals[Form] + 1) {
1077 switch (i) {
1078 case 1:
1079 // The second argument is the non-atomic operand. For arithmetic, this
1080 // is always passed by value, and for a compare_exchange it is always
1081 // passed by address. For the rest, GNU uses by-address and C11 uses
1082 // by-value.
1083 assert(Form != Load);
1084 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1085 Ty = ValType;
1086 else if (Form == Copy || Form == Xchg)
1087 Ty = ByValType;
1088 else if (Form == Arithmetic)
1089 Ty = Context.getPointerDiffType();
1090 else
1091 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1092 break;
1093 case 2:
1094 // The third argument to compare_exchange / GNU exchange is a
1095 // (pointer to a) desired value.
1096 Ty = ByValType;
1097 break;
1098 case 3:
1099 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1100 Ty = Context.BoolTy;
1101 break;
1102 }
Eli Friedman276b0612011-10-11 02:20:01 +00001103 } else {
1104 // The order(s) are always converted to int.
1105 Ty = Context.IntTy;
1106 }
Richard Smithff34d402012-04-12 05:08:17 +00001107
Eli Friedman276b0612011-10-11 02:20:01 +00001108 InitializedEntity Entity =
1109 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001110 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001111 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1112 if (Arg.isInvalid())
1113 return true;
1114 TheCall->setArg(i, Arg.get());
1115 }
1116
Richard Smithff34d402012-04-12 05:08:17 +00001117 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001118 SmallVector<Expr*, 5> SubExprs;
1119 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001120 switch (Form) {
1121 case Init:
1122 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001123 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001124 break;
1125 case Load:
1126 SubExprs.push_back(TheCall->getArg(1)); // Order
1127 break;
1128 case Copy:
1129 case Arithmetic:
1130 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001131 SubExprs.push_back(TheCall->getArg(2)); // Order
1132 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001133 break;
1134 case GNUXchg:
1135 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1136 SubExprs.push_back(TheCall->getArg(3)); // Order
1137 SubExprs.push_back(TheCall->getArg(1)); // Val1
1138 SubExprs.push_back(TheCall->getArg(2)); // Val2
1139 break;
1140 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001141 SubExprs.push_back(TheCall->getArg(3)); // Order
1142 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001143 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001144 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001145 break;
1146 case GNUCmpXchg:
1147 SubExprs.push_back(TheCall->getArg(4)); // Order
1148 SubExprs.push_back(TheCall->getArg(1)); // Val1
1149 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1150 SubExprs.push_back(TheCall->getArg(2)); // Val2
1151 SubExprs.push_back(TheCall->getArg(3)); // Weak
1152 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001153 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001154
1155 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1156 SubExprs, ResultType, Op,
1157 TheCall->getRParenLoc());
1158
1159 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1160 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1161 Context.AtomicUsesUnsupportedLibcall(AE))
1162 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1163 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001164
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001165 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +00001166}
1167
1168
John McCall5f8d6042011-08-27 01:09:30 +00001169/// checkBuiltinArgument - Given a call to a builtin function, perform
1170/// normal type-checking on the given argument, updating the call in
1171/// place. This is useful when a builtin function requires custom
1172/// type-checking for some of its arguments but not necessarily all of
1173/// them.
1174///
1175/// Returns true on error.
1176static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1177 FunctionDecl *Fn = E->getDirectCallee();
1178 assert(Fn && "builtin call without direct callee!");
1179
1180 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1181 InitializedEntity Entity =
1182 InitializedEntity::InitializeParameter(S.Context, Param);
1183
1184 ExprResult Arg = E->getArg(0);
1185 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1186 if (Arg.isInvalid())
1187 return true;
1188
1189 E->setArg(ArgIndex, Arg.take());
1190 return false;
1191}
1192
Chris Lattner5caa3702009-05-08 06:58:22 +00001193/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1194/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1195/// type of its first argument. The main ActOnCallExpr routines have already
1196/// promoted the types of arguments because all of these calls are prototyped as
1197/// void(...).
1198///
1199/// This function goes through and does final semantic checking for these
1200/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001201ExprResult
1202Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001203 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001204 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1205 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1206
1207 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001208 if (TheCall->getNumArgs() < 1) {
1209 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1210 << 0 << 1 << TheCall->getNumArgs()
1211 << TheCall->getCallee()->getSourceRange();
1212 return ExprError();
1213 }
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Chris Lattner5caa3702009-05-08 06:58:22 +00001215 // Inspect the first argument of the atomic builtin. This should always be
1216 // a pointer type, whose element is an integral scalar or pointer type.
1217 // Because it is a pointer type, we don't have to worry about any implicit
1218 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001219 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001220 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001221 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1222 if (FirstArgResult.isInvalid())
1223 return ExprError();
1224 FirstArg = FirstArgResult.take();
1225 TheCall->setArg(0, FirstArg);
1226
John McCallf85e1932011-06-15 23:02:42 +00001227 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1228 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001229 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1230 << FirstArg->getType() << FirstArg->getSourceRange();
1231 return ExprError();
1232 }
Mike Stump1eb44332009-09-09 15:08:12 +00001233
John McCallf85e1932011-06-15 23:02:42 +00001234 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001235 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001236 !ValType->isBlockPointerType()) {
1237 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1238 << FirstArg->getType() << FirstArg->getSourceRange();
1239 return ExprError();
1240 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001241
John McCallf85e1932011-06-15 23:02:42 +00001242 switch (ValType.getObjCLifetime()) {
1243 case Qualifiers::OCL_None:
1244 case Qualifiers::OCL_ExplicitNone:
1245 // okay
1246 break;
1247
1248 case Qualifiers::OCL_Weak:
1249 case Qualifiers::OCL_Strong:
1250 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001251 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001252 << ValType << FirstArg->getSourceRange();
1253 return ExprError();
1254 }
1255
John McCallb45ae252011-10-05 07:41:44 +00001256 // Strip any qualifiers off ValType.
1257 ValType = ValType.getUnqualifiedType();
1258
Chandler Carruth8d13d222010-07-18 20:54:12 +00001259 // The majority of builtins return a value, but a few have special return
1260 // types, so allow them to override appropriately below.
1261 QualType ResultType = ValType;
1262
Chris Lattner5caa3702009-05-08 06:58:22 +00001263 // We need to figure out which concrete builtin this maps onto. For example,
1264 // __sync_fetch_and_add with a 2 byte object turns into
1265 // __sync_fetch_and_add_2.
1266#define BUILTIN_ROW(x) \
1267 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1268 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Chris Lattner5caa3702009-05-08 06:58:22 +00001270 static const unsigned BuiltinIndices[][5] = {
1271 BUILTIN_ROW(__sync_fetch_and_add),
1272 BUILTIN_ROW(__sync_fetch_and_sub),
1273 BUILTIN_ROW(__sync_fetch_and_or),
1274 BUILTIN_ROW(__sync_fetch_and_and),
1275 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Chris Lattner5caa3702009-05-08 06:58:22 +00001277 BUILTIN_ROW(__sync_add_and_fetch),
1278 BUILTIN_ROW(__sync_sub_and_fetch),
1279 BUILTIN_ROW(__sync_and_and_fetch),
1280 BUILTIN_ROW(__sync_or_and_fetch),
1281 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Chris Lattner5caa3702009-05-08 06:58:22 +00001283 BUILTIN_ROW(__sync_val_compare_and_swap),
1284 BUILTIN_ROW(__sync_bool_compare_and_swap),
1285 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001286 BUILTIN_ROW(__sync_lock_release),
1287 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001288 };
Mike Stump1eb44332009-09-09 15:08:12 +00001289#undef BUILTIN_ROW
1290
Chris Lattner5caa3702009-05-08 06:58:22 +00001291 // Determine the index of the size.
1292 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001293 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001294 case 1: SizeIndex = 0; break;
1295 case 2: SizeIndex = 1; break;
1296 case 4: SizeIndex = 2; break;
1297 case 8: SizeIndex = 3; break;
1298 case 16: SizeIndex = 4; break;
1299 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001300 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1301 << FirstArg->getType() << FirstArg->getSourceRange();
1302 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001303 }
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Chris Lattner5caa3702009-05-08 06:58:22 +00001305 // Each of these builtins has one pointer argument, followed by some number of
1306 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1307 // that we ignore. Find out which row of BuiltinIndices to read from as well
1308 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001309 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001310 unsigned BuiltinIndex, NumFixed = 1;
1311 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001312 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001313 case Builtin::BI__sync_fetch_and_add:
1314 case Builtin::BI__sync_fetch_and_add_1:
1315 case Builtin::BI__sync_fetch_and_add_2:
1316 case Builtin::BI__sync_fetch_and_add_4:
1317 case Builtin::BI__sync_fetch_and_add_8:
1318 case Builtin::BI__sync_fetch_and_add_16:
1319 BuiltinIndex = 0;
1320 break;
1321
1322 case Builtin::BI__sync_fetch_and_sub:
1323 case Builtin::BI__sync_fetch_and_sub_1:
1324 case Builtin::BI__sync_fetch_and_sub_2:
1325 case Builtin::BI__sync_fetch_and_sub_4:
1326 case Builtin::BI__sync_fetch_and_sub_8:
1327 case Builtin::BI__sync_fetch_and_sub_16:
1328 BuiltinIndex = 1;
1329 break;
1330
1331 case Builtin::BI__sync_fetch_and_or:
1332 case Builtin::BI__sync_fetch_and_or_1:
1333 case Builtin::BI__sync_fetch_and_or_2:
1334 case Builtin::BI__sync_fetch_and_or_4:
1335 case Builtin::BI__sync_fetch_and_or_8:
1336 case Builtin::BI__sync_fetch_and_or_16:
1337 BuiltinIndex = 2;
1338 break;
1339
1340 case Builtin::BI__sync_fetch_and_and:
1341 case Builtin::BI__sync_fetch_and_and_1:
1342 case Builtin::BI__sync_fetch_and_and_2:
1343 case Builtin::BI__sync_fetch_and_and_4:
1344 case Builtin::BI__sync_fetch_and_and_8:
1345 case Builtin::BI__sync_fetch_and_and_16:
1346 BuiltinIndex = 3;
1347 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Douglas Gregora9766412011-11-28 16:30:08 +00001349 case Builtin::BI__sync_fetch_and_xor:
1350 case Builtin::BI__sync_fetch_and_xor_1:
1351 case Builtin::BI__sync_fetch_and_xor_2:
1352 case Builtin::BI__sync_fetch_and_xor_4:
1353 case Builtin::BI__sync_fetch_and_xor_8:
1354 case Builtin::BI__sync_fetch_and_xor_16:
1355 BuiltinIndex = 4;
1356 break;
1357
1358 case Builtin::BI__sync_add_and_fetch:
1359 case Builtin::BI__sync_add_and_fetch_1:
1360 case Builtin::BI__sync_add_and_fetch_2:
1361 case Builtin::BI__sync_add_and_fetch_4:
1362 case Builtin::BI__sync_add_and_fetch_8:
1363 case Builtin::BI__sync_add_and_fetch_16:
1364 BuiltinIndex = 5;
1365 break;
1366
1367 case Builtin::BI__sync_sub_and_fetch:
1368 case Builtin::BI__sync_sub_and_fetch_1:
1369 case Builtin::BI__sync_sub_and_fetch_2:
1370 case Builtin::BI__sync_sub_and_fetch_4:
1371 case Builtin::BI__sync_sub_and_fetch_8:
1372 case Builtin::BI__sync_sub_and_fetch_16:
1373 BuiltinIndex = 6;
1374 break;
1375
1376 case Builtin::BI__sync_and_and_fetch:
1377 case Builtin::BI__sync_and_and_fetch_1:
1378 case Builtin::BI__sync_and_and_fetch_2:
1379 case Builtin::BI__sync_and_and_fetch_4:
1380 case Builtin::BI__sync_and_and_fetch_8:
1381 case Builtin::BI__sync_and_and_fetch_16:
1382 BuiltinIndex = 7;
1383 break;
1384
1385 case Builtin::BI__sync_or_and_fetch:
1386 case Builtin::BI__sync_or_and_fetch_1:
1387 case Builtin::BI__sync_or_and_fetch_2:
1388 case Builtin::BI__sync_or_and_fetch_4:
1389 case Builtin::BI__sync_or_and_fetch_8:
1390 case Builtin::BI__sync_or_and_fetch_16:
1391 BuiltinIndex = 8;
1392 break;
1393
1394 case Builtin::BI__sync_xor_and_fetch:
1395 case Builtin::BI__sync_xor_and_fetch_1:
1396 case Builtin::BI__sync_xor_and_fetch_2:
1397 case Builtin::BI__sync_xor_and_fetch_4:
1398 case Builtin::BI__sync_xor_and_fetch_8:
1399 case Builtin::BI__sync_xor_and_fetch_16:
1400 BuiltinIndex = 9;
1401 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Chris Lattner5caa3702009-05-08 06:58:22 +00001403 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001404 case Builtin::BI__sync_val_compare_and_swap_1:
1405 case Builtin::BI__sync_val_compare_and_swap_2:
1406 case Builtin::BI__sync_val_compare_and_swap_4:
1407 case Builtin::BI__sync_val_compare_and_swap_8:
1408 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001409 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001410 NumFixed = 2;
1411 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001412
Chris Lattner5caa3702009-05-08 06:58:22 +00001413 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001414 case Builtin::BI__sync_bool_compare_and_swap_1:
1415 case Builtin::BI__sync_bool_compare_and_swap_2:
1416 case Builtin::BI__sync_bool_compare_and_swap_4:
1417 case Builtin::BI__sync_bool_compare_and_swap_8:
1418 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001419 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001420 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001421 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001422 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001423
1424 case Builtin::BI__sync_lock_test_and_set:
1425 case Builtin::BI__sync_lock_test_and_set_1:
1426 case Builtin::BI__sync_lock_test_and_set_2:
1427 case Builtin::BI__sync_lock_test_and_set_4:
1428 case Builtin::BI__sync_lock_test_and_set_8:
1429 case Builtin::BI__sync_lock_test_and_set_16:
1430 BuiltinIndex = 12;
1431 break;
1432
Chris Lattner5caa3702009-05-08 06:58:22 +00001433 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001434 case Builtin::BI__sync_lock_release_1:
1435 case Builtin::BI__sync_lock_release_2:
1436 case Builtin::BI__sync_lock_release_4:
1437 case Builtin::BI__sync_lock_release_8:
1438 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001439 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001440 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001441 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001442 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001443
1444 case Builtin::BI__sync_swap:
1445 case Builtin::BI__sync_swap_1:
1446 case Builtin::BI__sync_swap_2:
1447 case Builtin::BI__sync_swap_4:
1448 case Builtin::BI__sync_swap_8:
1449 case Builtin::BI__sync_swap_16:
1450 BuiltinIndex = 14;
1451 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001452 }
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Chris Lattner5caa3702009-05-08 06:58:22 +00001454 // Now that we know how many fixed arguments we expect, first check that we
1455 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001456 if (TheCall->getNumArgs() < 1+NumFixed) {
1457 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1458 << 0 << 1+NumFixed << TheCall->getNumArgs()
1459 << TheCall->getCallee()->getSourceRange();
1460 return ExprError();
1461 }
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001463 // Get the decl for the concrete builtin from this, we can tell what the
1464 // concrete integer type we should convert to is.
1465 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1466 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001467 FunctionDecl *NewBuiltinDecl;
1468 if (NewBuiltinID == BuiltinID)
1469 NewBuiltinDecl = FDecl;
1470 else {
1471 // Perform builtin lookup to avoid redeclaring it.
1472 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1473 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1474 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1475 assert(Res.getFoundDecl());
1476 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1477 if (NewBuiltinDecl == 0)
1478 return ExprError();
1479 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001480
John McCallf871d0c2010-08-07 06:22:56 +00001481 // The first argument --- the pointer --- has a fixed type; we
1482 // deduce the types of the rest of the arguments accordingly. Walk
1483 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001484 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001485 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Chris Lattner5caa3702009-05-08 06:58:22 +00001487 // GCC does an implicit conversion to the pointer or integer ValType. This
1488 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001489 // Initialize the argument.
1490 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1491 ValType, /*consume*/ false);
1492 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001493 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001494 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Chris Lattner5caa3702009-05-08 06:58:22 +00001496 // Okay, we have something that *can* be converted to the right type. Check
1497 // to see if there is a potentially weird extension going on here. This can
1498 // happen when you do an atomic operation on something like an char* and
1499 // pass in 42. The 42 gets converted to char. This is even more strange
1500 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001501 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001502 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001503 }
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001505 ASTContext& Context = this->getASTContext();
1506
1507 // Create a new DeclRefExpr to refer to the new decl.
1508 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1509 Context,
1510 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001511 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001512 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001513 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001514 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001515 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001516 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Chris Lattner5caa3702009-05-08 06:58:22 +00001518 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001519 // FIXME: This loses syntactic information.
1520 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1521 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1522 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001523 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001525 // Change the result type of the call to match the original value type. This
1526 // is arbitrary, but the codegen for these builtins ins design to handle it
1527 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001528 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001529
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001530 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001531}
1532
Chris Lattner69039812009-02-18 06:01:06 +00001533/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001534/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001535/// Note: It might also make sense to do the UTF-16 conversion here (would
1536/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001537bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001538 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001539 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1540
Douglas Gregor5cee1192011-07-27 05:40:30 +00001541 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001542 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1543 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001544 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001545 }
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001547 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001548 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001549 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001550 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001551 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001552 UTF16 *ToPtr = &ToBuf[0];
1553
1554 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1555 &ToPtr, ToPtr + NumBytes,
1556 strictConversion);
1557 // Check for conversion failure.
1558 if (Result != conversionOK)
1559 Diag(Arg->getLocStart(),
1560 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1561 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001562 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001563}
1564
Chris Lattnerc27c6652007-12-20 00:05:45 +00001565/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1566/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001567bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1568 Expr *Fn = TheCall->getCallee();
1569 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001570 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001571 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001572 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1573 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001574 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001575 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001576 return true;
1577 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001578
1579 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001580 return Diag(TheCall->getLocEnd(),
1581 diag::err_typecheck_call_too_few_args_at_least)
1582 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001583 }
1584
John McCall5f8d6042011-08-27 01:09:30 +00001585 // Type-check the first argument normally.
1586 if (checkBuiltinArgument(*this, TheCall, 0))
1587 return true;
1588
Chris Lattnerc27c6652007-12-20 00:05:45 +00001589 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001590 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001591 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001592 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001593 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001594 else if (FunctionDecl *FD = getCurFunctionDecl())
1595 isVariadic = FD->isVariadic();
1596 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001597 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Chris Lattnerc27c6652007-12-20 00:05:45 +00001599 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001600 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1601 return true;
1602 }
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Chris Lattner30ce3442007-12-19 23:59:04 +00001604 // Verify that the second argument to the builtin is the last argument of the
1605 // current function or method.
1606 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001607 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Nico Weberb07d4482013-05-24 23:31:57 +00001609 // These are valid if SecondArgIsLastNamedArgument is false after the next
1610 // block.
1611 QualType Type;
1612 SourceLocation ParamLoc;
1613
Anders Carlsson88cf2262008-02-11 04:20:54 +00001614 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1615 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001616 // FIXME: This isn't correct for methods (results in bogus warning).
1617 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001618 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001619 if (CurBlock)
1620 LastArg = *(CurBlock->TheDecl->param_end()-1);
1621 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001622 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001623 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001624 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001625 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001626
1627 Type = PV->getType();
1628 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001629 }
1630 }
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Chris Lattner30ce3442007-12-19 23:59:04 +00001632 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001633 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001634 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001635 else if (Type->isReferenceType()) {
1636 Diag(Arg->getLocStart(),
1637 diag::warn_va_start_of_reference_type_is_undefined);
1638 Diag(ParamLoc, diag::note_parameter_type) << Type;
1639 }
1640
Chris Lattner30ce3442007-12-19 23:59:04 +00001641 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001642}
Chris Lattner30ce3442007-12-19 23:59:04 +00001643
Chris Lattner1b9a0792007-12-20 00:26:33 +00001644/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1645/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001646bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1647 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001648 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001649 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001650 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001651 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001652 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001653 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001654 << SourceRange(TheCall->getArg(2)->getLocStart(),
1655 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001656
John Wiegley429bb272011-04-08 18:41:53 +00001657 ExprResult OrigArg0 = TheCall->getArg(0);
1658 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001659
Chris Lattner1b9a0792007-12-20 00:26:33 +00001660 // Do standard promotions between the two arguments, returning their common
1661 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001662 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001663 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1664 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001665
1666 // Make sure any conversions are pushed back into the call; this is
1667 // type safe since unordered compare builtins are declared as "_Bool
1668 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001669 TheCall->setArg(0, OrigArg0.get());
1670 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001671
John Wiegley429bb272011-04-08 18:41:53 +00001672 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001673 return false;
1674
Chris Lattner1b9a0792007-12-20 00:26:33 +00001675 // If the common type isn't a real floating type, then the arguments were
1676 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001677 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001678 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001679 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001680 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1681 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Chris Lattner1b9a0792007-12-20 00:26:33 +00001683 return false;
1684}
1685
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001686/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1687/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001688/// to check everything. We expect the last argument to be a floating point
1689/// value.
1690bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1691 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001692 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001693 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001694 if (TheCall->getNumArgs() > NumArgs)
1695 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001696 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001697 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001698 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001699 (*(TheCall->arg_end()-1))->getLocEnd());
1700
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001701 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Eli Friedman9ac6f622009-08-31 20:06:00 +00001703 if (OrigArg->isTypeDependent())
1704 return false;
1705
Chris Lattner81368fb2010-05-06 05:50:07 +00001706 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001707 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001708 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001709 diag::err_typecheck_call_invalid_unary_fp)
1710 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Chris Lattner81368fb2010-05-06 05:50:07 +00001712 // If this is an implicit conversion from float -> double, remove it.
1713 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1714 Expr *CastArg = Cast->getSubExpr();
1715 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1716 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1717 "promotion from float to double is the only expected cast here");
1718 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001719 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001720 }
1721 }
1722
Eli Friedman9ac6f622009-08-31 20:06:00 +00001723 return false;
1724}
1725
Eli Friedmand38617c2008-05-14 19:38:39 +00001726/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1727// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001728ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001729 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001730 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001731 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00001732 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1733 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001734
Nate Begeman37b6a572010-06-08 00:16:34 +00001735 // Determine which of the following types of shufflevector we're checking:
1736 // 1) unary, vector mask: (lhs, mask)
1737 // 2) binary, vector mask: (lhs, rhs, mask)
1738 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1739 QualType resType = TheCall->getArg(0)->getType();
1740 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00001741
Douglas Gregorcde01732009-05-19 22:10:17 +00001742 if (!TheCall->getArg(0)->isTypeDependent() &&
1743 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001744 QualType LHSType = TheCall->getArg(0)->getType();
1745 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00001746
Craig Topperbbe759c2013-07-29 06:47:04 +00001747 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1748 return ExprError(Diag(TheCall->getLocStart(),
1749 diag::err_shufflevector_non_vector)
1750 << SourceRange(TheCall->getArg(0)->getLocStart(),
1751 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001752
Nate Begeman37b6a572010-06-08 00:16:34 +00001753 numElements = LHSType->getAs<VectorType>()->getNumElements();
1754 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Nate Begeman37b6a572010-06-08 00:16:34 +00001756 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1757 // with mask. If so, verify that RHS is an integer vector type with the
1758 // same number of elts as lhs.
1759 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001760 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001761 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00001762 return ExprError(Diag(TheCall->getLocStart(),
1763 diag::err_shufflevector_incompatible_vector)
1764 << SourceRange(TheCall->getArg(1)->getLocStart(),
1765 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001766 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00001767 return ExprError(Diag(TheCall->getLocStart(),
1768 diag::err_shufflevector_incompatible_vector)
1769 << SourceRange(TheCall->getArg(0)->getLocStart(),
1770 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001771 } else if (numElements != numResElements) {
1772 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001773 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001774 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001775 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001776 }
1777
1778 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001779 if (TheCall->getArg(i)->isTypeDependent() ||
1780 TheCall->getArg(i)->isValueDependent())
1781 continue;
1782
Nate Begeman37b6a572010-06-08 00:16:34 +00001783 llvm::APSInt Result(32);
1784 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1785 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001786 diag::err_shufflevector_nonconstant_argument)
1787 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001788
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001789 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001790 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001791 diag::err_shufflevector_argument_too_large)
1792 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001793 }
1794
Chris Lattner5f9e2722011-07-23 10:55:15 +00001795 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001796
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001797 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001798 exprs.push_back(TheCall->getArg(i));
1799 TheCall->setArg(i, 0);
1800 }
1801
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001802 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001803 TheCall->getCallee()->getLocStart(),
1804 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001805}
Chris Lattner30ce3442007-12-19 23:59:04 +00001806
Daniel Dunbar4493f792008-07-21 22:59:13 +00001807/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1808// This is declared to take (const void*, ...) and can take two
1809// optional constant int args.
1810bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001811 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001812
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001813 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001814 return Diag(TheCall->getLocEnd(),
1815 diag::err_typecheck_call_too_many_args_at_most)
1816 << 0 /*function call*/ << 3 << NumArgs
1817 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001818
1819 // Argument 0 is checked for us and the remaining arguments must be
1820 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001821 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001822 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001823
1824 // We can't check the value of a dependent argument.
1825 if (Arg->isTypeDependent() || Arg->isValueDependent())
1826 continue;
1827
Eli Friedman9aef7262009-12-04 00:30:06 +00001828 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001829 if (SemaBuiltinConstantArg(TheCall, i, Result))
1830 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Daniel Dunbar4493f792008-07-21 22:59:13 +00001832 // FIXME: gcc issues a warning and rewrites these to 0. These
1833 // seems especially odd for the third argument since the default
1834 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001835 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001836 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001837 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001838 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001839 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001840 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001841 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001842 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001843 }
1844 }
1845
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001846 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001847}
1848
Eric Christopher691ebc32010-04-17 02:26:23 +00001849/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1850/// TheCall is a constant expression.
1851bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1852 llvm::APSInt &Result) {
1853 Expr *Arg = TheCall->getArg(ArgNum);
1854 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1855 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1856
1857 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1858
1859 if (!Arg->isIntegerConstantExpr(Result, Context))
1860 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001861 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001862
Chris Lattner21fb98e2009-09-23 06:06:36 +00001863 return false;
1864}
1865
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001866/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1867/// int type). This simply type checks that type is one of the defined
1868/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001869// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001870bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001871 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001872
1873 // We can't check the value of a dependent argument.
1874 if (TheCall->getArg(1)->isTypeDependent() ||
1875 TheCall->getArg(1)->isValueDependent())
1876 return false;
1877
Eric Christopher691ebc32010-04-17 02:26:23 +00001878 // Check constant-ness first.
1879 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1880 return true;
1881
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001882 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001883 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001884 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1885 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001886 }
1887
1888 return false;
1889}
1890
Eli Friedman586d6a82009-05-03 06:04:26 +00001891/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001892/// This checks that val is a constant 1.
1893bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1894 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001895 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001896
Eric Christopher691ebc32010-04-17 02:26:23 +00001897 // TODO: This is less than ideal. Overload this to take a value.
1898 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1899 return true;
1900
1901 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001902 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1903 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1904
1905 return false;
1906}
1907
Richard Smith831421f2012-06-25 20:30:08 +00001908// Determine if an expression is a string literal or constant string.
1909// If this function returns false on the arguments to a function expecting a
1910// format string, we will usually need to emit a warning.
1911// True string literals are then checked by CheckFormatString.
1912Sema::StringLiteralCheckType
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001913Sema::checkFormatStringExpr(const Expr *E, ArrayRef<const Expr *> Args,
1914 bool HasVAListArg,
Richard Smith831421f2012-06-25 20:30:08 +00001915 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001916 FormatStringType Type, VariadicCallType CallType,
1917 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001918 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001919 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001920 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001921
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001922 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001923
David Blaikiea73cdcb2012-02-10 21:07:25 +00001924 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1925 // Technically -Wformat-nonliteral does not warn about this case.
1926 // The behavior of printf and friends in this case is implementation
1927 // dependent. Ideally if the format string cannot be null then
1928 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001929 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001930
Ted Kremenekd30ef872009-01-12 23:09:09 +00001931 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001932 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001933 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001934 // The expression is a literal if both sub-expressions were, and it was
1935 // completely checked only if both sub-expressions were checked.
1936 const AbstractConditionalOperator *C =
1937 cast<AbstractConditionalOperator>(E);
1938 StringLiteralCheckType Left =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001939 checkFormatStringExpr(C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001940 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001941 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001942 if (Left == SLCT_NotALiteral)
1943 return SLCT_NotALiteral;
1944 StringLiteralCheckType Right =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001945 checkFormatStringExpr(C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001946 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001947 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001948 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001949 }
1950
1951 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001952 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1953 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001954 }
1955
John McCall56ca35d2011-02-17 10:25:35 +00001956 case Stmt::OpaqueValueExprClass:
1957 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1958 E = src;
1959 goto tryAgain;
1960 }
Richard Smith831421f2012-06-25 20:30:08 +00001961 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001962
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001963 case Stmt::PredefinedExprClass:
1964 // While __func__, etc., are technically not string literals, they
1965 // cannot contain format specifiers and thus are not a security
1966 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001967 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001968
Ted Kremenek082d9362009-03-20 21:35:28 +00001969 case Stmt::DeclRefExprClass: {
1970 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Ted Kremenek082d9362009-03-20 21:35:28 +00001972 // As an exception, do not flag errors for variables binding to
1973 // const string literals.
1974 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1975 bool isConstant = false;
1976 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001977
Ted Kremenek082d9362009-03-20 21:35:28 +00001978 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1979 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001980 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001981 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001982 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001983 } else if (T->isObjCObjectPointerType()) {
1984 // In ObjC, there is usually no "const ObjectPointer" type,
1985 // so don't check if the pointee type is constant.
1986 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001987 }
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Ted Kremenek082d9362009-03-20 21:35:28 +00001989 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001990 if (const Expr *Init = VD->getAnyInitializer()) {
1991 // Look through initializers like const char c[] = { "foo" }
1992 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1993 if (InitList->isStringLiteralInit())
1994 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1995 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001996 return checkFormatStringExpr(Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001997 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001998 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001999 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002000 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002001 }
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Anders Carlssond966a552009-06-28 19:55:58 +00002003 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2004 // special check to see if the format string is a function parameter
2005 // of the function calling the printf function. If the function
2006 // has an attribute indicating it is a printf-like function, then we
2007 // should suppress warnings concerning non-literals being used in a call
2008 // to a vprintf function. For example:
2009 //
2010 // void
2011 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2012 // va_list ap;
2013 // va_start(ap, fmt);
2014 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2015 // ...
2016 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002017 if (HasVAListArg) {
2018 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2019 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2020 int PVIndex = PV->getFunctionScopeIndex() + 1;
2021 for (specific_attr_iterator<FormatAttr>
2022 i = ND->specific_attr_begin<FormatAttr>(),
2023 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2024 FormatAttr *PVFormat = *i;
2025 // adjust for implicit parameter
2026 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2027 if (MD->isInstance())
2028 ++PVIndex;
2029 // We also check if the formats are compatible.
2030 // We can't pass a 'scanf' string to a 'printf' function.
2031 if (PVIndex == PVFormat->getFormatIdx() &&
2032 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002033 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002034 }
2035 }
2036 }
2037 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002038 }
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Richard Smith831421f2012-06-25 20:30:08 +00002040 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002041 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002042
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002043 case Stmt::CallExprClass:
2044 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002045 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002046 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2047 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2048 unsigned ArgIndex = FA->getFormatIdx();
2049 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2050 if (MD->isInstance())
2051 --ArgIndex;
2052 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002054 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002055 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002056 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00002057 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2058 unsigned BuiltinID = FD->getBuiltinID();
2059 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2060 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2061 const Expr *Arg = CE->getArg(0);
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002062 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002063 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002064 firstDataArg, Type, CallType,
2065 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00002066 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002067 }
2068 }
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Richard Smith831421f2012-06-25 20:30:08 +00002070 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002071 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002072 case Stmt::ObjCStringLiteralClass:
2073 case Stmt::StringLiteralClass: {
2074 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Ted Kremenek082d9362009-03-20 21:35:28 +00002076 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002077 StrE = ObjCFExpr->getString();
2078 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002079 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Ted Kremenekd30ef872009-01-12 23:09:09 +00002081 if (StrE) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002082 CheckFormatString(StrE, E, Args, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002083 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00002084 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002085 }
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Richard Smith831421f2012-06-25 20:30:08 +00002087 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002088 }
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Ted Kremenek082d9362009-03-20 21:35:28 +00002090 default:
Richard Smith831421f2012-06-25 20:30:08 +00002091 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002092 }
2093}
2094
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002095void
Mike Stump1eb44332009-09-09 15:08:12 +00002096Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00002097 const Expr * const *ExprArgs,
2098 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00002099 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2100 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002101 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00002102 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00002103
2104 // As a special case, transparent unions initialized with zero are
2105 // considered null for the purposes of the nonnull attribute.
2106 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2107 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2108 if (const CompoundLiteralExpr *CLE =
2109 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2110 if (const InitListExpr *ILE =
2111 dyn_cast<InitListExpr>(CLE->getInitializer()))
2112 ArgExpr = ILE->getInit(0);
2113 }
2114
2115 bool Result;
2116 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00002117 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002118 }
2119}
Ted Kremenekd30ef872009-01-12 23:09:09 +00002120
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002121Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2122 return llvm::StringSwitch<FormatStringType>(Format->getType())
2123 .Case("scanf", FST_Scanf)
2124 .Cases("printf", "printf0", FST_Printf)
2125 .Cases("NSString", "CFString", FST_NSString)
2126 .Case("strftime", FST_Strftime)
2127 .Case("strfmon", FST_Strfmon)
2128 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2129 .Default(FST_Unknown);
2130}
2131
Jordan Roseddcfbc92012-07-19 18:10:23 +00002132/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002133/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002134/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002135bool Sema::CheckFormatArguments(const FormatAttr *Format,
2136 ArrayRef<const Expr *> Args,
2137 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002138 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002139 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00002140 FormatStringInfo FSI;
2141 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002142 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002143 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00002144 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00002145 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002146}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002147
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002148bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002149 bool HasVAListArg, unsigned format_idx,
2150 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002151 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002152 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002153 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002154 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002155 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002156 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002157 }
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002159 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Chris Lattner59907c42007-08-10 20:18:51 +00002161 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002162 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002163 // Dynamically generated format strings are difficult to
2164 // automatically vet at compile time. Requiring that format strings
2165 // are string literals: (1) permits the checking of format strings by
2166 // the compiler and thereby (2) can practically remove the source of
2167 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002168
Mike Stump1eb44332009-09-09 15:08:12 +00002169 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002170 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002171 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002172 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002173 StringLiteralCheckType CT =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002174 checkFormatStringExpr(OrigFormatExpr, Args, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002175 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00002176 if (CT != SLCT_NotALiteral)
2177 // Literal format string found, check done!
2178 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002179
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002180 // Strftime is particular as it always uses a single 'time' argument,
2181 // so it is safe to pass a non-literal string.
2182 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002183 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002184
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002185 // Do not emit diag when the string param is a macro expansion and the
2186 // format is either NSString or CFString. This is a hack to prevent
2187 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2188 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002189 if (Type == FST_NSString &&
2190 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002191 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002192
Chris Lattner655f1412009-04-29 04:59:47 +00002193 // If there are no arguments specified, warn with -Wformat-security, otherwise
2194 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002195 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002196 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002197 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002198 << OrigFormatExpr->getSourceRange();
2199 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002200 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002201 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002202 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002203 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002204}
Ted Kremenek71895b92007-08-14 17:39:48 +00002205
Ted Kremeneke0e53132010-01-28 23:39:18 +00002206namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002207class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2208protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002209 Sema &S;
2210 const StringLiteral *FExpr;
2211 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002212 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002213 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002214 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002215 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002216 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002217 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002218 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002219 bool usesPositionalArgs;
2220 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002221 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002222 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002223public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002224 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002225 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002226 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002227 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002228 unsigned formatIdx, bool inFunctionCall,
2229 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002230 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002231 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2232 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002233 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002234 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00002235 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002236 CoveredArgs.resize(numDataArgs);
2237 CoveredArgs.reset();
2238 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002239
Ted Kremenek07d161f2010-01-29 01:50:07 +00002240 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002241
Ted Kremenek826a3452010-07-16 02:11:22 +00002242 void HandleIncompleteSpecifier(const char *startSpecifier,
2243 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002244
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002245 void HandleInvalidLengthModifier(
2246 const analyze_format_string::FormatSpecifier &FS,
2247 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002248 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002249
Hans Wennborg76517422012-02-22 10:17:01 +00002250 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002251 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002252 const char *startSpecifier, unsigned specifierLen);
2253
2254 void HandleNonStandardConversionSpecifier(
2255 const analyze_format_string::ConversionSpecifier &CS,
2256 const char *startSpecifier, unsigned specifierLen);
2257
Hans Wennborgf8562642012-03-09 10:10:54 +00002258 virtual void HandlePosition(const char *startPos, unsigned posLen);
2259
Ted Kremenekefaff192010-02-27 01:41:03 +00002260 virtual void HandleInvalidPosition(const char *startSpecifier,
2261 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002262 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002263
2264 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2265
Ted Kremeneke0e53132010-01-28 23:39:18 +00002266 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002267
Richard Trieu55733de2011-10-28 00:41:25 +00002268 template <typename Range>
2269 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2270 const Expr *ArgumentExpr,
2271 PartialDiagnostic PDiag,
2272 SourceLocation StringLoc,
2273 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002274 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002275
Ted Kremenek826a3452010-07-16 02:11:22 +00002276protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002277 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2278 const char *startSpec,
2279 unsigned specifierLen,
2280 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002281
2282 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2283 const char *startSpec,
2284 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002285
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002286 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002287 CharSourceRange getSpecifierRange(const char *startSpecifier,
2288 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002289 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002290
Ted Kremenek0d277352010-01-29 01:06:55 +00002291 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002292
2293 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2294 const analyze_format_string::ConversionSpecifier &CS,
2295 const char *startSpecifier, unsigned specifierLen,
2296 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002297
2298 template <typename Range>
2299 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2300 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002301 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002302
2303 void CheckPositionalAndNonpositionalArgs(
2304 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002305};
2306}
2307
Ted Kremenek826a3452010-07-16 02:11:22 +00002308SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002309 return OrigFormatExpr->getSourceRange();
2310}
2311
Ted Kremenek826a3452010-07-16 02:11:22 +00002312CharSourceRange CheckFormatHandler::
2313getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002314 SourceLocation Start = getLocationOfByte(startSpecifier);
2315 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2316
2317 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002318 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002319
2320 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002321}
2322
Ted Kremenek826a3452010-07-16 02:11:22 +00002323SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002324 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002325}
2326
Ted Kremenek826a3452010-07-16 02:11:22 +00002327void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2328 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002329 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2330 getLocationOfByte(startSpecifier),
2331 /*IsStringLocation*/true,
2332 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002333}
2334
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002335void CheckFormatHandler::HandleInvalidLengthModifier(
2336 const analyze_format_string::FormatSpecifier &FS,
2337 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002338 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002339 using namespace analyze_format_string;
2340
2341 const LengthModifier &LM = FS.getLengthModifier();
2342 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2343
2344 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002345 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002346 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002347 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002348 getLocationOfByte(LM.getStart()),
2349 /*IsStringLocation*/true,
2350 getSpecifierRange(startSpecifier, specifierLen));
2351
2352 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2353 << FixedLM->toString()
2354 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2355
2356 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002357 FixItHint Hint;
2358 if (DiagID == diag::warn_format_nonsensical_length)
2359 Hint = FixItHint::CreateRemoval(LMRange);
2360
2361 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002362 getLocationOfByte(LM.getStart()),
2363 /*IsStringLocation*/true,
2364 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002365 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002366 }
2367}
2368
Hans Wennborg76517422012-02-22 10:17:01 +00002369void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002370 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002371 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002372 using namespace analyze_format_string;
2373
2374 const LengthModifier &LM = FS.getLengthModifier();
2375 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2376
2377 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002378 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002379 if (FixedLM) {
2380 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2381 << LM.toString() << 0,
2382 getLocationOfByte(LM.getStart()),
2383 /*IsStringLocation*/true,
2384 getSpecifierRange(startSpecifier, specifierLen));
2385
2386 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2387 << FixedLM->toString()
2388 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2389
2390 } else {
2391 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2392 << LM.toString() << 0,
2393 getLocationOfByte(LM.getStart()),
2394 /*IsStringLocation*/true,
2395 getSpecifierRange(startSpecifier, specifierLen));
2396 }
Hans Wennborg76517422012-02-22 10:17:01 +00002397}
2398
2399void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2400 const analyze_format_string::ConversionSpecifier &CS,
2401 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002402 using namespace analyze_format_string;
2403
2404 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002405 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002406 if (FixedCS) {
2407 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2408 << CS.toString() << /*conversion specifier*/1,
2409 getLocationOfByte(CS.getStart()),
2410 /*IsStringLocation*/true,
2411 getSpecifierRange(startSpecifier, specifierLen));
2412
2413 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2414 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2415 << FixedCS->toString()
2416 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2417 } else {
2418 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2419 << CS.toString() << /*conversion specifier*/1,
2420 getLocationOfByte(CS.getStart()),
2421 /*IsStringLocation*/true,
2422 getSpecifierRange(startSpecifier, specifierLen));
2423 }
Hans Wennborg76517422012-02-22 10:17:01 +00002424}
2425
Hans Wennborgf8562642012-03-09 10:10:54 +00002426void CheckFormatHandler::HandlePosition(const char *startPos,
2427 unsigned posLen) {
2428 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2429 getLocationOfByte(startPos),
2430 /*IsStringLocation*/true,
2431 getSpecifierRange(startPos, posLen));
2432}
2433
Ted Kremenekefaff192010-02-27 01:41:03 +00002434void
Ted Kremenek826a3452010-07-16 02:11:22 +00002435CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2436 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002437 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2438 << (unsigned) p,
2439 getLocationOfByte(startPos), /*IsStringLocation*/true,
2440 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002441}
2442
Ted Kremenek826a3452010-07-16 02:11:22 +00002443void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002444 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002445 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2446 getLocationOfByte(startPos),
2447 /*IsStringLocation*/true,
2448 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002449}
2450
Ted Kremenek826a3452010-07-16 02:11:22 +00002451void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002452 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002453 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002454 EmitFormatDiagnostic(
2455 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2456 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2457 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002458 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002459}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002460
Jordan Rose48716662012-07-19 18:10:08 +00002461// Note that this may return NULL if there was an error parsing or building
2462// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002463const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002464 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002465}
2466
2467void CheckFormatHandler::DoneProcessing() {
2468 // Does the number of data arguments exceed the number of
2469 // format conversions in the format string?
2470 if (!HasVAListArg) {
2471 // Find any arguments that weren't covered.
2472 CoveredArgs.flip();
2473 signed notCoveredArg = CoveredArgs.find_first();
2474 if (notCoveredArg >= 0) {
2475 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002476 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2477 SourceLocation Loc = E->getLocStart();
2478 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2479 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2480 Loc, /*IsStringLocation*/false,
2481 getFormatStringRange());
2482 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002483 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002484 }
2485 }
2486}
2487
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002488bool
2489CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2490 SourceLocation Loc,
2491 const char *startSpec,
2492 unsigned specifierLen,
2493 const char *csStart,
2494 unsigned csLen) {
2495
2496 bool keepGoing = true;
2497 if (argIndex < NumDataArgs) {
2498 // Consider the argument coverered, even though the specifier doesn't
2499 // make sense.
2500 CoveredArgs.set(argIndex);
2501 }
2502 else {
2503 // If argIndex exceeds the number of data arguments we
2504 // don't issue a warning because that is just a cascade of warnings (and
2505 // they may have intended '%%' anyway). We don't want to continue processing
2506 // the format string after this point, however, as we will like just get
2507 // gibberish when trying to match arguments.
2508 keepGoing = false;
2509 }
2510
Richard Trieu55733de2011-10-28 00:41:25 +00002511 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2512 << StringRef(csStart, csLen),
2513 Loc, /*IsStringLocation*/true,
2514 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002515
2516 return keepGoing;
2517}
2518
Richard Trieu55733de2011-10-28 00:41:25 +00002519void
2520CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2521 const char *startSpec,
2522 unsigned specifierLen) {
2523 EmitFormatDiagnostic(
2524 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2525 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2526}
2527
Ted Kremenek666a1972010-07-26 19:45:42 +00002528bool
2529CheckFormatHandler::CheckNumArgs(
2530 const analyze_format_string::FormatSpecifier &FS,
2531 const analyze_format_string::ConversionSpecifier &CS,
2532 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2533
2534 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002535 PartialDiagnostic PDiag = FS.usesPositionalArg()
2536 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2537 << (argIndex+1) << NumDataArgs)
2538 : S.PDiag(diag::warn_printf_insufficient_data_args);
2539 EmitFormatDiagnostic(
2540 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2541 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002542 return false;
2543 }
2544 return true;
2545}
2546
Richard Trieu55733de2011-10-28 00:41:25 +00002547template<typename Range>
2548void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2549 SourceLocation Loc,
2550 bool IsStringLocation,
2551 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002552 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002553 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002554 Loc, IsStringLocation, StringRange, FixIt);
2555}
2556
2557/// \brief If the format string is not within the funcion call, emit a note
2558/// so that the function call and string are in diagnostic messages.
2559///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002560/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002561/// call and only one diagnostic message will be produced. Otherwise, an
2562/// extra note will be emitted pointing to location of the format string.
2563///
2564/// \param ArgumentExpr the expression that is passed as the format string
2565/// argument in the function call. Used for getting locations when two
2566/// diagnostics are emitted.
2567///
2568/// \param PDiag the callee should already have provided any strings for the
2569/// diagnostic message. This function only adds locations and fixits
2570/// to diagnostics.
2571///
2572/// \param Loc primary location for diagnostic. If two diagnostics are
2573/// required, one will be at Loc and a new SourceLocation will be created for
2574/// the other one.
2575///
2576/// \param IsStringLocation if true, Loc points to the format string should be
2577/// used for the note. Otherwise, Loc points to the argument list and will
2578/// be used with PDiag.
2579///
2580/// \param StringRange some or all of the string to highlight. This is
2581/// templated so it can accept either a CharSourceRange or a SourceRange.
2582///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002583/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002584template<typename Range>
2585void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2586 const Expr *ArgumentExpr,
2587 PartialDiagnostic PDiag,
2588 SourceLocation Loc,
2589 bool IsStringLocation,
2590 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002591 ArrayRef<FixItHint> FixIt) {
2592 if (InFunctionCall) {
2593 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2594 D << StringRange;
2595 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2596 I != E; ++I) {
2597 D << *I;
2598 }
2599 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002600 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2601 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002602
2603 const Sema::SemaDiagnosticBuilder &Note =
2604 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2605 diag::note_format_string_defined);
2606
2607 Note << StringRange;
2608 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2609 I != E; ++I) {
2610 Note << *I;
2611 }
Richard Trieu55733de2011-10-28 00:41:25 +00002612 }
2613}
2614
Ted Kremenek826a3452010-07-16 02:11:22 +00002615//===--- CHECK: Printf format string checking ------------------------------===//
2616
2617namespace {
2618class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002619 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002620public:
2621 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2622 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002623 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002624 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002625 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002626 unsigned formatIdx, bool inFunctionCall,
2627 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002628 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002629 numDataArgs, beg, hasVAListArg, Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002630 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2631 {}
2632
Ted Kremenek826a3452010-07-16 02:11:22 +00002633
2634 bool HandleInvalidPrintfConversionSpecifier(
2635 const analyze_printf::PrintfSpecifier &FS,
2636 const char *startSpecifier,
2637 unsigned specifierLen);
2638
2639 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2640 const char *startSpecifier,
2641 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002642 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2643 const char *StartSpecifier,
2644 unsigned SpecifierLen,
2645 const Expr *E);
2646
Ted Kremenek826a3452010-07-16 02:11:22 +00002647 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2648 const char *startSpecifier, unsigned specifierLen);
2649 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2650 const analyze_printf::OptionalAmount &Amt,
2651 unsigned type,
2652 const char *startSpecifier, unsigned specifierLen);
2653 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2654 const analyze_printf::OptionalFlag &flag,
2655 const char *startSpecifier, unsigned specifierLen);
2656 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2657 const analyze_printf::OptionalFlag &ignoredFlag,
2658 const analyze_printf::OptionalFlag &flag,
2659 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002660 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002661 const Expr *E, const CharSourceRange &CSR);
2662
Ted Kremenek826a3452010-07-16 02:11:22 +00002663};
2664}
2665
2666bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2667 const analyze_printf::PrintfSpecifier &FS,
2668 const char *startSpecifier,
2669 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002670 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002671 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002672
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002673 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2674 getLocationOfByte(CS.getStart()),
2675 startSpecifier, specifierLen,
2676 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002677}
2678
Ted Kremenek826a3452010-07-16 02:11:22 +00002679bool CheckPrintfHandler::HandleAmount(
2680 const analyze_format_string::OptionalAmount &Amt,
2681 unsigned k, const char *startSpecifier,
2682 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002683
2684 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002685 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002686 unsigned argIndex = Amt.getArgIndex();
2687 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002688 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2689 << k,
2690 getLocationOfByte(Amt.getStart()),
2691 /*IsStringLocation*/true,
2692 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002693 // Don't do any more checking. We will just emit
2694 // spurious errors.
2695 return false;
2696 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002697
Ted Kremenek0d277352010-01-29 01:06:55 +00002698 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002699 // Although not in conformance with C99, we also allow the argument to be
2700 // an 'unsigned int' as that is a reasonably safe case. GCC also
2701 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002702 CoveredArgs.set(argIndex);
2703 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002704 if (!Arg)
2705 return false;
2706
Ted Kremenek0d277352010-01-29 01:06:55 +00002707 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002708
Hans Wennborgf3749f42012-08-07 08:11:26 +00002709 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2710 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002711
Hans Wennborgf3749f42012-08-07 08:11:26 +00002712 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002713 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002714 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002715 << T << Arg->getSourceRange(),
2716 getLocationOfByte(Amt.getStart()),
2717 /*IsStringLocation*/true,
2718 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002719 // Don't do any more checking. We will just emit
2720 // spurious errors.
2721 return false;
2722 }
2723 }
2724 }
2725 return true;
2726}
Ted Kremenek0d277352010-01-29 01:06:55 +00002727
Tom Caree4ee9662010-06-17 19:00:27 +00002728void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002729 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002730 const analyze_printf::OptionalAmount &Amt,
2731 unsigned type,
2732 const char *startSpecifier,
2733 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002734 const analyze_printf::PrintfConversionSpecifier &CS =
2735 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002736
Richard Trieu55733de2011-10-28 00:41:25 +00002737 FixItHint fixit =
2738 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2739 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2740 Amt.getConstantLength()))
2741 : FixItHint();
2742
2743 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2744 << type << CS.toString(),
2745 getLocationOfByte(Amt.getStart()),
2746 /*IsStringLocation*/true,
2747 getSpecifierRange(startSpecifier, specifierLen),
2748 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002749}
2750
Ted Kremenek826a3452010-07-16 02:11:22 +00002751void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002752 const analyze_printf::OptionalFlag &flag,
2753 const char *startSpecifier,
2754 unsigned specifierLen) {
2755 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002756 const analyze_printf::PrintfConversionSpecifier &CS =
2757 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002758 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2759 << flag.toString() << CS.toString(),
2760 getLocationOfByte(flag.getPosition()),
2761 /*IsStringLocation*/true,
2762 getSpecifierRange(startSpecifier, specifierLen),
2763 FixItHint::CreateRemoval(
2764 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002765}
2766
2767void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002768 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002769 const analyze_printf::OptionalFlag &ignoredFlag,
2770 const analyze_printf::OptionalFlag &flag,
2771 const char *startSpecifier,
2772 unsigned specifierLen) {
2773 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002774 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2775 << ignoredFlag.toString() << flag.toString(),
2776 getLocationOfByte(ignoredFlag.getPosition()),
2777 /*IsStringLocation*/true,
2778 getSpecifierRange(startSpecifier, specifierLen),
2779 FixItHint::CreateRemoval(
2780 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002781}
2782
Richard Smith831421f2012-06-25 20:30:08 +00002783// Determines if the specified is a C++ class or struct containing
2784// a member with the specified name and kind (e.g. a CXXMethodDecl named
2785// "c_str()").
2786template<typename MemberKind>
2787static llvm::SmallPtrSet<MemberKind*, 1>
2788CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2789 const RecordType *RT = Ty->getAs<RecordType>();
2790 llvm::SmallPtrSet<MemberKind*, 1> Results;
2791
2792 if (!RT)
2793 return Results;
2794 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2795 if (!RD)
2796 return Results;
2797
2798 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2799 Sema::LookupMemberName);
2800
2801 // We just need to include all members of the right kind turned up by the
2802 // filter, at this point.
2803 if (S.LookupQualifiedName(R, RT->getDecl()))
2804 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2805 NamedDecl *decl = (*I)->getUnderlyingDecl();
2806 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2807 Results.insert(FK);
2808 }
2809 return Results;
2810}
2811
2812// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002813// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002814// Returns true when a c_str() conversion method is found.
2815bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002816 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002817 const CharSourceRange &CSR) {
2818 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2819
2820 MethodSet Results =
2821 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2822
2823 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2824 MI != ME; ++MI) {
2825 const CXXMethodDecl *Method = *MI;
2826 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002827 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002828 // FIXME: Suggest parens if the expression needs them.
2829 SourceLocation EndLoc =
2830 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2831 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2832 << "c_str()"
2833 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2834 return true;
2835 }
2836 }
2837
2838 return false;
2839}
2840
Ted Kremeneke0e53132010-01-28 23:39:18 +00002841bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002842CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002843 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002844 const char *startSpecifier,
2845 unsigned specifierLen) {
2846
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002847 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002848 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002849 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002850
Ted Kremenekbaa40062010-07-19 22:01:06 +00002851 if (FS.consumesDataArgument()) {
2852 if (atFirstArg) {
2853 atFirstArg = false;
2854 usesPositionalArgs = FS.usesPositionalArg();
2855 }
2856 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002857 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2858 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002859 return false;
2860 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002861 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002862
Ted Kremenekefaff192010-02-27 01:41:03 +00002863 // First check if the field width, precision, and conversion specifier
2864 // have matching data arguments.
2865 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2866 startSpecifier, specifierLen)) {
2867 return false;
2868 }
2869
2870 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2871 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002872 return false;
2873 }
2874
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002875 if (!CS.consumesDataArgument()) {
2876 // FIXME: Technically specifying a precision or field width here
2877 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002878 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002879 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002880
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002881 // Consume the argument.
2882 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002883 if (argIndex < NumDataArgs) {
2884 // The check to see if the argIndex is valid will come later.
2885 // We set the bit here because we may exit early from this
2886 // function if we encounter some other error.
2887 CoveredArgs.set(argIndex);
2888 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002889
2890 // Check for using an Objective-C specific conversion specifier
2891 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002892 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002893 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2894 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002895 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002896
Tom Caree4ee9662010-06-17 19:00:27 +00002897 // Check for invalid use of field width
2898 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002899 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002900 startSpecifier, specifierLen);
2901 }
2902
2903 // Check for invalid use of precision
2904 if (!FS.hasValidPrecision()) {
2905 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2906 startSpecifier, specifierLen);
2907 }
2908
2909 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002910 if (!FS.hasValidThousandsGroupingPrefix())
2911 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002912 if (!FS.hasValidLeadingZeros())
2913 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2914 if (!FS.hasValidPlusPrefix())
2915 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002916 if (!FS.hasValidSpacePrefix())
2917 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002918 if (!FS.hasValidAlternativeForm())
2919 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2920 if (!FS.hasValidLeftJustified())
2921 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2922
2923 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002924 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2925 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2926 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002927 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2928 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2929 startSpecifier, specifierLen);
2930
2931 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002932 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002933 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2934 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002935 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002936 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002937 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002938 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2939 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002940
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002941 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2942 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2943
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002944 // The remaining checks depend on the data arguments.
2945 if (HasVAListArg)
2946 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002947
Ted Kremenek666a1972010-07-26 19:45:42 +00002948 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002949 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002950
Jordan Rose48716662012-07-19 18:10:08 +00002951 const Expr *Arg = getDataArg(argIndex);
2952 if (!Arg)
2953 return true;
2954
2955 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002956}
2957
Jordan Roseec087352012-09-05 22:56:26 +00002958static bool requiresParensToAddCast(const Expr *E) {
2959 // FIXME: We should have a general way to reason about operator
2960 // precedence and whether parens are actually needed here.
2961 // Take care of a few common cases where they aren't.
2962 const Expr *Inside = E->IgnoreImpCasts();
2963 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2964 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2965
2966 switch (Inside->getStmtClass()) {
2967 case Stmt::ArraySubscriptExprClass:
2968 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002969 case Stmt::CharacterLiteralClass:
2970 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002971 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002972 case Stmt::FloatingLiteralClass:
2973 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002974 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002975 case Stmt::ObjCArrayLiteralClass:
2976 case Stmt::ObjCBoolLiteralExprClass:
2977 case Stmt::ObjCBoxedExprClass:
2978 case Stmt::ObjCDictionaryLiteralClass:
2979 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002980 case Stmt::ObjCIvarRefExprClass:
2981 case Stmt::ObjCMessageExprClass:
2982 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002983 case Stmt::ObjCStringLiteralClass:
2984 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002985 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002986 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002987 case Stmt::UnaryOperatorClass:
2988 return false;
2989 default:
2990 return true;
2991 }
2992}
2993
Richard Smith831421f2012-06-25 20:30:08 +00002994bool
2995CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2996 const char *StartSpecifier,
2997 unsigned SpecifierLen,
2998 const Expr *E) {
2999 using namespace analyze_format_string;
3000 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003001 // Now type check the data expression that matches the
3002 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003003 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3004 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003005 if (!AT.isValid())
3006 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003007
Jordan Rose448ac3e2012-12-05 18:44:40 +00003008 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003009 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3010 ExprTy = TET->getUnderlyingExpr()->getType();
3011 }
3012
Jordan Rose448ac3e2012-12-05 18:44:40 +00003013 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003014 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003015
Jordan Rose614a8652012-09-05 22:56:19 +00003016 // Look through argument promotions for our error message's reported type.
3017 // This includes the integral and floating promotions, but excludes array
3018 // and function pointer decay; seeing that an argument intended to be a
3019 // string has type 'char [6]' is probably more confusing than 'char *'.
3020 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3021 if (ICE->getCastKind() == CK_IntegralCast ||
3022 ICE->getCastKind() == CK_FloatingCast) {
3023 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003024 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003025
3026 // Check if we didn't match because of an implicit cast from a 'char'
3027 // or 'short' to an 'int'. This is done because printf is a varargs
3028 // function.
3029 if (ICE->getType() == S.Context.IntTy ||
3030 ICE->getType() == S.Context.UnsignedIntTy) {
3031 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003032 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003033 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003034 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003035 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003036 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3037 // Special case for 'a', which has type 'int' in C.
3038 // Note, however, that we do /not/ want to treat multibyte constants like
3039 // 'MooV' as characters! This form is deprecated but still exists.
3040 if (ExprTy == S.Context.IntTy)
3041 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3042 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003043 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003044
Jordan Rose2cd34402012-12-05 18:44:49 +00003045 // %C in an Objective-C context prints a unichar, not a wchar_t.
3046 // If the argument is an integer of some kind, believe the %C and suggest
3047 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003048 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003049 if (ObjCContext &&
3050 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3051 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3052 !ExprTy->isCharType()) {
3053 // 'unichar' is defined as a typedef of unsigned short, but we should
3054 // prefer using the typedef if it is visible.
3055 IntendedTy = S.Context.UnsignedShortTy;
3056
3057 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3058 Sema::LookupOrdinaryName);
3059 if (S.LookupName(Result, S.getCurScope())) {
3060 NamedDecl *ND = Result.getFoundDecl();
3061 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3062 if (TD->getUnderlyingType() == IntendedTy)
3063 IntendedTy = S.Context.getTypedefType(TD);
3064 }
3065 }
3066 }
3067
3068 // Special-case some of Darwin's platform-independence types by suggesting
3069 // casts to primitive types that are known to be large enough.
3070 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00003071 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00003072 // Use a 'while' to peel off layers of typedefs.
3073 QualType TyTy = IntendedTy;
3074 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00003075 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00003076 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00003077 .Case("NSInteger", S.Context.LongTy)
3078 .Case("NSUInteger", S.Context.UnsignedLongTy)
3079 .Case("SInt32", S.Context.IntTy)
3080 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00003081 .Default(QualType());
3082
3083 if (!CastTy.isNull()) {
3084 ShouldNotPrintDirectly = true;
3085 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00003086 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00003087 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00003088 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00003089 }
3090 }
3091
Jordan Rose614a8652012-09-05 22:56:19 +00003092 // We may be able to offer a FixItHint if it is a supported type.
3093 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003094 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003095 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003096
Jordan Rose614a8652012-09-05 22:56:19 +00003097 if (success) {
3098 // Get the fix string from the fixed format specifier
3099 SmallString<16> buf;
3100 llvm::raw_svector_ostream os(buf);
3101 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003102
Jordan Roseec087352012-09-05 22:56:26 +00003103 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3104
Jordan Rose2cd34402012-12-05 18:44:49 +00003105 if (IntendedTy == ExprTy) {
3106 // In this case, the specifier is wrong and should be changed to match
3107 // the argument.
3108 EmitFormatDiagnostic(
3109 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3110 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3111 << E->getSourceRange(),
3112 E->getLocStart(),
3113 /*IsStringLocation*/false,
3114 SpecRange,
3115 FixItHint::CreateReplacement(SpecRange, os.str()));
3116
3117 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003118 // The canonical type for formatting this value is different from the
3119 // actual type of the expression. (This occurs, for example, with Darwin's
3120 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3121 // should be printed as 'long' for 64-bit compatibility.)
3122 // Rather than emitting a normal format/argument mismatch, we want to
3123 // add a cast to the recommended type (and correct the format string
3124 // if necessary).
3125 SmallString<16> CastBuf;
3126 llvm::raw_svector_ostream CastFix(CastBuf);
3127 CastFix << "(";
3128 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3129 CastFix << ")";
3130
3131 SmallVector<FixItHint,4> Hints;
3132 if (!AT.matchesType(S.Context, IntendedTy))
3133 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3134
3135 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3136 // If there's already a cast present, just replace it.
3137 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3138 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3139
3140 } else if (!requiresParensToAddCast(E)) {
3141 // If the expression has high enough precedence,
3142 // just write the C-style cast.
3143 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3144 CastFix.str()));
3145 } else {
3146 // Otherwise, add parens around the expression as well as the cast.
3147 CastFix << "(";
3148 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3149 CastFix.str()));
3150
3151 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3152 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3153 }
3154
Jordan Rose2cd34402012-12-05 18:44:49 +00003155 if (ShouldNotPrintDirectly) {
3156 // The expression has a type that should not be printed directly.
3157 // We extract the name from the typedef because we don't want to show
3158 // the underlying type in the diagnostic.
3159 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00003160
Jordan Rose2cd34402012-12-05 18:44:49 +00003161 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3162 << Name << IntendedTy
3163 << E->getSourceRange(),
3164 E->getLocStart(), /*IsStringLocation=*/false,
3165 SpecRange, Hints);
3166 } else {
3167 // In this case, the expression could be printed using a different
3168 // specifier, but we've decided that the specifier is probably correct
3169 // and we should cast instead. Just use the normal warning message.
3170 EmitFormatDiagnostic(
3171 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3172 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3173 << E->getSourceRange(),
3174 E->getLocStart(), /*IsStringLocation*/false,
3175 SpecRange, Hints);
3176 }
Jordan Roseec087352012-09-05 22:56:26 +00003177 }
Jordan Rose614a8652012-09-05 22:56:19 +00003178 } else {
3179 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3180 SpecifierLen);
3181 // Since the warning for passing non-POD types to variadic functions
3182 // was deferred until now, we emit a warning for non-POD
3183 // arguments here.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003184 if (S.isValidVarArgType(ExprTy) == Sema::VAK_Invalid) {
Jordan Rose614a8652012-09-05 22:56:19 +00003185 unsigned DiagKind;
Jordan Rose448ac3e2012-12-05 18:44:40 +00003186 if (ExprTy->isObjCObjectType())
Jordan Rose614a8652012-09-05 22:56:19 +00003187 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
3188 else
3189 DiagKind = diag::warn_non_pod_vararg_with_format_string;
3190
3191 EmitFormatDiagnostic(
3192 S.PDiag(DiagKind)
Richard Smith80ad52f2013-01-02 11:42:31 +00003193 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003194 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003195 << CallType
3196 << AT.getRepresentativeTypeName(S.Context)
3197 << CSR
3198 << E->getSourceRange(),
3199 E->getLocStart(), /*IsStringLocation*/false, CSR);
3200
3201 checkForCStrMembers(AT, E, CSR);
3202 } else
Richard Trieu55733de2011-10-28 00:41:25 +00003203 EmitFormatDiagnostic(
3204 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Jordan Rose448ac3e2012-12-05 18:44:40 +00003205 << AT.getRepresentativeTypeName(S.Context) << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003206 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00003207 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00003208 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003209 }
3210
Ted Kremeneke0e53132010-01-28 23:39:18 +00003211 return true;
3212}
3213
Ted Kremenek826a3452010-07-16 02:11:22 +00003214//===--- CHECK: Scanf format string checking ------------------------------===//
3215
3216namespace {
3217class CheckScanfHandler : public CheckFormatHandler {
3218public:
3219 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3220 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003221 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003222 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003223 unsigned formatIdx, bool inFunctionCall,
3224 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00003225 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003226 numDataArgs, beg, hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003227 Args, formatIdx, inFunctionCall, CallType)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003228 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003229
3230 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3231 const char *startSpecifier,
3232 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003233
3234 bool HandleInvalidScanfConversionSpecifier(
3235 const analyze_scanf::ScanfSpecifier &FS,
3236 const char *startSpecifier,
3237 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003238
3239 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003240};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003241}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003242
Ted Kremenekb7c21012010-07-16 18:28:03 +00003243void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3244 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003245 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3246 getLocationOfByte(end), /*IsStringLocation*/true,
3247 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003248}
3249
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003250bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3251 const analyze_scanf::ScanfSpecifier &FS,
3252 const char *startSpecifier,
3253 unsigned specifierLen) {
3254
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003255 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003256 FS.getConversionSpecifier();
3257
3258 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3259 getLocationOfByte(CS.getStart()),
3260 startSpecifier, specifierLen,
3261 CS.getStart(), CS.getLength());
3262}
3263
Ted Kremenek826a3452010-07-16 02:11:22 +00003264bool CheckScanfHandler::HandleScanfSpecifier(
3265 const analyze_scanf::ScanfSpecifier &FS,
3266 const char *startSpecifier,
3267 unsigned specifierLen) {
3268
3269 using namespace analyze_scanf;
3270 using namespace analyze_format_string;
3271
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003272 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003273
Ted Kremenekbaa40062010-07-19 22:01:06 +00003274 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3275 // be used to decide if we are using positional arguments consistently.
3276 if (FS.consumesDataArgument()) {
3277 if (atFirstArg) {
3278 atFirstArg = false;
3279 usesPositionalArgs = FS.usesPositionalArg();
3280 }
3281 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003282 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3283 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003284 return false;
3285 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003286 }
3287
3288 // Check if the field with is non-zero.
3289 const OptionalAmount &Amt = FS.getFieldWidth();
3290 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3291 if (Amt.getConstantAmount() == 0) {
3292 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3293 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003294 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3295 getLocationOfByte(Amt.getStart()),
3296 /*IsStringLocation*/true, R,
3297 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003298 }
3299 }
3300
3301 if (!FS.consumesDataArgument()) {
3302 // FIXME: Technically specifying a precision or field width here
3303 // makes no sense. Worth issuing a warning at some point.
3304 return true;
3305 }
3306
3307 // Consume the argument.
3308 unsigned argIndex = FS.getArgIndex();
3309 if (argIndex < NumDataArgs) {
3310 // The check to see if the argIndex is valid will come later.
3311 // We set the bit here because we may exit early from this
3312 // function if we encounter some other error.
3313 CoveredArgs.set(argIndex);
3314 }
3315
Ted Kremenek1e51c202010-07-20 20:04:47 +00003316 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003317 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003318 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3319 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003320 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003321 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003322 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003323 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3324 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003325
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003326 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3327 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3328
Ted Kremenek826a3452010-07-16 02:11:22 +00003329 // The remaining checks depend on the data arguments.
3330 if (HasVAListArg)
3331 return true;
3332
Ted Kremenek666a1972010-07-26 19:45:42 +00003333 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003334 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003335
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003336 // Check that the argument type matches the format specifier.
3337 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003338 if (!Ex)
3339 return true;
3340
Hans Wennborg58e1e542012-08-07 08:59:46 +00003341 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3342 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003343 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003344 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003345 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003346
3347 if (success) {
3348 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003349 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003350 llvm::raw_svector_ostream os(buf);
3351 fixedFS.toString(os);
3352
3353 EmitFormatDiagnostic(
3354 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003355 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003356 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003357 Ex->getLocStart(),
3358 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003359 getSpecifierRange(startSpecifier, specifierLen),
3360 FixItHint::CreateReplacement(
3361 getSpecifierRange(startSpecifier, specifierLen),
3362 os.str()));
3363 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003364 EmitFormatDiagnostic(
3365 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003366 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003367 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003368 Ex->getLocStart(),
3369 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003370 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003371 }
3372 }
3373
Ted Kremenek826a3452010-07-16 02:11:22 +00003374 return true;
3375}
3376
3377void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003378 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003379 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003380 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003381 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003382 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003383
Ted Kremeneke0e53132010-01-28 23:39:18 +00003384 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003385 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003386 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003387 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003388 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3389 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003390 return;
3391 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003392
Ted Kremeneke0e53132010-01-28 23:39:18 +00003393 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003394 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003395 const char *Str = StrRef.data();
3396 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003397 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003398
Ted Kremeneke0e53132010-01-28 23:39:18 +00003399 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003400 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003401 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003402 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003403 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3404 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003405 return;
3406 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003407
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003408 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003409 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003410 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003411 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003412 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003413
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003414 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003415 getLangOpts(),
3416 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003417 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003418 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003419 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003420 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003421 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003422
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003423 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003424 getLangOpts(),
3425 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003426 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003427 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003428}
3429
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003430//===--- CHECK: Standard memory functions ---------------------------------===//
3431
Douglas Gregor2a053a32011-05-03 20:05:22 +00003432/// \brief Determine whether the given type is a dynamic class type (e.g.,
3433/// whether it has a vtable).
3434static bool isDynamicClassType(QualType T) {
3435 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3436 if (CXXRecordDecl *Definition = Record->getDefinition())
3437 if (Definition->isDynamicClass())
3438 return true;
3439
3440 return false;
3441}
3442
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003443/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003444/// otherwise returns NULL.
3445static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003446 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003447 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3448 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3449 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003450
Chandler Carruth000d4282011-06-16 09:09:40 +00003451 return 0;
3452}
3453
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003454/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003455static QualType getSizeOfArgType(const Expr* E) {
3456 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3457 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3458 if (SizeOf->getKind() == clang::UETT_SizeOf)
3459 return SizeOf->getTypeOfArgument();
3460
3461 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003462}
3463
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003464/// \brief Check for dangerous or invalid arguments to memset().
3465///
Chandler Carruth929f0132011-06-03 06:23:57 +00003466/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003467/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3468/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003469///
3470/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003471void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003472 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003473 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003474 assert(BId != 0);
3475
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003476 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003477 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003478 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003479 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003480 return;
3481
Anna Zaks0a151a12012-01-17 00:37:07 +00003482 unsigned LastArg = (BId == Builtin::BImemset ||
3483 BId == Builtin::BIstrndup ? 1 : 2);
3484 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003485 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003486
3487 // We have special checking when the length is a sizeof expression.
3488 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3489 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3490 llvm::FoldingSetNodeID SizeOfArgID;
3491
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003492 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3493 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003494 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003495
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003496 QualType DestTy = Dest->getType();
3497 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3498 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003499
Chandler Carruth000d4282011-06-16 09:09:40 +00003500 // Never warn about void type pointers. This can be used to suppress
3501 // false positives.
3502 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003503 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003504
Chandler Carruth000d4282011-06-16 09:09:40 +00003505 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3506 // actually comparing the expressions for equality. Because computing the
3507 // expression IDs can be expensive, we only do this if the diagnostic is
3508 // enabled.
3509 if (SizeOfArg &&
3510 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3511 SizeOfArg->getExprLoc())) {
3512 // We only compute IDs for expressions if the warning is enabled, and
3513 // cache the sizeof arg's ID.
3514 if (SizeOfArgID == llvm::FoldingSetNodeID())
3515 SizeOfArg->Profile(SizeOfArgID, Context, true);
3516 llvm::FoldingSetNodeID DestID;
3517 Dest->Profile(DestID, Context, true);
3518 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003519 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3520 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003521 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003522 StringRef ReadableName = FnName->getName();
3523
Chandler Carruth000d4282011-06-16 09:09:40 +00003524 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003525 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003526 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003527 if (!PointeeTy->isIncompleteType() &&
3528 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003529 ActionIdx = 2; // If the pointee's size is sizeof(char),
3530 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003531
3532 // If the function is defined as a builtin macro, do not show macro
3533 // expansion.
3534 SourceLocation SL = SizeOfArg->getExprLoc();
3535 SourceRange DSR = Dest->getSourceRange();
3536 SourceRange SSR = SizeOfArg->getSourceRange();
3537 SourceManager &SM = PP.getSourceManager();
3538
3539 if (SM.isMacroArgExpansion(SL)) {
3540 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3541 SL = SM.getSpellingLoc(SL);
3542 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3543 SM.getSpellingLoc(DSR.getEnd()));
3544 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3545 SM.getSpellingLoc(SSR.getEnd()));
3546 }
3547
Anna Zaks90c78322012-05-30 23:14:52 +00003548 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003549 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003550 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003551 << PointeeTy
3552 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003553 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003554 << SSR);
3555 DiagRuntimeBehavior(SL, SizeOfArg,
3556 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3557 << ActionIdx
3558 << SSR);
3559
Chandler Carruth000d4282011-06-16 09:09:40 +00003560 break;
3561 }
3562 }
3563
3564 // Also check for cases where the sizeof argument is the exact same
3565 // type as the memory argument, and where it points to a user-defined
3566 // record type.
3567 if (SizeOfArgTy != QualType()) {
3568 if (PointeeTy->isRecordType() &&
3569 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3570 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3571 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3572 << FnName << SizeOfArgTy << ArgIdx
3573 << PointeeTy << Dest->getSourceRange()
3574 << LenExpr->getSourceRange());
3575 break;
3576 }
Nico Webere4a1c642011-06-14 16:14:58 +00003577 }
3578
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003579 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003580 if (isDynamicClassType(PointeeTy)) {
3581
3582 unsigned OperationType = 0;
3583 // "overwritten" if we're warning about the destination for any call
3584 // but memcmp; otherwise a verb appropriate to the call.
3585 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3586 if (BId == Builtin::BImemcpy)
3587 OperationType = 1;
3588 else if(BId == Builtin::BImemmove)
3589 OperationType = 2;
3590 else if (BId == Builtin::BImemcmp)
3591 OperationType = 3;
3592 }
3593
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003594 DiagRuntimeBehavior(
3595 Dest->getExprLoc(), Dest,
3596 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003597 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003598 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003599 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003600 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003601 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3602 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003603 DiagRuntimeBehavior(
3604 Dest->getExprLoc(), Dest,
3605 PDiag(diag::warn_arc_object_memaccess)
3606 << ArgIdx << FnName << PointeeTy
3607 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003608 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003609 continue;
John McCallf85e1932011-06-15 23:02:42 +00003610
3611 DiagRuntimeBehavior(
3612 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003613 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003614 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3615 break;
3616 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003617 }
3618}
3619
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003620// A little helper routine: ignore addition and subtraction of integer literals.
3621// This intentionally does not ignore all integer constant expressions because
3622// we don't want to remove sizeof().
3623static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3624 Ex = Ex->IgnoreParenCasts();
3625
3626 for (;;) {
3627 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3628 if (!BO || !BO->isAdditiveOp())
3629 break;
3630
3631 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3632 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3633
3634 if (isa<IntegerLiteral>(RHS))
3635 Ex = LHS;
3636 else if (isa<IntegerLiteral>(LHS))
3637 Ex = RHS;
3638 else
3639 break;
3640 }
3641
3642 return Ex;
3643}
3644
Anna Zaks0f38ace2012-08-08 21:42:23 +00003645static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3646 ASTContext &Context) {
3647 // Only handle constant-sized or VLAs, but not flexible members.
3648 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3649 // Only issue the FIXIT for arrays of size > 1.
3650 if (CAT->getSize().getSExtValue() <= 1)
3651 return false;
3652 } else if (!Ty->isVariableArrayType()) {
3653 return false;
3654 }
3655 return true;
3656}
3657
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003658// Warn if the user has made the 'size' argument to strlcpy or strlcat
3659// be the size of the source, instead of the destination.
3660void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3661 IdentifierInfo *FnName) {
3662
3663 // Don't crash if the user has the wrong number of arguments
3664 if (Call->getNumArgs() != 3)
3665 return;
3666
3667 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3668 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3669 const Expr *CompareWithSrc = NULL;
3670
3671 // Look for 'strlcpy(dst, x, sizeof(x))'
3672 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3673 CompareWithSrc = Ex;
3674 else {
3675 // Look for 'strlcpy(dst, x, strlen(x))'
3676 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003677 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003678 && SizeCall->getNumArgs() == 1)
3679 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3680 }
3681 }
3682
3683 if (!CompareWithSrc)
3684 return;
3685
3686 // Determine if the argument to sizeof/strlen is equal to the source
3687 // argument. In principle there's all kinds of things you could do
3688 // here, for instance creating an == expression and evaluating it with
3689 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3690 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3691 if (!SrcArgDRE)
3692 return;
3693
3694 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3695 if (!CompareWithSrcDRE ||
3696 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3697 return;
3698
3699 const Expr *OriginalSizeArg = Call->getArg(2);
3700 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3701 << OriginalSizeArg->getSourceRange() << FnName;
3702
3703 // Output a FIXIT hint if the destination is an array (rather than a
3704 // pointer to an array). This could be enhanced to handle some
3705 // pointers if we know the actual size, like if DstArg is 'array+2'
3706 // we could say 'sizeof(array)-2'.
3707 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003708 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003709 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003710
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003711 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003712 llvm::raw_svector_ostream OS(sizeString);
3713 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003714 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003715 OS << ")";
3716
3717 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3718 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3719 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003720}
3721
Anna Zaksc36bedc2012-02-01 19:08:57 +00003722/// Check if two expressions refer to the same declaration.
3723static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3724 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3725 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3726 return D1->getDecl() == D2->getDecl();
3727 return false;
3728}
3729
3730static const Expr *getStrlenExprArg(const Expr *E) {
3731 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3732 const FunctionDecl *FD = CE->getDirectCallee();
3733 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3734 return 0;
3735 return CE->getArg(0)->IgnoreParenCasts();
3736 }
3737 return 0;
3738}
3739
3740// Warn on anti-patterns as the 'size' argument to strncat.
3741// The correct size argument should look like following:
3742// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3743void Sema::CheckStrncatArguments(const CallExpr *CE,
3744 IdentifierInfo *FnName) {
3745 // Don't crash if the user has the wrong number of arguments.
3746 if (CE->getNumArgs() < 3)
3747 return;
3748 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3749 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3750 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3751
3752 // Identify common expressions, which are wrongly used as the size argument
3753 // to strncat and may lead to buffer overflows.
3754 unsigned PatternType = 0;
3755 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3756 // - sizeof(dst)
3757 if (referToTheSameDecl(SizeOfArg, DstArg))
3758 PatternType = 1;
3759 // - sizeof(src)
3760 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3761 PatternType = 2;
3762 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3763 if (BE->getOpcode() == BO_Sub) {
3764 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3765 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3766 // - sizeof(dst) - strlen(dst)
3767 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3768 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3769 PatternType = 1;
3770 // - sizeof(src) - (anything)
3771 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3772 PatternType = 2;
3773 }
3774 }
3775
3776 if (PatternType == 0)
3777 return;
3778
Anna Zaksafdb0412012-02-03 01:27:37 +00003779 // Generate the diagnostic.
3780 SourceLocation SL = LenArg->getLocStart();
3781 SourceRange SR = LenArg->getSourceRange();
3782 SourceManager &SM = PP.getSourceManager();
3783
3784 // If the function is defined as a builtin macro, do not show macro expansion.
3785 if (SM.isMacroArgExpansion(SL)) {
3786 SL = SM.getSpellingLoc(SL);
3787 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3788 SM.getSpellingLoc(SR.getEnd()));
3789 }
3790
Anna Zaks0f38ace2012-08-08 21:42:23 +00003791 // Check if the destination is an array (rather than a pointer to an array).
3792 QualType DstTy = DstArg->getType();
3793 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3794 Context);
3795 if (!isKnownSizeArray) {
3796 if (PatternType == 1)
3797 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3798 else
3799 Diag(SL, diag::warn_strncat_src_size) << SR;
3800 return;
3801 }
3802
Anna Zaksc36bedc2012-02-01 19:08:57 +00003803 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003804 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003805 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003806 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003807
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003808 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003809 llvm::raw_svector_ostream OS(sizeString);
3810 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003811 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003812 OS << ") - ";
3813 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003814 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003815 OS << ") - 1";
3816
Anna Zaksafdb0412012-02-03 01:27:37 +00003817 Diag(SL, diag::note_strncat_wrong_size)
3818 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003819}
3820
Ted Kremenek06de2762007-08-17 16:46:58 +00003821//===--- CHECK: Return Address of Stack Variable --------------------------===//
3822
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003823static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3824 Decl *ParentDecl);
3825static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3826 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003827
3828/// CheckReturnStackAddr - Check if a return statement returns the address
3829/// of a stack variable.
3830void
3831Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3832 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003833
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003834 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003835 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003836
3837 // Perform checking for returned stack addresses, local blocks,
3838 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003839 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003840 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003841 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003842 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003843 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003844 }
3845
3846 if (stackE == 0)
3847 return; // Nothing suspicious was found.
3848
3849 SourceLocation diagLoc;
3850 SourceRange diagRange;
3851 if (refVars.empty()) {
3852 diagLoc = stackE->getLocStart();
3853 diagRange = stackE->getSourceRange();
3854 } else {
3855 // We followed through a reference variable. 'stackE' contains the
3856 // problematic expression but we will warn at the return statement pointing
3857 // at the reference variable. We will later display the "trail" of
3858 // reference variables using notes.
3859 diagLoc = refVars[0]->getLocStart();
3860 diagRange = refVars[0]->getSourceRange();
3861 }
3862
3863 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3864 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3865 : diag::warn_ret_stack_addr)
3866 << DR->getDecl()->getDeclName() << diagRange;
3867 } else if (isa<BlockExpr>(stackE)) { // local block.
3868 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3869 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3870 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3871 } else { // local temporary.
3872 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3873 : diag::warn_ret_local_temp_addr)
3874 << diagRange;
3875 }
3876
3877 // Display the "trail" of reference variables that we followed until we
3878 // found the problematic expression using notes.
3879 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3880 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3881 // If this var binds to another reference var, show the range of the next
3882 // var, otherwise the var binds to the problematic expression, in which case
3883 // show the range of the expression.
3884 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3885 : stackE->getSourceRange();
3886 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3887 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003888 }
3889}
3890
3891/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3892/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003893/// to a location on the stack, a local block, an address of a label, or a
3894/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003895/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003896/// encounter a subexpression that (1) clearly does not lead to one of the
3897/// above problematic expressions (2) is something we cannot determine leads to
3898/// a problematic expression based on such local checking.
3899///
3900/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3901/// the expression that they point to. Such variables are added to the
3902/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003903///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003904/// EvalAddr processes expressions that are pointers that are used as
3905/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003906/// At the base case of the recursion is a check for the above problematic
3907/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003908///
3909/// This implementation handles:
3910///
3911/// * pointer-to-pointer casts
3912/// * implicit conversions from array references to pointers
3913/// * taking the address of fields
3914/// * arbitrary interplay between "&" and "*" operators
3915/// * pointer arithmetic from an address of a stack variable
3916/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003917static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3918 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003919 if (E->isTypeDependent())
Craig Topperb61c2942013-08-02 05:10:31 +00003920 return NULL;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003921
Ted Kremenek06de2762007-08-17 16:46:58 +00003922 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003923 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003924 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003925 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003926 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003927
Peter Collingbournef111d932011-04-15 00:35:48 +00003928 E = E->IgnoreParens();
3929
Ted Kremenek06de2762007-08-17 16:46:58 +00003930 // Our "symbolic interpreter" is just a dispatch off the currently
3931 // viewed AST node. We then recursively traverse the AST by calling
3932 // EvalAddr and EvalVal appropriately.
3933 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003934 case Stmt::DeclRefExprClass: {
3935 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3936
3937 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3938 // If this is a reference variable, follow through to the expression that
3939 // it points to.
3940 if (V->hasLocalStorage() &&
3941 V->getType()->isReferenceType() && V->hasInit()) {
3942 // Add the reference variable to the "trail".
3943 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003944 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003945 }
3946
3947 return NULL;
3948 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003949
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003950 case Stmt::UnaryOperatorClass: {
3951 // The only unary operator that make sense to handle here
3952 // is AddrOf. All others don't make sense as pointers.
3953 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003954
John McCall2de56d12010-08-25 11:45:40 +00003955 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003956 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003957 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003958 return NULL;
3959 }
Mike Stump1eb44332009-09-09 15:08:12 +00003960
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003961 case Stmt::BinaryOperatorClass: {
3962 // Handle pointer arithmetic. All other binary operators are not valid
3963 // in this context.
3964 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003965 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003966
John McCall2de56d12010-08-25 11:45:40 +00003967 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003968 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003969
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003970 Expr *Base = B->getLHS();
3971
3972 // Determine which argument is the real pointer base. It could be
3973 // the RHS argument instead of the LHS.
3974 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003975
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003976 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003977 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003978 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003979
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003980 // For conditional operators we need to see if either the LHS or RHS are
3981 // valid DeclRefExpr*s. If one of them is valid, we return it.
3982 case Stmt::ConditionalOperatorClass: {
3983 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003984
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003985 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003986 if (Expr *lhsExpr = C->getLHS()) {
3987 // In C++, we can have a throw-expression, which has 'void' type.
3988 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003989 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003990 return LHS;
3991 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003992
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003993 // In C++, we can have a throw-expression, which has 'void' type.
3994 if (C->getRHS()->getType()->isVoidType())
3995 return NULL;
3996
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003997 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003998 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003999
4000 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004001 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004002 return E; // local block.
4003 return NULL;
4004
4005 case Stmt::AddrLabelExprClass:
4006 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004007
John McCall80ee6e82011-11-10 05:35:25 +00004008 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004009 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4010 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004011
Ted Kremenek54b52742008-08-07 00:49:01 +00004012 // For casts, we need to handle conversions from arrays to
4013 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004014 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004015 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004016 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004017 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004018 case Stmt::CXXStaticCastExprClass:
4019 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004020 case Stmt::CXXConstCastExprClass:
4021 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004022 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4023 switch (cast<CastExpr>(E)->getCastKind()) {
4024 case CK_BitCast:
4025 case CK_LValueToRValue:
4026 case CK_NoOp:
4027 case CK_BaseToDerived:
4028 case CK_DerivedToBase:
4029 case CK_UncheckedDerivedToBase:
4030 case CK_Dynamic:
4031 case CK_CPointerToObjCPointerCast:
4032 case CK_BlockPointerToObjCPointerCast:
4033 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004034 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004035
4036 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004037 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004038
4039 default:
4040 return 0;
4041 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004042 }
Mike Stump1eb44332009-09-09 15:08:12 +00004043
Douglas Gregor03e80032011-06-21 17:03:29 +00004044 case Stmt::MaterializeTemporaryExprClass:
4045 if (Expr *Result = EvalAddr(
4046 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004047 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004048 return Result;
4049
4050 return E;
4051
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004052 // Everything else: we simply don't reason about them.
4053 default:
4054 return NULL;
4055 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004056}
Mike Stump1eb44332009-09-09 15:08:12 +00004057
Ted Kremenek06de2762007-08-17 16:46:58 +00004058
4059/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4060/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004061static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4062 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004063do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004064 // We should only be called for evaluating non-pointer expressions, or
4065 // expressions with a pointer type that are not used as references but instead
4066 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00004067
Ted Kremenek06de2762007-08-17 16:46:58 +00004068 // Our "symbolic interpreter" is just a dispatch off the currently
4069 // viewed AST node. We then recursively traverse the AST by calling
4070 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00004071
4072 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00004073 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004074 case Stmt::ImplicitCastExprClass: {
4075 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00004076 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004077 E = IE->getSubExpr();
4078 continue;
4079 }
4080 return NULL;
4081 }
4082
John McCall80ee6e82011-11-10 05:35:25 +00004083 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004084 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004085
Douglas Gregora2813ce2009-10-23 18:54:35 +00004086 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004087 // When we hit a DeclRefExpr we are looking at code that refers to a
4088 // variable's name. If it's not a reference variable we check if it has
4089 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00004090 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004091
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004092 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4093 // Check if it refers to itself, e.g. "int& i = i;".
4094 if (V == ParentDecl)
4095 return DR;
4096
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004097 if (V->hasLocalStorage()) {
4098 if (!V->getType()->isReferenceType())
4099 return DR;
4100
4101 // Reference variable, follow through to the expression that
4102 // it points to.
4103 if (V->hasInit()) {
4104 // Add the reference variable to the "trail".
4105 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004106 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004107 }
4108 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004109 }
Mike Stump1eb44332009-09-09 15:08:12 +00004110
Ted Kremenek06de2762007-08-17 16:46:58 +00004111 return NULL;
4112 }
Mike Stump1eb44332009-09-09 15:08:12 +00004113
Ted Kremenek06de2762007-08-17 16:46:58 +00004114 case Stmt::UnaryOperatorClass: {
4115 // The only unary operator that make sense to handle here
4116 // is Deref. All others don't resolve to a "name." This includes
4117 // handling all sorts of rvalues passed to a unary operator.
4118 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004119
John McCall2de56d12010-08-25 11:45:40 +00004120 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004121 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004122
4123 return NULL;
4124 }
Mike Stump1eb44332009-09-09 15:08:12 +00004125
Ted Kremenek06de2762007-08-17 16:46:58 +00004126 case Stmt::ArraySubscriptExprClass: {
4127 // Array subscripts are potential references to data on the stack. We
4128 // retrieve the DeclRefExpr* for the array variable if it indeed
4129 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004130 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004131 }
Mike Stump1eb44332009-09-09 15:08:12 +00004132
Ted Kremenek06de2762007-08-17 16:46:58 +00004133 case Stmt::ConditionalOperatorClass: {
4134 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004135 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00004136 ConditionalOperator *C = cast<ConditionalOperator>(E);
4137
Anders Carlsson39073232007-11-30 19:04:31 +00004138 // Handle the GNU extension for missing LHS.
4139 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004140 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00004141 return LHS;
4142
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004143 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004144 }
Mike Stump1eb44332009-09-09 15:08:12 +00004145
Ted Kremenek06de2762007-08-17 16:46:58 +00004146 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00004147 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00004148 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Ted Kremenek06de2762007-08-17 16:46:58 +00004150 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00004151 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00004152 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00004153
4154 // Check whether the member type is itself a reference, in which case
4155 // we're not going to refer to the member, but to what the member refers to.
4156 if (M->getMemberDecl()->getType()->isReferenceType())
4157 return NULL;
4158
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004159 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004160 }
Mike Stump1eb44332009-09-09 15:08:12 +00004161
Douglas Gregor03e80032011-06-21 17:03:29 +00004162 case Stmt::MaterializeTemporaryExprClass:
4163 if (Expr *Result = EvalVal(
4164 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004165 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004166 return Result;
4167
4168 return E;
4169
Ted Kremenek06de2762007-08-17 16:46:58 +00004170 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004171 // Check that we don't return or take the address of a reference to a
4172 // temporary. This is only useful in C++.
4173 if (!E->isTypeDependent() && E->isRValue())
4174 return E;
4175
4176 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00004177 return NULL;
4178 }
Ted Kremenek68957a92010-08-04 20:01:07 +00004179} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00004180}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004181
4182//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4183
4184/// Check for comparisons of floating point operands using != and ==.
4185/// Issue a warning if these are no self-comparisons, as they are not likely
4186/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00004187void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00004188 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4189 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004190
4191 // Special case: check for x == x (which is OK).
4192 // Do not emit warnings for such cases.
4193 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4194 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4195 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004196 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004197
4198
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004199 // Special case: check for comparisons against literals that can be exactly
4200 // represented by APFloat. In such cases, do not emit a warning. This
4201 // is a heuristic: often comparison against such literals are used to
4202 // detect if a value in a variable has not changed. This clearly can
4203 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004204 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4205 if (FLL->isExact())
4206 return;
4207 } else
4208 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4209 if (FLR->isExact())
4210 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004211
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004212 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004213 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4214 if (CL->isBuiltinCall())
4215 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004216
David Blaikie980343b2012-07-16 20:47:22 +00004217 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4218 if (CR->isBuiltinCall())
4219 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004220
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004221 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004222 Diag(Loc, diag::warn_floatingpoint_eq)
4223 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004224}
John McCallba26e582010-01-04 23:21:16 +00004225
John McCallf2370c92010-01-06 05:24:50 +00004226//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4227//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004228
John McCallf2370c92010-01-06 05:24:50 +00004229namespace {
John McCallba26e582010-01-04 23:21:16 +00004230
John McCallf2370c92010-01-06 05:24:50 +00004231/// Structure recording the 'active' range of an integer-valued
4232/// expression.
4233struct IntRange {
4234 /// The number of bits active in the int.
4235 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004236
John McCallf2370c92010-01-06 05:24:50 +00004237 /// True if the int is known not to have negative values.
4238 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004239
John McCallf2370c92010-01-06 05:24:50 +00004240 IntRange(unsigned Width, bool NonNegative)
4241 : Width(Width), NonNegative(NonNegative)
4242 {}
John McCallba26e582010-01-04 23:21:16 +00004243
John McCall1844a6e2010-11-10 23:38:19 +00004244 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004245 static IntRange forBoolType() {
4246 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004247 }
4248
John McCall1844a6e2010-11-10 23:38:19 +00004249 /// Returns the range of an opaque value of the given integral type.
4250 static IntRange forValueOfType(ASTContext &C, QualType T) {
4251 return forValueOfCanonicalType(C,
4252 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004253 }
4254
John McCall1844a6e2010-11-10 23:38:19 +00004255 /// Returns the range of an opaque value of a canonical integral type.
4256 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004257 assert(T->isCanonicalUnqualified());
4258
4259 if (const VectorType *VT = dyn_cast<VectorType>(T))
4260 T = VT->getElementType().getTypePtr();
4261 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4262 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004263
David Majnemerf9eaf982013-06-07 22:07:20 +00004264 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004265 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004266 EnumDecl *Enum = ET->getDecl();
4267 if (!Enum->isCompleteDefinition())
4268 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004269
David Majnemerf9eaf982013-06-07 22:07:20 +00004270 unsigned NumPositive = Enum->getNumPositiveBits();
4271 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004272
David Majnemerf9eaf982013-06-07 22:07:20 +00004273 if (NumNegative == 0)
4274 return IntRange(NumPositive, true/*NonNegative*/);
4275 else
4276 return IntRange(std::max(NumPositive + 1, NumNegative),
4277 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004278 }
John McCallf2370c92010-01-06 05:24:50 +00004279
4280 const BuiltinType *BT = cast<BuiltinType>(T);
4281 assert(BT->isInteger());
4282
4283 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4284 }
4285
John McCall1844a6e2010-11-10 23:38:19 +00004286 /// Returns the "target" range of a canonical integral type, i.e.
4287 /// the range of values expressible in the type.
4288 ///
4289 /// This matches forValueOfCanonicalType except that enums have the
4290 /// full range of their type, not the range of their enumerators.
4291 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4292 assert(T->isCanonicalUnqualified());
4293
4294 if (const VectorType *VT = dyn_cast<VectorType>(T))
4295 T = VT->getElementType().getTypePtr();
4296 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4297 T = CT->getElementType().getTypePtr();
4298 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004299 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004300
4301 const BuiltinType *BT = cast<BuiltinType>(T);
4302 assert(BT->isInteger());
4303
4304 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4305 }
4306
4307 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004308 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004309 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004310 L.NonNegative && R.NonNegative);
4311 }
4312
John McCall1844a6e2010-11-10 23:38:19 +00004313 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004314 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004315 return IntRange(std::min(L.Width, R.Width),
4316 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004317 }
4318};
4319
Ted Kremenek0692a192012-01-31 05:37:37 +00004320static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4321 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004322 if (value.isSigned() && value.isNegative())
4323 return IntRange(value.getMinSignedBits(), false);
4324
4325 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004326 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004327
4328 // isNonNegative() just checks the sign bit without considering
4329 // signedness.
4330 return IntRange(value.getActiveBits(), true);
4331}
4332
Ted Kremenek0692a192012-01-31 05:37:37 +00004333static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4334 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004335 if (result.isInt())
4336 return GetValueRange(C, result.getInt(), MaxWidth);
4337
4338 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004339 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4340 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4341 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4342 R = IntRange::join(R, El);
4343 }
John McCallf2370c92010-01-06 05:24:50 +00004344 return R;
4345 }
4346
4347 if (result.isComplexInt()) {
4348 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4349 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4350 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004351 }
4352
4353 // This can happen with lossless casts to intptr_t of "based" lvalues.
4354 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004355 // FIXME: The only reason we need to pass the type in here is to get
4356 // the sign right on this one case. It would be nice if APValue
4357 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004358 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004359 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004360}
John McCallf2370c92010-01-06 05:24:50 +00004361
Eli Friedman09bddcf2013-07-08 20:20:06 +00004362static QualType GetExprType(Expr *E) {
4363 QualType Ty = E->getType();
4364 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4365 Ty = AtomicRHS->getValueType();
4366 return Ty;
4367}
4368
John McCallf2370c92010-01-06 05:24:50 +00004369/// Pseudo-evaluate the given integer expression, estimating the
4370/// range of values it might take.
4371///
4372/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004373static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004374 E = E->IgnoreParens();
4375
4376 // Try a full evaluation first.
4377 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004378 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004379 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004380
4381 // I think we only want to look through implicit casts here; if the
4382 // user has an explicit widening cast, we should treat the value as
4383 // being of the new, wider type.
4384 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004385 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004386 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4387
Eli Friedman09bddcf2013-07-08 20:20:06 +00004388 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004389
John McCall2de56d12010-08-25 11:45:40 +00004390 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004391
John McCallf2370c92010-01-06 05:24:50 +00004392 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004393 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004394 return OutputTypeRange;
4395
4396 IntRange SubRange
4397 = GetExprRange(C, CE->getSubExpr(),
4398 std::min(MaxWidth, OutputTypeRange.Width));
4399
4400 // Bail out if the subexpr's range is as wide as the cast type.
4401 if (SubRange.Width >= OutputTypeRange.Width)
4402 return OutputTypeRange;
4403
4404 // Otherwise, we take the smaller width, and we're non-negative if
4405 // either the output type or the subexpr is.
4406 return IntRange(SubRange.Width,
4407 SubRange.NonNegative || OutputTypeRange.NonNegative);
4408 }
4409
4410 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4411 // If we can fold the condition, just take that operand.
4412 bool CondResult;
4413 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4414 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4415 : CO->getFalseExpr(),
4416 MaxWidth);
4417
4418 // Otherwise, conservatively merge.
4419 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4420 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4421 return IntRange::join(L, R);
4422 }
4423
4424 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4425 switch (BO->getOpcode()) {
4426
4427 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004428 case BO_LAnd:
4429 case BO_LOr:
4430 case BO_LT:
4431 case BO_GT:
4432 case BO_LE:
4433 case BO_GE:
4434 case BO_EQ:
4435 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004436 return IntRange::forBoolType();
4437
John McCall862ff872011-07-13 06:35:24 +00004438 // The type of the assignments is the type of the LHS, so the RHS
4439 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004440 case BO_MulAssign:
4441 case BO_DivAssign:
4442 case BO_RemAssign:
4443 case BO_AddAssign:
4444 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004445 case BO_XorAssign:
4446 case BO_OrAssign:
4447 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00004448 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00004449
John McCall862ff872011-07-13 06:35:24 +00004450 // Simple assignments just pass through the RHS, which will have
4451 // been coerced to the LHS type.
4452 case BO_Assign:
4453 // TODO: bitfields?
4454 return GetExprRange(C, BO->getRHS(), MaxWidth);
4455
John McCallf2370c92010-01-06 05:24:50 +00004456 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004457 case BO_PtrMemD:
4458 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004459 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004460
John McCall60fad452010-01-06 22:07:33 +00004461 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004462 case BO_And:
4463 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004464 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4465 GetExprRange(C, BO->getRHS(), MaxWidth));
4466
John McCallf2370c92010-01-06 05:24:50 +00004467 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004468 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004469 // ...except that we want to treat '1 << (blah)' as logically
4470 // positive. It's an important idiom.
4471 if (IntegerLiteral *I
4472 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4473 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004474 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00004475 return IntRange(R.Width, /*NonNegative*/ true);
4476 }
4477 }
4478 // fallthrough
4479
John McCall2de56d12010-08-25 11:45:40 +00004480 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004481 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004482
John McCall60fad452010-01-06 22:07:33 +00004483 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004484 case BO_Shr:
4485 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004486 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4487
4488 // If the shift amount is a positive constant, drop the width by
4489 // that much.
4490 llvm::APSInt shift;
4491 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4492 shift.isNonNegative()) {
4493 unsigned zext = shift.getZExtValue();
4494 if (zext >= L.Width)
4495 L.Width = (L.NonNegative ? 0 : 1);
4496 else
4497 L.Width -= zext;
4498 }
4499
4500 return L;
4501 }
4502
4503 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004504 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004505 return GetExprRange(C, BO->getRHS(), MaxWidth);
4506
John McCall60fad452010-01-06 22:07:33 +00004507 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004508 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004509 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00004510 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004511 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004512
John McCall00fe7612011-07-14 22:39:48 +00004513 // The width of a division result is mostly determined by the size
4514 // of the LHS.
4515 case BO_Div: {
4516 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004517 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004518 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4519
4520 // If the divisor is constant, use that.
4521 llvm::APSInt divisor;
4522 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4523 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4524 if (log2 >= L.Width)
4525 L.Width = (L.NonNegative ? 0 : 1);
4526 else
4527 L.Width = std::min(L.Width - log2, MaxWidth);
4528 return L;
4529 }
4530
4531 // Otherwise, just use the LHS's width.
4532 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4533 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4534 }
4535
4536 // The result of a remainder can't be larger than the result of
4537 // either side.
4538 case BO_Rem: {
4539 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004540 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004541 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4542 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4543
4544 IntRange meet = IntRange::meet(L, R);
4545 meet.Width = std::min(meet.Width, MaxWidth);
4546 return meet;
4547 }
4548
4549 // The default behavior is okay for these.
4550 case BO_Mul:
4551 case BO_Add:
4552 case BO_Xor:
4553 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004554 break;
4555 }
4556
John McCall00fe7612011-07-14 22:39:48 +00004557 // The default case is to treat the operation as if it were closed
4558 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004559 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4560 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4561 return IntRange::join(L, R);
4562 }
4563
4564 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4565 switch (UO->getOpcode()) {
4566 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004567 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004568 return IntRange::forBoolType();
4569
4570 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004571 case UO_Deref:
4572 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00004573 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004574
4575 default:
4576 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4577 }
4578 }
4579
John McCall993f43f2013-05-06 21:39:12 +00004580 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004581 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004582 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004583
Eli Friedman09bddcf2013-07-08 20:20:06 +00004584 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004585}
John McCall51313c32010-01-04 23:31:57 +00004586
Ted Kremenek0692a192012-01-31 05:37:37 +00004587static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004588 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00004589}
4590
John McCall51313c32010-01-04 23:31:57 +00004591/// Checks whether the given value, which currently has the given
4592/// source semantics, has the same value when coerced through the
4593/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004594static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4595 const llvm::fltSemantics &Src,
4596 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004597 llvm::APFloat truncated = value;
4598
4599 bool ignored;
4600 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4601 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4602
4603 return truncated.bitwiseIsEqual(value);
4604}
4605
4606/// Checks whether the given value, which currently has the given
4607/// source semantics, has the same value when coerced through the
4608/// target semantics.
4609///
4610/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004611static bool IsSameFloatAfterCast(const APValue &value,
4612 const llvm::fltSemantics &Src,
4613 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004614 if (value.isFloat())
4615 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4616
4617 if (value.isVector()) {
4618 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4619 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4620 return false;
4621 return true;
4622 }
4623
4624 assert(value.isComplexFloat());
4625 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4626 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4627}
4628
Ted Kremenek0692a192012-01-31 05:37:37 +00004629static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004630
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004631static bool IsZero(Sema &S, Expr *E) {
4632 // Suppress cases where we are comparing against an enum constant.
4633 if (const DeclRefExpr *DR =
4634 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4635 if (isa<EnumConstantDecl>(DR->getDecl()))
4636 return false;
4637
4638 // Suppress cases where the '0' value is expanded from a macro.
4639 if (E->getLocStart().isMacroID())
4640 return false;
4641
John McCall323ed742010-05-06 08:58:33 +00004642 llvm::APSInt Value;
4643 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4644}
4645
John McCall372e1032010-10-06 00:25:24 +00004646static bool HasEnumType(Expr *E) {
4647 // Strip off implicit integral promotions.
4648 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004649 if (ICE->getCastKind() != CK_IntegralCast &&
4650 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004651 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004652 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004653 }
4654
4655 return E->getType()->isEnumeralType();
4656}
4657
Ted Kremenek0692a192012-01-31 05:37:37 +00004658static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004659 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004660 if (E->isValueDependent())
4661 return;
4662
John McCall2de56d12010-08-25 11:45:40 +00004663 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004664 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004665 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004666 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004667 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004668 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004669 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004670 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004671 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004672 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004673 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004674 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004675 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004676 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004677 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004678 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4679 }
4680}
4681
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004682static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004683 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004684 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004685 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004686 // 0 values are handled later by CheckTrivialUnsignedComparison().
4687 if (Value == 0)
4688 return;
4689
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004690 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004691 QualType OtherT = Other->getType();
4692 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004693 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004694 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004695 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004696 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004697 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004698
4699 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004700 bool CommonSigned = CommonT->isSignedIntegerType();
4701
4702 bool EqualityOnly = false;
4703
4704 // TODO: Investigate using GetExprRange() to get tighter bounds on
4705 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004706 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004707 unsigned OtherWidth = OtherRange.Width;
4708
4709 if (CommonSigned) {
4710 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004711 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004712 // Check that the constant is representable in type OtherT.
4713 if (ConstantSigned) {
4714 if (OtherWidth >= Value.getMinSignedBits())
4715 return;
4716 } else { // !ConstantSigned
4717 if (OtherWidth >= Value.getActiveBits() + 1)
4718 return;
4719 }
4720 } else { // !OtherSigned
4721 // Check that the constant is representable in type OtherT.
4722 // Negative values are out of range.
4723 if (ConstantSigned) {
4724 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4725 return;
4726 } else { // !ConstantSigned
4727 if (OtherWidth >= Value.getActiveBits())
4728 return;
4729 }
4730 }
4731 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004732 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004733 if (OtherWidth >= Value.getActiveBits())
4734 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004735 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004736 // Check to see if the constant is representable in OtherT.
4737 if (OtherWidth > Value.getActiveBits())
4738 return;
4739 // Check to see if the constant is equivalent to a negative value
4740 // cast to CommonT.
4741 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004742 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004743 return;
4744 // The constant value rests between values that OtherT can represent after
4745 // conversion. Relational comparison still works, but equality
4746 // comparisons will be tautological.
4747 EqualityOnly = true;
4748 } else { // OtherSigned && ConstantSigned
4749 assert(0 && "Two signed types converted to unsigned types.");
4750 }
4751 }
4752
4753 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4754
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004755 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004756 if (op == BO_EQ || op == BO_NE) {
4757 IsTrue = op == BO_NE;
4758 } else if (EqualityOnly) {
4759 return;
4760 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004761 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004762 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004763 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004764 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004765 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004766 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004767 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004768 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004769 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004770 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004771
4772 // If this is a comparison to an enum constant, include that
4773 // constant in the diagnostic.
4774 const EnumConstantDecl *ED = 0;
4775 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4776 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4777
4778 SmallString<64> PrettySourceValue;
4779 llvm::raw_svector_ostream OS(PrettySourceValue);
4780 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004781 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004782 else
4783 OS << Value;
4784
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004785 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004786 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004787 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004788}
4789
John McCall323ed742010-05-06 08:58:33 +00004790/// Analyze the operands of the given comparison. Implements the
4791/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004792static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004793 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4794 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004795}
John McCall51313c32010-01-04 23:31:57 +00004796
John McCallba26e582010-01-04 23:21:16 +00004797/// \brief Implements -Wsign-compare.
4798///
Richard Trieudd225092011-09-15 21:56:47 +00004799/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004800static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004801 // The type the comparison is being performed in.
4802 QualType T = E->getLHS()->getType();
4803 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4804 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004805 if (E->isValueDependent())
4806 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004807
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004808 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4809 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004810
4811 bool IsComparisonConstant = false;
4812
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004813 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004814 // of 'true' or 'false'.
4815 if (T->isIntegralType(S.Context)) {
4816 llvm::APSInt RHSValue;
4817 bool IsRHSIntegralLiteral =
4818 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4819 llvm::APSInt LHSValue;
4820 bool IsLHSIntegralLiteral =
4821 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4822 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4823 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4824 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4825 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4826 else
4827 IsComparisonConstant =
4828 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004829 } else if (!T->hasUnsignedIntegerRepresentation())
4830 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004831
John McCall323ed742010-05-06 08:58:33 +00004832 // We don't do anything special if this isn't an unsigned integral
4833 // comparison: we're only interested in integral comparisons, and
4834 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004835 //
4836 // We also don't care about value-dependent expressions or expressions
4837 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004838 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004839 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004840
John McCall323ed742010-05-06 08:58:33 +00004841 // Check to see if one of the (unmodified) operands is of different
4842 // signedness.
4843 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004844 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4845 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004846 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004847 signedOperand = LHS;
4848 unsignedOperand = RHS;
4849 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4850 signedOperand = RHS;
4851 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004852 } else {
John McCall323ed742010-05-06 08:58:33 +00004853 CheckTrivialUnsignedComparison(S, E);
4854 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004855 }
4856
John McCall323ed742010-05-06 08:58:33 +00004857 // Otherwise, calculate the effective range of the signed operand.
4858 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004859
John McCall323ed742010-05-06 08:58:33 +00004860 // Go ahead and analyze implicit conversions in the operands. Note
4861 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004862 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4863 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004864
John McCall323ed742010-05-06 08:58:33 +00004865 // If the signed range is non-negative, -Wsign-compare won't fire,
4866 // but we should still check for comparisons which are always true
4867 // or false.
4868 if (signedRange.NonNegative)
4869 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004870
4871 // For (in)equality comparisons, if the unsigned operand is a
4872 // constant which cannot collide with a overflowed signed operand,
4873 // then reinterpreting the signed operand as unsigned will not
4874 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004875 if (E->isEqualityOp()) {
4876 unsigned comparisonWidth = S.Context.getIntWidth(T);
4877 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004878
John McCall323ed742010-05-06 08:58:33 +00004879 // We should never be unable to prove that the unsigned operand is
4880 // non-negative.
4881 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4882
4883 if (unsignedRange.Width < comparisonWidth)
4884 return;
4885 }
4886
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004887 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4888 S.PDiag(diag::warn_mixed_sign_comparison)
4889 << LHS->getType() << RHS->getType()
4890 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004891}
4892
John McCall15d7d122010-11-11 03:21:53 +00004893/// Analyzes an attempt to assign the given value to a bitfield.
4894///
4895/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004896static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4897 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004898 assert(Bitfield->isBitField());
4899 if (Bitfield->isInvalidDecl())
4900 return false;
4901
John McCall91b60142010-11-11 05:33:51 +00004902 // White-list bool bitfields.
4903 if (Bitfield->getType()->isBooleanType())
4904 return false;
4905
Douglas Gregor46ff3032011-02-04 13:09:01 +00004906 // Ignore value- or type-dependent expressions.
4907 if (Bitfield->getBitWidth()->isValueDependent() ||
4908 Bitfield->getBitWidth()->isTypeDependent() ||
4909 Init->isValueDependent() ||
4910 Init->isTypeDependent())
4911 return false;
4912
John McCall15d7d122010-11-11 03:21:53 +00004913 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4914
Richard Smith80d4b552011-12-28 19:48:30 +00004915 llvm::APSInt Value;
4916 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004917 return false;
4918
John McCall15d7d122010-11-11 03:21:53 +00004919 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004920 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004921
4922 if (OriginalWidth <= FieldWidth)
4923 return false;
4924
Eli Friedman3a643af2012-01-26 23:11:39 +00004925 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004926 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004927 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004928
Eli Friedman3a643af2012-01-26 23:11:39 +00004929 // Check whether the stored value is equal to the original value.
4930 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004931 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004932 return false;
4933
Eli Friedman3a643af2012-01-26 23:11:39 +00004934 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004935 // therefore don't strictly fit into a signed bitfield of width 1.
4936 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004937 return false;
4938
John McCall15d7d122010-11-11 03:21:53 +00004939 std::string PrettyValue = Value.toString(10);
4940 std::string PrettyTrunc = TruncatedValue.toString(10);
4941
4942 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4943 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4944 << Init->getSourceRange();
4945
4946 return true;
4947}
4948
John McCallbeb22aa2010-11-09 23:24:47 +00004949/// Analyze the given simple or compound assignment for warning-worthy
4950/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004951static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004952 // Just recurse on the LHS.
4953 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4954
4955 // We want to recurse on the RHS as normal unless we're assigning to
4956 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00004957 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004958 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00004959 E->getOperatorLoc())) {
4960 // Recurse, ignoring any implicit conversions on the RHS.
4961 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4962 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004963 }
4964 }
4965
4966 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4967}
4968
John McCall51313c32010-01-04 23:31:57 +00004969/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004970static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004971 SourceLocation CContext, unsigned diag,
4972 bool pruneControlFlow = false) {
4973 if (pruneControlFlow) {
4974 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4975 S.PDiag(diag)
4976 << SourceType << T << E->getSourceRange()
4977 << SourceRange(CContext));
4978 return;
4979 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004980 S.Diag(E->getExprLoc(), diag)
4981 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4982}
4983
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004984/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004985static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004986 SourceLocation CContext, unsigned diag,
4987 bool pruneControlFlow = false) {
4988 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004989}
4990
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004991/// Diagnose an implicit cast from a literal expression. Does not warn when the
4992/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004993void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4994 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004995 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004996 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004997 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004998 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4999 T->hasUnsignedIntegerRepresentation());
5000 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00005001 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005002 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00005003 return;
5004
David Blaikiebe0ee872012-05-15 16:56:36 +00005005 SmallString<16> PrettySourceValue;
5006 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00005007 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00005008 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5009 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5010 else
David Blaikiede7e7b82012-05-15 17:18:27 +00005011 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00005012
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005013 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00005014 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5015 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00005016}
5017
John McCall091f23f2010-11-09 22:22:12 +00005018std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5019 if (!Range.Width) return "0";
5020
5021 llvm::APSInt ValueInRange = Value;
5022 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00005023 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00005024 return ValueInRange.toString(10);
5025}
5026
Hans Wennborg88617a22012-08-28 15:44:30 +00005027static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5028 if (!isa<ImplicitCastExpr>(Ex))
5029 return false;
5030
5031 Expr *InnerE = Ex->IgnoreParenImpCasts();
5032 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5033 const Type *Source =
5034 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5035 if (Target->isDependentType())
5036 return false;
5037
5038 const BuiltinType *FloatCandidateBT =
5039 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5040 const Type *BoolCandidateType = ToBool ? Target : Source;
5041
5042 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5043 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5044}
5045
5046void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5047 SourceLocation CC) {
5048 unsigned NumArgs = TheCall->getNumArgs();
5049 for (unsigned i = 0; i < NumArgs; ++i) {
5050 Expr *CurrA = TheCall->getArg(i);
5051 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5052 continue;
5053
5054 bool IsSwapped = ((i > 0) &&
5055 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5056 IsSwapped |= ((i < (NumArgs - 1)) &&
5057 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5058 if (IsSwapped) {
5059 // Warn on this floating-point to bool conversion.
5060 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5061 CurrA->getType(), CC,
5062 diag::warn_impcast_floating_point_to_bool);
5063 }
5064 }
5065}
5066
John McCall323ed742010-05-06 08:58:33 +00005067void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005068 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00005069 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00005070
John McCall323ed742010-05-06 08:58:33 +00005071 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5072 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5073 if (Source == Target) return;
5074 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00005075
Chandler Carruth108f7562011-07-26 05:40:03 +00005076 // If the conversion context location is invalid don't complain. We also
5077 // don't want to emit a warning if the issue occurs from the expansion of
5078 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5079 // delay this check as long as possible. Once we detect we are in that
5080 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00005081 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00005082 return;
5083
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005084 // Diagnose implicit casts to bool.
5085 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5086 if (isa<StringLiteral>(E))
5087 // Warn on string literal to bool. Checks for string literals in logical
5088 // expressions, for instances, assert(0 && "error here"), is prevented
5089 // by a check in AnalyzeImplicitConversions().
5090 return DiagnoseImpCast(S, E, T, CC,
5091 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00005092 if (Source->isFunctionType()) {
5093 // Warn on function to bool. Checks free functions and static member
5094 // functions. Weakly imported functions are excluded from the check,
5095 // since it's common to test their value to check whether the linker
5096 // found a definition for them.
5097 ValueDecl *D = 0;
5098 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5099 D = R->getDecl();
5100 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5101 D = M->getMemberDecl();
5102 }
5103
5104 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00005105 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5106 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5107 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00005108 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5109 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5110 QualType ReturnType;
5111 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00005112 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00005113 if (!ReturnType.isNull()
5114 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5115 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5116 << FixItHint::CreateInsertion(
5117 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00005118 return;
5119 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00005120 }
5121 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005122 }
John McCall51313c32010-01-04 23:31:57 +00005123
5124 // Strip vector types.
5125 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005126 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005127 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005128 return;
John McCallb4eb64d2010-10-08 02:01:28 +00005129 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005130 }
Chris Lattnerb792b302011-06-14 04:51:15 +00005131
5132 // If the vector cast is cast between two vectors of the same size, it is
5133 // a bitcast, not a conversion.
5134 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5135 return;
John McCall51313c32010-01-04 23:31:57 +00005136
5137 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5138 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5139 }
5140
5141 // Strip complex types.
5142 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005143 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005144 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005145 return;
5146
John McCallb4eb64d2010-10-08 02:01:28 +00005147 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005148 }
John McCall51313c32010-01-04 23:31:57 +00005149
5150 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5151 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5152 }
5153
5154 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5155 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5156
5157 // If the source is floating point...
5158 if (SourceBT && SourceBT->isFloatingPoint()) {
5159 // ...and the target is floating point...
5160 if (TargetBT && TargetBT->isFloatingPoint()) {
5161 // ...then warn if we're dropping FP rank.
5162
5163 // Builtin FP kinds are ordered by increasing FP rank.
5164 if (SourceBT->getKind() > TargetBT->getKind()) {
5165 // Don't warn about float constants that are precisely
5166 // representable in the target type.
5167 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005168 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00005169 // Value might be a float, a float vector, or a float complex.
5170 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00005171 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5172 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00005173 return;
5174 }
5175
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005176 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005177 return;
5178
John McCallb4eb64d2010-10-08 02:01:28 +00005179 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00005180 }
5181 return;
5182 }
5183
Ted Kremenekef9ff882011-03-10 20:03:42 +00005184 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00005185 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005186 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005187 return;
5188
Chandler Carrutha5b93322011-02-17 11:05:49 +00005189 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00005190 // We also want to warn on, e.g., "int i = -1.234"
5191 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5192 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5193 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5194
Chandler Carruthf65076e2011-04-10 08:36:24 +00005195 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5196 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005197 } else {
5198 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5199 }
5200 }
John McCall51313c32010-01-04 23:31:57 +00005201
Hans Wennborg88617a22012-08-28 15:44:30 +00005202 // If the target is bool, warn if expr is a function or method call.
5203 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5204 isa<CallExpr>(E)) {
5205 // Check last argument of function call to see if it is an
5206 // implicit cast from a type matching the type the result
5207 // is being cast to.
5208 CallExpr *CEx = cast<CallExpr>(E);
5209 unsigned NumArgs = CEx->getNumArgs();
5210 if (NumArgs > 0) {
5211 Expr *LastA = CEx->getArg(NumArgs - 1);
5212 Expr *InnerE = LastA->IgnoreParenImpCasts();
5213 const Type *InnerType =
5214 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5215 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5216 // Warn on this floating-point to bool conversion
5217 DiagnoseImpCast(S, E, T, CC,
5218 diag::warn_impcast_floating_point_to_bool);
5219 }
5220 }
5221 }
John McCall51313c32010-01-04 23:31:57 +00005222 return;
5223 }
5224
Richard Trieu1838ca52011-05-29 19:59:02 +00005225 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005226 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005227 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005228 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005229 SourceLocation Loc = E->getSourceRange().getBegin();
5230 if (Loc.isMacroID())
5231 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005232 if (!Loc.isMacroID() || CC.isMacroID())
5233 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5234 << T << clang::SourceRange(CC)
5235 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00005236 }
5237
David Blaikieb26331b2012-06-19 21:19:06 +00005238 if (!Source->isIntegerType() || !Target->isIntegerType())
5239 return;
5240
David Blaikiebe0ee872012-05-15 16:56:36 +00005241 // TODO: remove this early return once the false positives for constant->bool
5242 // in templates, macros, etc, are reduced or removed.
5243 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5244 return;
5245
John McCall323ed742010-05-06 08:58:33 +00005246 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005247 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005248
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005249 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005250 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005251 // TODO: this should happen for bitfield stores, too.
5252 llvm::APSInt Value(32);
5253 if (E->isIntegerConstantExpr(Value, S.Context)) {
5254 if (S.SourceMgr.isInSystemMacro(CC))
5255 return;
5256
John McCall091f23f2010-11-09 22:22:12 +00005257 std::string PrettySourceValue = Value.toString(10);
5258 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005259
Ted Kremenek5e745da2011-10-22 02:37:33 +00005260 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5261 S.PDiag(diag::warn_impcast_integer_precision_constant)
5262 << PrettySourceValue << PrettyTargetValue
5263 << E->getType() << T << E->getSourceRange()
5264 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005265 return;
5266 }
5267
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005268 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5269 if (S.SourceMgr.isInSystemMacro(CC))
5270 return;
5271
David Blaikie37050842012-04-12 22:40:54 +00005272 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005273 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5274 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005275 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005276 }
5277
5278 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5279 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5280 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005281
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005282 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005283 return;
5284
John McCall323ed742010-05-06 08:58:33 +00005285 unsigned DiagID = diag::warn_impcast_integer_sign;
5286
5287 // Traditionally, gcc has warned about this under -Wsign-compare.
5288 // We also want to warn about it in -Wconversion.
5289 // So if -Wconversion is off, use a completely identical diagnostic
5290 // in the sign-compare group.
5291 // The conditional-checking code will
5292 if (ICContext) {
5293 DiagID = diag::warn_impcast_integer_sign_conditional;
5294 *ICContext = true;
5295 }
5296
John McCallb4eb64d2010-10-08 02:01:28 +00005297 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005298 }
5299
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005300 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005301 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5302 // type, to give us better diagnostics.
5303 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005304 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005305 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5306 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5307 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5308 SourceType = S.Context.getTypeDeclType(Enum);
5309 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5310 }
5311 }
5312
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005313 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5314 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005315 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5316 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005317 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005318 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005319 return;
5320
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005321 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005322 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005323 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005324
John McCall51313c32010-01-04 23:31:57 +00005325 return;
5326}
5327
David Blaikie9fb1ac52012-05-15 21:57:38 +00005328void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5329 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005330
5331void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005332 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005333 E = E->IgnoreParenImpCasts();
5334
5335 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005336 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005337
John McCallb4eb64d2010-10-08 02:01:28 +00005338 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005339 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005340 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005341 return;
5342}
5343
David Blaikie9fb1ac52012-05-15 21:57:38 +00005344void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5345 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005346 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005347
5348 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005349 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5350 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005351
5352 // If -Wconversion would have warned about either of the candidates
5353 // for a signedness conversion to the context type...
5354 if (!Suspicious) return;
5355
5356 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005357 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5358 CC))
John McCall323ed742010-05-06 08:58:33 +00005359 return;
5360
John McCall323ed742010-05-06 08:58:33 +00005361 // ...then check whether it would have warned about either of the
5362 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005363 if (E->getType() == T) return;
5364
5365 Suspicious = false;
5366 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5367 E->getType(), CC, &Suspicious);
5368 if (!Suspicious)
5369 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005370 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005371}
5372
5373/// AnalyzeImplicitConversions - Find and report any interesting
5374/// implicit conversions in the given expression. There are a couple
5375/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005376void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005377 QualType T = OrigE->getType();
5378 Expr *E = OrigE->IgnoreParenImpCasts();
5379
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005380 if (E->isTypeDependent() || E->isValueDependent())
5381 return;
5382
John McCall323ed742010-05-06 08:58:33 +00005383 // For conditional operators, we analyze the arguments as if they
5384 // were being fed directly into the output.
5385 if (isa<ConditionalOperator>(E)) {
5386 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005387 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005388 return;
5389 }
5390
Hans Wennborg88617a22012-08-28 15:44:30 +00005391 // Check implicit argument conversions for function calls.
5392 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5393 CheckImplicitArgumentConversions(S, Call, CC);
5394
John McCall323ed742010-05-06 08:58:33 +00005395 // Go ahead and check any implicit conversions we might have skipped.
5396 // The non-canonical typecheck is just an optimization;
5397 // CheckImplicitConversion will filter out dead implicit conversions.
5398 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005399 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005400
5401 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005402
5403 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005404 if (POE->getResultExpr())
5405 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005406 }
5407
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005408 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5409 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5410
John McCall323ed742010-05-06 08:58:33 +00005411 // Skip past explicit casts.
5412 if (isa<ExplicitCastExpr>(E)) {
5413 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005414 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005415 }
5416
John McCallbeb22aa2010-11-09 23:24:47 +00005417 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5418 // Do a somewhat different check with comparison operators.
5419 if (BO->isComparisonOp())
5420 return AnalyzeComparison(S, BO);
5421
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005422 // And with simple assignments.
5423 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005424 return AnalyzeAssignment(S, BO);
5425 }
John McCall323ed742010-05-06 08:58:33 +00005426
5427 // These break the otherwise-useful invariant below. Fortunately,
5428 // we don't really need to recurse into them, because any internal
5429 // expressions should have been analyzed already when they were
5430 // built into statements.
5431 if (isa<StmtExpr>(E)) return;
5432
5433 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005434 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005435
5436 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005437 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005438 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5439 bool IsLogicalOperator = BO && BO->isLogicalOp();
5440 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005441 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005442 if (!ChildExpr)
5443 continue;
5444
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005445 if (IsLogicalOperator &&
5446 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5447 // Ignore checking string literals that are in logical operators.
5448 continue;
5449 AnalyzeImplicitConversions(S, ChildExpr, CC);
5450 }
John McCall323ed742010-05-06 08:58:33 +00005451}
5452
5453} // end anonymous namespace
5454
5455/// Diagnoses "dangerous" implicit conversions within the given
5456/// expression (which is a full expression). Implements -Wconversion
5457/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005458///
5459/// \param CC the "context" location of the implicit conversion, i.e.
5460/// the most location of the syntactic entity requiring the implicit
5461/// conversion
5462void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005463 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005464 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005465 return;
5466
5467 // Don't diagnose for value- or type-dependent expressions.
5468 if (E->isTypeDependent() || E->isValueDependent())
5469 return;
5470
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005471 // Check for array bounds violations in cases where the check isn't triggered
5472 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5473 // ArraySubscriptExpr is on the RHS of a variable initialization.
5474 CheckArrayAccess(E);
5475
John McCallb4eb64d2010-10-08 02:01:28 +00005476 // This is not the right CC for (e.g.) a variable initialization.
5477 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005478}
5479
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005480/// Diagnose when expression is an integer constant expression and its evaluation
5481/// results in integer overflow
5482void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005483 if (isa<BinaryOperator>(E->IgnoreParens())) {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005484 llvm::SmallVector<PartialDiagnosticAt, 4> Diags;
5485 E->EvaluateForOverflow(Context, &Diags);
5486 }
5487}
5488
Richard Smith6c3af3d2013-01-17 01:17:56 +00005489namespace {
5490/// \brief Visitor for expressions which looks for unsequenced operations on the
5491/// same object.
5492class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005493 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5494
Richard Smith6c3af3d2013-01-17 01:17:56 +00005495 /// \brief A tree of sequenced regions within an expression. Two regions are
5496 /// unsequenced if one is an ancestor or a descendent of the other. When we
5497 /// finish processing an expression with sequencing, such as a comma
5498 /// expression, we fold its tree nodes into its parent, since they are
5499 /// unsequenced with respect to nodes we will visit later.
5500 class SequenceTree {
5501 struct Value {
5502 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5503 unsigned Parent : 31;
5504 bool Merged : 1;
5505 };
5506 llvm::SmallVector<Value, 8> Values;
5507
5508 public:
5509 /// \brief A region within an expression which may be sequenced with respect
5510 /// to some other region.
5511 class Seq {
5512 explicit Seq(unsigned N) : Index(N) {}
5513 unsigned Index;
5514 friend class SequenceTree;
5515 public:
5516 Seq() : Index(0) {}
5517 };
5518
5519 SequenceTree() { Values.push_back(Value(0)); }
5520 Seq root() const { return Seq(0); }
5521
5522 /// \brief Create a new sequence of operations, which is an unsequenced
5523 /// subset of \p Parent. This sequence of operations is sequenced with
5524 /// respect to other children of \p Parent.
5525 Seq allocate(Seq Parent) {
5526 Values.push_back(Value(Parent.Index));
5527 return Seq(Values.size() - 1);
5528 }
5529
5530 /// \brief Merge a sequence of operations into its parent.
5531 void merge(Seq S) {
5532 Values[S.Index].Merged = true;
5533 }
5534
5535 /// \brief Determine whether two operations are unsequenced. This operation
5536 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5537 /// should have been merged into its parent as appropriate.
5538 bool isUnsequenced(Seq Cur, Seq Old) {
5539 unsigned C = representative(Cur.Index);
5540 unsigned Target = representative(Old.Index);
5541 while (C >= Target) {
5542 if (C == Target)
5543 return true;
5544 C = Values[C].Parent;
5545 }
5546 return false;
5547 }
5548
5549 private:
5550 /// \brief Pick a representative for a sequence.
5551 unsigned representative(unsigned K) {
5552 if (Values[K].Merged)
5553 // Perform path compression as we go.
5554 return Values[K].Parent = representative(Values[K].Parent);
5555 return K;
5556 }
5557 };
5558
5559 /// An object for which we can track unsequenced uses.
5560 typedef NamedDecl *Object;
5561
5562 /// Different flavors of object usage which we track. We only track the
5563 /// least-sequenced usage of each kind.
5564 enum UsageKind {
5565 /// A read of an object. Multiple unsequenced reads are OK.
5566 UK_Use,
5567 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005568 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005569 UK_ModAsValue,
5570 /// A modification of an object which is not sequenced before the value
5571 /// computation of the expression, such as n++.
5572 UK_ModAsSideEffect,
5573
5574 UK_Count = UK_ModAsSideEffect + 1
5575 };
5576
5577 struct Usage {
5578 Usage() : Use(0), Seq() {}
5579 Expr *Use;
5580 SequenceTree::Seq Seq;
5581 };
5582
5583 struct UsageInfo {
5584 UsageInfo() : Diagnosed(false) {}
5585 Usage Uses[UK_Count];
5586 /// Have we issued a diagnostic for this variable already?
5587 bool Diagnosed;
5588 };
5589 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5590
5591 Sema &SemaRef;
5592 /// Sequenced regions within the expression.
5593 SequenceTree Tree;
5594 /// Declaration modifications and references which we have seen.
5595 UsageInfoMap UsageMap;
5596 /// The region we are currently within.
5597 SequenceTree::Seq Region;
5598 /// Filled in with declarations which were modified as a side-effect
5599 /// (that is, post-increment operations).
5600 llvm::SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005601 /// Expressions to check later. We defer checking these to reduce
5602 /// stack usage.
5603 llvm::SmallVectorImpl<Expr*> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005604
5605 /// RAII object wrapping the visitation of a sequenced subexpression of an
5606 /// expression. At the end of this process, the side-effects of the evaluation
5607 /// become sequenced with respect to the value computation of the result, so
5608 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5609 /// UK_ModAsValue.
5610 struct SequencedSubexpression {
5611 SequencedSubexpression(SequenceChecker &Self)
5612 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5613 Self.ModAsSideEffect = &ModAsSideEffect;
5614 }
5615 ~SequencedSubexpression() {
5616 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5617 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5618 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5619 Self.addUsage(U, ModAsSideEffect[I].first,
5620 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5621 }
5622 Self.ModAsSideEffect = OldModAsSideEffect;
5623 }
5624
5625 SequenceChecker &Self;
5626 llvm::SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5627 llvm::SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5628 };
5629
Richard Smith67470052013-06-20 22:21:56 +00005630 /// RAII object wrapping the visitation of a subexpression which we might
5631 /// choose to evaluate as a constant. If any subexpression is evaluated and
5632 /// found to be non-constant, this allows us to suppress the evaluation of
5633 /// the outer expression.
5634 class EvaluationTracker {
5635 public:
5636 EvaluationTracker(SequenceChecker &Self)
5637 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5638 Self.EvalTracker = this;
5639 }
5640 ~EvaluationTracker() {
5641 Self.EvalTracker = Prev;
5642 if (Prev)
5643 Prev->EvalOK &= EvalOK;
5644 }
5645
5646 bool evaluate(const Expr *E, bool &Result) {
5647 if (!EvalOK || E->isValueDependent())
5648 return false;
5649 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5650 return EvalOK;
5651 }
5652
5653 private:
5654 SequenceChecker &Self;
5655 EvaluationTracker *Prev;
5656 bool EvalOK;
5657 } *EvalTracker;
5658
Richard Smith6c3af3d2013-01-17 01:17:56 +00005659 /// \brief Find the object which is produced by the specified expression,
5660 /// if any.
5661 Object getObject(Expr *E, bool Mod) const {
5662 E = E->IgnoreParenCasts();
5663 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5664 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5665 return getObject(UO->getSubExpr(), Mod);
5666 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5667 if (BO->getOpcode() == BO_Comma)
5668 return getObject(BO->getRHS(), Mod);
5669 if (Mod && BO->isAssignmentOp())
5670 return getObject(BO->getLHS(), Mod);
5671 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5672 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5673 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5674 return ME->getMemberDecl();
5675 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5676 // FIXME: If this is a reference, map through to its value.
5677 return DRE->getDecl();
5678 return 0;
5679 }
5680
5681 /// \brief Note that an object was modified or used by an expression.
5682 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5683 Usage &U = UI.Uses[UK];
5684 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5685 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5686 ModAsSideEffect->push_back(std::make_pair(O, U));
5687 U.Use = Ref;
5688 U.Seq = Region;
5689 }
5690 }
5691 /// \brief Check whether a modification or use conflicts with a prior usage.
5692 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5693 bool IsModMod) {
5694 if (UI.Diagnosed)
5695 return;
5696
5697 const Usage &U = UI.Uses[OtherKind];
5698 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5699 return;
5700
5701 Expr *Mod = U.Use;
5702 Expr *ModOrUse = Ref;
5703 if (OtherKind == UK_Use)
5704 std::swap(Mod, ModOrUse);
5705
5706 SemaRef.Diag(Mod->getExprLoc(),
5707 IsModMod ? diag::warn_unsequenced_mod_mod
5708 : diag::warn_unsequenced_mod_use)
5709 << O << SourceRange(ModOrUse->getExprLoc());
5710 UI.Diagnosed = true;
5711 }
5712
5713 void notePreUse(Object O, Expr *Use) {
5714 UsageInfo &U = UsageMap[O];
5715 // Uses conflict with other modifications.
5716 checkUsage(O, U, Use, UK_ModAsValue, false);
5717 }
5718 void notePostUse(Object O, Expr *Use) {
5719 UsageInfo &U = UsageMap[O];
5720 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5721 addUsage(U, O, Use, UK_Use);
5722 }
5723
5724 void notePreMod(Object O, Expr *Mod) {
5725 UsageInfo &U = UsageMap[O];
5726 // Modifications conflict with other modifications and with uses.
5727 checkUsage(O, U, Mod, UK_ModAsValue, true);
5728 checkUsage(O, U, Mod, UK_Use, false);
5729 }
5730 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5731 UsageInfo &U = UsageMap[O];
5732 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5733 addUsage(U, O, Use, UK);
5734 }
5735
5736public:
Richard Smith1a2dcd52013-01-17 23:18:09 +00005737 SequenceChecker(Sema &S, Expr *E,
5738 llvm::SmallVectorImpl<Expr*> &WorkList)
Richard Smith0c0b3902013-06-30 10:40:20 +00005739 : Base(S.Context), SemaRef(S), Region(Tree.root()),
5740 ModAsSideEffect(0), WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005741 Visit(E);
5742 }
5743
5744 void VisitStmt(Stmt *S) {
5745 // Skip all statements which aren't expressions for now.
5746 }
5747
5748 void VisitExpr(Expr *E) {
5749 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005750 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005751 }
5752
5753 void VisitCastExpr(CastExpr *E) {
5754 Object O = Object();
5755 if (E->getCastKind() == CK_LValueToRValue)
5756 O = getObject(E->getSubExpr(), false);
5757
5758 if (O)
5759 notePreUse(O, E);
5760 VisitExpr(E);
5761 if (O)
5762 notePostUse(O, E);
5763 }
5764
5765 void VisitBinComma(BinaryOperator *BO) {
5766 // C++11 [expr.comma]p1:
5767 // Every value computation and side effect associated with the left
5768 // expression is sequenced before every value computation and side
5769 // effect associated with the right expression.
5770 SequenceTree::Seq LHS = Tree.allocate(Region);
5771 SequenceTree::Seq RHS = Tree.allocate(Region);
5772 SequenceTree::Seq OldRegion = Region;
5773
5774 {
5775 SequencedSubexpression SeqLHS(*this);
5776 Region = LHS;
5777 Visit(BO->getLHS());
5778 }
5779
5780 Region = RHS;
5781 Visit(BO->getRHS());
5782
5783 Region = OldRegion;
5784
5785 // Forget that LHS and RHS are sequenced. They are both unsequenced
5786 // with respect to other stuff.
5787 Tree.merge(LHS);
5788 Tree.merge(RHS);
5789 }
5790
5791 void VisitBinAssign(BinaryOperator *BO) {
5792 // The modification is sequenced after the value computation of the LHS
5793 // and RHS, so check it before inspecting the operands and update the
5794 // map afterwards.
5795 Object O = getObject(BO->getLHS(), true);
5796 if (!O)
5797 return VisitExpr(BO);
5798
5799 notePreMod(O, BO);
5800
5801 // C++11 [expr.ass]p7:
5802 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5803 // only once.
5804 //
5805 // Therefore, for a compound assignment operator, O is considered used
5806 // everywhere except within the evaluation of E1 itself.
5807 if (isa<CompoundAssignOperator>(BO))
5808 notePreUse(O, BO);
5809
5810 Visit(BO->getLHS());
5811
5812 if (isa<CompoundAssignOperator>(BO))
5813 notePostUse(O, BO);
5814
5815 Visit(BO->getRHS());
5816
Richard Smith418dd3e2013-06-26 23:16:51 +00005817 // C++11 [expr.ass]p1:
5818 // the assignment is sequenced [...] before the value computation of the
5819 // assignment expression.
5820 // C11 6.5.16/3 has no such rule.
5821 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5822 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005823 }
5824 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5825 VisitBinAssign(CAO);
5826 }
5827
5828 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5829 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5830 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5831 Object O = getObject(UO->getSubExpr(), true);
5832 if (!O)
5833 return VisitExpr(UO);
5834
5835 notePreMod(O, UO);
5836 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005837 // C++11 [expr.pre.incr]p1:
5838 // the expression ++x is equivalent to x+=1
5839 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5840 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005841 }
5842
5843 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5844 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5845 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5846 Object O = getObject(UO->getSubExpr(), true);
5847 if (!O)
5848 return VisitExpr(UO);
5849
5850 notePreMod(O, UO);
5851 Visit(UO->getSubExpr());
5852 notePostMod(O, UO, UK_ModAsSideEffect);
5853 }
5854
5855 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5856 void VisitBinLOr(BinaryOperator *BO) {
5857 // The side-effects of the LHS of an '&&' are sequenced before the
5858 // value computation of the RHS, and hence before the value computation
5859 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5860 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00005861 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005862 {
5863 SequencedSubexpression Sequenced(*this);
5864 Visit(BO->getLHS());
5865 }
5866
5867 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005868 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005869 if (!Result)
5870 Visit(BO->getRHS());
5871 } else {
5872 // Check for unsequenced operations in the RHS, treating it as an
5873 // entirely separate evaluation.
5874 //
5875 // FIXME: If there are operations in the RHS which are unsequenced
5876 // with respect to operations outside the RHS, and those operations
5877 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005878 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005879 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005880 }
5881 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00005882 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005883 {
5884 SequencedSubexpression Sequenced(*this);
5885 Visit(BO->getLHS());
5886 }
5887
5888 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005889 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005890 if (Result)
5891 Visit(BO->getRHS());
5892 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005893 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005894 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005895 }
5896
5897 // Only visit the condition, unless we can be sure which subexpression will
5898 // be chosen.
5899 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00005900 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00005901 {
5902 SequencedSubexpression Sequenced(*this);
5903 Visit(CO->getCond());
5904 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005905
5906 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005907 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00005908 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005909 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005910 WorkList.push_back(CO->getTrueExpr());
5911 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005912 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005913 }
5914
Richard Smith0c0b3902013-06-30 10:40:20 +00005915 void VisitCallExpr(CallExpr *CE) {
5916 // C++11 [intro.execution]p15:
5917 // When calling a function [...], every value computation and side effect
5918 // associated with any argument expression, or with the postfix expression
5919 // designating the called function, is sequenced before execution of every
5920 // expression or statement in the body of the function [and thus before
5921 // the value computation of its result].
5922 SequencedSubexpression Sequenced(*this);
5923 Base::VisitCallExpr(CE);
5924
5925 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
5926 }
5927
Richard Smith6c3af3d2013-01-17 01:17:56 +00005928 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00005929 // This is a call, so all subexpressions are sequenced before the result.
5930 SequencedSubexpression Sequenced(*this);
5931
Richard Smith6c3af3d2013-01-17 01:17:56 +00005932 if (!CCE->isListInitialization())
5933 return VisitExpr(CCE);
5934
5935 // In C++11, list initializations are sequenced.
5936 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5937 SequenceTree::Seq Parent = Region;
5938 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5939 E = CCE->arg_end();
5940 I != E; ++I) {
5941 Region = Tree.allocate(Parent);
5942 Elts.push_back(Region);
5943 Visit(*I);
5944 }
5945
5946 // Forget that the initializers are sequenced.
5947 Region = Parent;
5948 for (unsigned I = 0; I < Elts.size(); ++I)
5949 Tree.merge(Elts[I]);
5950 }
5951
5952 void VisitInitListExpr(InitListExpr *ILE) {
5953 if (!SemaRef.getLangOpts().CPlusPlus11)
5954 return VisitExpr(ILE);
5955
5956 // In C++11, list initializations are sequenced.
5957 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5958 SequenceTree::Seq Parent = Region;
5959 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
5960 Expr *E = ILE->getInit(I);
5961 if (!E) continue;
5962 Region = Tree.allocate(Parent);
5963 Elts.push_back(Region);
5964 Visit(E);
5965 }
5966
5967 // Forget that the initializers are sequenced.
5968 Region = Parent;
5969 for (unsigned I = 0; I < Elts.size(); ++I)
5970 Tree.merge(Elts[I]);
5971 }
5972};
5973}
5974
5975void Sema::CheckUnsequencedOperations(Expr *E) {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005976 llvm::SmallVector<Expr*, 8> WorkList;
5977 WorkList.push_back(E);
5978 while (!WorkList.empty()) {
5979 Expr *Item = WorkList.back();
5980 WorkList.pop_back();
5981 SequenceChecker(*this, Item, WorkList);
5982 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005983}
5984
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005985void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
5986 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005987 CheckImplicitConversions(E, CheckLoc);
5988 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005989 if (!IsConstexpr && !E->isValueDependent())
5990 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005991}
5992
John McCall15d7d122010-11-11 03:21:53 +00005993void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5994 FieldDecl *BitField,
5995 Expr *Init) {
5996 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5997}
5998
Mike Stumpf8c49212010-01-21 03:59:47 +00005999/// CheckParmsForFunctionDef - Check that the parameters of the given
6000/// function are appropriate for the definition of a function. This
6001/// takes care of any checks that cannot be performed on the
6002/// declaration itself, e.g., that the types of each of the function
6003/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00006004bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6005 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00006006 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006007 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00006008 for (; P != PEnd; ++P) {
6009 ParmVarDecl *Param = *P;
6010
Mike Stumpf8c49212010-01-21 03:59:47 +00006011 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6012 // function declarator that is part of a function definition of
6013 // that function shall not have incomplete type.
6014 //
6015 // This is also C++ [dcl.fct]p6.
6016 if (!Param->isInvalidDecl() &&
6017 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00006018 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006019 Param->setInvalidDecl();
6020 HasInvalidParm = true;
6021 }
6022
6023 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6024 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00006025 if (CheckParameterNames &&
6026 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00006027 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006028 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00006029 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00006030
6031 // C99 6.7.5.3p12:
6032 // If the function declarator is not part of a definition of that
6033 // function, parameters may have incomplete type and may use the [*]
6034 // notation in their sequences of declarator specifiers to specify
6035 // variable length array types.
6036 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006037 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00006038 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00006039 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00006040 // information is added for it.
6041 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006042 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00006043 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006044 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00006045 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006046
6047 // MSVC destroys objects passed by value in the callee. Therefore a
6048 // function definition which takes such a parameter must be able to call the
6049 // object's destructor.
6050 if (getLangOpts().CPlusPlus &&
6051 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6052 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6053 FinalizeVarWithDestructor(Param, RT);
6054 }
Mike Stumpf8c49212010-01-21 03:59:47 +00006055 }
6056
6057 return HasInvalidParm;
6058}
John McCallb7f4ffe2010-08-12 21:44:57 +00006059
6060/// CheckCastAlign - Implements -Wcast-align, which warns when a
6061/// pointer cast increases the alignment requirements.
6062void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6063 // This is actually a lot of work to potentially be doing on every
6064 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006065 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6066 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00006067 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00006068 return;
6069
6070 // Ignore dependent types.
6071 if (T->isDependentType() || Op->getType()->isDependentType())
6072 return;
6073
6074 // Require that the destination be a pointer type.
6075 const PointerType *DestPtr = T->getAs<PointerType>();
6076 if (!DestPtr) return;
6077
6078 // If the destination has alignment 1, we're done.
6079 QualType DestPointee = DestPtr->getPointeeType();
6080 if (DestPointee->isIncompleteType()) return;
6081 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6082 if (DestAlign.isOne()) return;
6083
6084 // Require that the source be a pointer type.
6085 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6086 if (!SrcPtr) return;
6087 QualType SrcPointee = SrcPtr->getPointeeType();
6088
6089 // Whitelist casts from cv void*. We already implicitly
6090 // whitelisted casts to cv void*, since they have alignment 1.
6091 // Also whitelist casts involving incomplete types, which implicitly
6092 // includes 'void'.
6093 if (SrcPointee->isIncompleteType()) return;
6094
6095 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6096 if (SrcAlign >= DestAlign) return;
6097
6098 Diag(TRange.getBegin(), diag::warn_cast_align)
6099 << Op->getType() << T
6100 << static_cast<unsigned>(SrcAlign.getQuantity())
6101 << static_cast<unsigned>(DestAlign.getQuantity())
6102 << TRange << Op->getSourceRange();
6103}
6104
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006105static const Type* getElementType(const Expr *BaseExpr) {
6106 const Type* EltType = BaseExpr->getType().getTypePtr();
6107 if (EltType->isAnyPointerType())
6108 return EltType->getPointeeType().getTypePtr();
6109 else if (EltType->isArrayType())
6110 return EltType->getBaseElementTypeUnsafe();
6111 return EltType;
6112}
6113
Chandler Carruthc2684342011-08-05 09:10:50 +00006114/// \brief Check whether this array fits the idiom of a size-one tail padded
6115/// array member of a struct.
6116///
6117/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6118/// commonly used to emulate flexible arrays in C89 code.
6119static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6120 const NamedDecl *ND) {
6121 if (Size != 1 || !ND) return false;
6122
6123 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6124 if (!FD) return false;
6125
6126 // Don't consider sizes resulting from macro expansions or template argument
6127 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00006128
6129 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006130 while (TInfo) {
6131 TypeLoc TL = TInfo->getTypeLoc();
6132 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00006133 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6134 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006135 TInfo = TDL->getTypeSourceInfo();
6136 continue;
6137 }
David Blaikie39e6ab42013-02-18 22:06:02 +00006138 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6139 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00006140 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6141 return false;
6142 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006143 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00006144 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006145
6146 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00006147 if (!RD) return false;
6148 if (RD->isUnion()) return false;
6149 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6150 if (!CRD->isStandardLayout()) return false;
6151 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006152
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00006153 // See if this is the last field decl in the record.
6154 const Decl *D = FD;
6155 while ((D = D->getNextDeclInContext()))
6156 if (isa<FieldDecl>(D))
6157 return false;
6158 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00006159}
6160
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006161void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006162 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00006163 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00006164 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006165 if (IndexExpr->isValueDependent())
6166 return;
6167
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00006168 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006169 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00006170 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006171 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00006172 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00006173 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00006174
Chandler Carruth34064582011-02-17 20:55:08 +00006175 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006176 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00006177 return;
Richard Smith25b009a2011-12-16 19:31:14 +00006178 if (IndexNegated)
6179 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006180
Chandler Carruthba447122011-08-05 08:07:29 +00006181 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00006182 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6183 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00006184 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00006185 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00006186
Ted Kremenek9e060ca2011-02-23 23:06:04 +00006187 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00006188 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00006189 if (!size.isStrictlyPositive())
6190 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006191
6192 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00006193 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006194 // Make sure we're comparing apples to apples when comparing index to size
6195 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6196 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00006197 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00006198 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006199 if (ptrarith_typesize != array_typesize) {
6200 // There's a cast to a different size type involved
6201 uint64_t ratio = array_typesize / ptrarith_typesize;
6202 // TODO: Be smarter about handling cases where array_typesize is not a
6203 // multiple of ptrarith_typesize
6204 if (ptrarith_typesize * ratio == array_typesize)
6205 size *= llvm::APInt(size.getBitWidth(), ratio);
6206 }
6207 }
6208
Chandler Carruth34064582011-02-17 20:55:08 +00006209 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006210 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006211 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006212 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006213
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006214 // For array subscripting the index must be less than size, but for pointer
6215 // arithmetic also allow the index (offset) to be equal to size since
6216 // computing the next address after the end of the array is legal and
6217 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006218 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006219 return;
6220
6221 // Also don't warn for arrays of size 1 which are members of some
6222 // structure. These are often used to approximate flexible arrays in C89
6223 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006224 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006225 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006226
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006227 // Suppress the warning if the subscript expression (as identified by the
6228 // ']' location) and the index expression are both from macro expansions
6229 // within a system header.
6230 if (ASE) {
6231 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6232 ASE->getRBracketLoc());
6233 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6234 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6235 IndexExpr->getLocStart());
6236 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
6237 return;
6238 }
6239 }
6240
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006241 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006242 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006243 DiagID = diag::warn_array_index_exceeds_bounds;
6244
6245 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6246 PDiag(DiagID) << index.toString(10, true)
6247 << size.toString(10, true)
6248 << (unsigned)size.getLimitedValue(~0U)
6249 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006250 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006251 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006252 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006253 DiagID = diag::warn_ptr_arith_precedes_bounds;
6254 if (index.isNegative()) index = -index;
6255 }
6256
6257 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6258 PDiag(DiagID) << index.toString(10, true)
6259 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006260 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006261
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006262 if (!ND) {
6263 // Try harder to find a NamedDecl to point at in the note.
6264 while (const ArraySubscriptExpr *ASE =
6265 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6266 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6267 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6268 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6269 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6270 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6271 }
6272
Chandler Carruth35001ca2011-02-17 21:10:52 +00006273 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006274 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6275 PDiag(diag::note_array_index_out_of_bounds)
6276 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006277}
6278
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006279void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006280 int AllowOnePastEnd = 0;
6281 while (expr) {
6282 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006283 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006284 case Stmt::ArraySubscriptExprClass: {
6285 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006286 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006287 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006288 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006289 }
6290 case Stmt::UnaryOperatorClass: {
6291 // Only unwrap the * and & unary operators
6292 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6293 expr = UO->getSubExpr();
6294 switch (UO->getOpcode()) {
6295 case UO_AddrOf:
6296 AllowOnePastEnd++;
6297 break;
6298 case UO_Deref:
6299 AllowOnePastEnd--;
6300 break;
6301 default:
6302 return;
6303 }
6304 break;
6305 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006306 case Stmt::ConditionalOperatorClass: {
6307 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6308 if (const Expr *lhs = cond->getLHS())
6309 CheckArrayAccess(lhs);
6310 if (const Expr *rhs = cond->getRHS())
6311 CheckArrayAccess(rhs);
6312 return;
6313 }
6314 default:
6315 return;
6316 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006317 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006318}
John McCallf85e1932011-06-15 23:02:42 +00006319
6320//===--- CHECK: Objective-C retain cycles ----------------------------------//
6321
6322namespace {
6323 struct RetainCycleOwner {
6324 RetainCycleOwner() : Variable(0), Indirect(false) {}
6325 VarDecl *Variable;
6326 SourceRange Range;
6327 SourceLocation Loc;
6328 bool Indirect;
6329
6330 void setLocsFrom(Expr *e) {
6331 Loc = e->getExprLoc();
6332 Range = e->getSourceRange();
6333 }
6334 };
6335}
6336
6337/// Consider whether capturing the given variable can possibly lead to
6338/// a retain cycle.
6339static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006340 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006341 // lifetime. In MRR, it's captured strongly if the variable is
6342 // __block and has an appropriate type.
6343 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6344 return false;
6345
6346 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006347 if (ref)
6348 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006349 return true;
6350}
6351
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006352static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006353 while (true) {
6354 e = e->IgnoreParens();
6355 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6356 switch (cast->getCastKind()) {
6357 case CK_BitCast:
6358 case CK_LValueBitCast:
6359 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006360 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006361 e = cast->getSubExpr();
6362 continue;
6363
John McCallf85e1932011-06-15 23:02:42 +00006364 default:
6365 return false;
6366 }
6367 }
6368
6369 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6370 ObjCIvarDecl *ivar = ref->getDecl();
6371 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6372 return false;
6373
6374 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006375 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006376 return false;
6377
6378 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6379 owner.Indirect = true;
6380 return true;
6381 }
6382
6383 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6384 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6385 if (!var) return false;
6386 return considerVariable(var, ref, owner);
6387 }
6388
John McCallf85e1932011-06-15 23:02:42 +00006389 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6390 if (member->isArrow()) return false;
6391
6392 // Don't count this as an indirect ownership.
6393 e = member->getBase();
6394 continue;
6395 }
6396
John McCall4b9c2d22011-11-06 09:01:30 +00006397 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6398 // Only pay attention to pseudo-objects on property references.
6399 ObjCPropertyRefExpr *pre
6400 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6401 ->IgnoreParens());
6402 if (!pre) return false;
6403 if (pre->isImplicitProperty()) return false;
6404 ObjCPropertyDecl *property = pre->getExplicitProperty();
6405 if (!property->isRetaining() &&
6406 !(property->getPropertyIvarDecl() &&
6407 property->getPropertyIvarDecl()->getType()
6408 .getObjCLifetime() == Qualifiers::OCL_Strong))
6409 return false;
6410
6411 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006412 if (pre->isSuperReceiver()) {
6413 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6414 if (!owner.Variable)
6415 return false;
6416 owner.Loc = pre->getLocation();
6417 owner.Range = pre->getSourceRange();
6418 return true;
6419 }
John McCall4b9c2d22011-11-06 09:01:30 +00006420 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6421 ->getSourceExpr());
6422 continue;
6423 }
6424
John McCallf85e1932011-06-15 23:02:42 +00006425 // Array ivars?
6426
6427 return false;
6428 }
6429}
6430
6431namespace {
6432 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6433 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6434 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6435 Variable(variable), Capturer(0) {}
6436
6437 VarDecl *Variable;
6438 Expr *Capturer;
6439
6440 void VisitDeclRefExpr(DeclRefExpr *ref) {
6441 if (ref->getDecl() == Variable && !Capturer)
6442 Capturer = ref;
6443 }
6444
John McCallf85e1932011-06-15 23:02:42 +00006445 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6446 if (Capturer) return;
6447 Visit(ref->getBase());
6448 if (Capturer && ref->isFreeIvar())
6449 Capturer = ref;
6450 }
6451
6452 void VisitBlockExpr(BlockExpr *block) {
6453 // Look inside nested blocks
6454 if (block->getBlockDecl()->capturesVariable(Variable))
6455 Visit(block->getBlockDecl()->getBody());
6456 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006457
6458 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6459 if (Capturer) return;
6460 if (OVE->getSourceExpr())
6461 Visit(OVE->getSourceExpr());
6462 }
John McCallf85e1932011-06-15 23:02:42 +00006463 };
6464}
6465
6466/// Check whether the given argument is a block which captures a
6467/// variable.
6468static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6469 assert(owner.Variable && owner.Loc.isValid());
6470
6471 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006472
6473 // Look through [^{...} copy] and Block_copy(^{...}).
6474 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6475 Selector Cmd = ME->getSelector();
6476 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6477 e = ME->getInstanceReceiver();
6478 if (!e)
6479 return 0;
6480 e = e->IgnoreParenCasts();
6481 }
6482 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6483 if (CE->getNumArgs() == 1) {
6484 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006485 if (Fn) {
6486 const IdentifierInfo *FnI = Fn->getIdentifier();
6487 if (FnI && FnI->isStr("_Block_copy")) {
6488 e = CE->getArg(0)->IgnoreParenCasts();
6489 }
6490 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006491 }
6492 }
6493
John McCallf85e1932011-06-15 23:02:42 +00006494 BlockExpr *block = dyn_cast<BlockExpr>(e);
6495 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6496 return 0;
6497
6498 FindCaptureVisitor visitor(S.Context, owner.Variable);
6499 visitor.Visit(block->getBlockDecl()->getBody());
6500 return visitor.Capturer;
6501}
6502
6503static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6504 RetainCycleOwner &owner) {
6505 assert(capturer);
6506 assert(owner.Variable && owner.Loc.isValid());
6507
6508 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6509 << owner.Variable << capturer->getSourceRange();
6510 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6511 << owner.Indirect << owner.Range;
6512}
6513
6514/// Check for a keyword selector that starts with the word 'add' or
6515/// 'set'.
6516static bool isSetterLikeSelector(Selector sel) {
6517 if (sel.isUnarySelector()) return false;
6518
Chris Lattner5f9e2722011-07-23 10:55:15 +00006519 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006520 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006521 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006522 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006523 else if (str.startswith("add")) {
6524 // Specially whitelist 'addOperationWithBlock:'.
6525 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6526 return false;
6527 str = str.substr(3);
6528 }
John McCallf85e1932011-06-15 23:02:42 +00006529 else
6530 return false;
6531
6532 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006533 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006534}
6535
6536/// Check a message send to see if it's likely to cause a retain cycle.
6537void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6538 // Only check instance methods whose selector looks like a setter.
6539 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6540 return;
6541
6542 // Try to find a variable that the receiver is strongly owned by.
6543 RetainCycleOwner owner;
6544 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006545 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006546 return;
6547 } else {
6548 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6549 owner.Variable = getCurMethodDecl()->getSelfDecl();
6550 owner.Loc = msg->getSuperLoc();
6551 owner.Range = msg->getSuperLoc();
6552 }
6553
6554 // Check whether the receiver is captured by any of the arguments.
6555 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6556 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6557 return diagnoseRetainCycle(*this, capturer, owner);
6558}
6559
6560/// Check a property assign to see if it's likely to cause a retain cycle.
6561void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6562 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006563 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006564 return;
6565
6566 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6567 diagnoseRetainCycle(*this, capturer, owner);
6568}
6569
Jordan Rosee10f4d32012-09-15 02:48:31 +00006570void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6571 RetainCycleOwner Owner;
6572 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6573 return;
6574
6575 // Because we don't have an expression for the variable, we have to set the
6576 // location explicitly here.
6577 Owner.Loc = Var->getLocation();
6578 Owner.Range = Var->getSourceRange();
6579
6580 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6581 diagnoseRetainCycle(*this, Capturer, Owner);
6582}
6583
Ted Kremenek9d084012012-12-21 08:04:28 +00006584static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6585 Expr *RHS, bool isProperty) {
6586 // Check if RHS is an Objective-C object literal, which also can get
6587 // immediately zapped in a weak reference. Note that we explicitly
6588 // allow ObjCStringLiterals, since those are designed to never really die.
6589 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006590
Ted Kremenekd3292c82012-12-21 22:46:35 +00006591 // This enum needs to match with the 'select' in
6592 // warn_objc_arc_literal_assign (off-by-1).
6593 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6594 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6595 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006596
6597 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006598 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006599 << (isProperty ? 0 : 1)
6600 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006601
6602 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006603}
6604
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006605static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6606 Qualifiers::ObjCLifetime LT,
6607 Expr *RHS, bool isProperty) {
6608 // Strip off any implicit cast added to get to the one ARC-specific.
6609 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6610 if (cast->getCastKind() == CK_ARCConsumeObject) {
6611 S.Diag(Loc, diag::warn_arc_retained_assign)
6612 << (LT == Qualifiers::OCL_ExplicitNone)
6613 << (isProperty ? 0 : 1)
6614 << RHS->getSourceRange();
6615 return true;
6616 }
6617 RHS = cast->getSubExpr();
6618 }
6619
6620 if (LT == Qualifiers::OCL_Weak &&
6621 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6622 return true;
6623
6624 return false;
6625}
6626
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006627bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6628 QualType LHS, Expr *RHS) {
6629 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6630
6631 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6632 return false;
6633
6634 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6635 return true;
6636
6637 return false;
6638}
6639
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006640void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6641 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006642 QualType LHSType;
6643 // PropertyRef on LHS type need be directly obtained from
6644 // its declaration as it has a PsuedoType.
6645 ObjCPropertyRefExpr *PRE
6646 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6647 if (PRE && !PRE->isImplicitProperty()) {
6648 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6649 if (PD)
6650 LHSType = PD->getType();
6651 }
6652
6653 if (LHSType.isNull())
6654 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006655
6656 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6657
6658 if (LT == Qualifiers::OCL_Weak) {
6659 DiagnosticsEngine::Level Level =
6660 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6661 if (Level != DiagnosticsEngine::Ignored)
6662 getCurFunction()->markSafeWeakUse(LHS);
6663 }
6664
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006665 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6666 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006667
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006668 // FIXME. Check for other life times.
6669 if (LT != Qualifiers::OCL_None)
6670 return;
6671
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006672 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006673 if (PRE->isImplicitProperty())
6674 return;
6675 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6676 if (!PD)
6677 return;
6678
Bill Wendlingad017fa2012-12-20 19:22:21 +00006679 unsigned Attributes = PD->getPropertyAttributes();
6680 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006681 // when 'assign' attribute was not explicitly specified
6682 // by user, ignore it and rely on property type itself
6683 // for lifetime info.
6684 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6685 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6686 LHSType->isObjCRetainableType())
6687 return;
6688
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006689 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006690 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006691 Diag(Loc, diag::warn_arc_retained_property_assign)
6692 << RHS->getSourceRange();
6693 return;
6694 }
6695 RHS = cast->getSubExpr();
6696 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006697 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006698 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006699 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6700 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006701 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006702 }
6703}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006704
6705//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6706
6707namespace {
6708bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6709 SourceLocation StmtLoc,
6710 const NullStmt *Body) {
6711 // Do not warn if the body is a macro that expands to nothing, e.g:
6712 //
6713 // #define CALL(x)
6714 // if (condition)
6715 // CALL(0);
6716 //
6717 if (Body->hasLeadingEmptyMacro())
6718 return false;
6719
6720 // Get line numbers of statement and body.
6721 bool StmtLineInvalid;
6722 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6723 &StmtLineInvalid);
6724 if (StmtLineInvalid)
6725 return false;
6726
6727 bool BodyLineInvalid;
6728 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6729 &BodyLineInvalid);
6730 if (BodyLineInvalid)
6731 return false;
6732
6733 // Warn if null statement and body are on the same line.
6734 if (StmtLine != BodyLine)
6735 return false;
6736
6737 return true;
6738}
6739} // Unnamed namespace
6740
6741void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6742 const Stmt *Body,
6743 unsigned DiagID) {
6744 // Since this is a syntactic check, don't emit diagnostic for template
6745 // instantiations, this just adds noise.
6746 if (CurrentInstantiationScope)
6747 return;
6748
6749 // The body should be a null statement.
6750 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6751 if (!NBody)
6752 return;
6753
6754 // Do the usual checks.
6755 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6756 return;
6757
6758 Diag(NBody->getSemiLoc(), DiagID);
6759 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6760}
6761
6762void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6763 const Stmt *PossibleBody) {
6764 assert(!CurrentInstantiationScope); // Ensured by caller
6765
6766 SourceLocation StmtLoc;
6767 const Stmt *Body;
6768 unsigned DiagID;
6769 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6770 StmtLoc = FS->getRParenLoc();
6771 Body = FS->getBody();
6772 DiagID = diag::warn_empty_for_body;
6773 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6774 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6775 Body = WS->getBody();
6776 DiagID = diag::warn_empty_while_body;
6777 } else
6778 return; // Neither `for' nor `while'.
6779
6780 // The body should be a null statement.
6781 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6782 if (!NBody)
6783 return;
6784
6785 // Skip expensive checks if diagnostic is disabled.
6786 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6787 DiagnosticsEngine::Ignored)
6788 return;
6789
6790 // Do the usual checks.
6791 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6792 return;
6793
6794 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6795 // noise level low, emit diagnostics only if for/while is followed by a
6796 // CompoundStmt, e.g.:
6797 // for (int i = 0; i < n; i++);
6798 // {
6799 // a(i);
6800 // }
6801 // or if for/while is followed by a statement with more indentation
6802 // than for/while itself:
6803 // for (int i = 0; i < n; i++);
6804 // a(i);
6805 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6806 if (!ProbableTypo) {
6807 bool BodyColInvalid;
6808 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6809 PossibleBody->getLocStart(),
6810 &BodyColInvalid);
6811 if (BodyColInvalid)
6812 return;
6813
6814 bool StmtColInvalid;
6815 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6816 S->getLocStart(),
6817 &StmtColInvalid);
6818 if (StmtColInvalid)
6819 return;
6820
6821 if (BodyCol > StmtCol)
6822 ProbableTypo = true;
6823 }
6824
6825 if (ProbableTypo) {
6826 Diag(NBody->getSemiLoc(), DiagID);
6827 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6828 }
6829}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006830
6831//===--- Layout compatibility ----------------------------------------------//
6832
6833namespace {
6834
6835bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6836
6837/// \brief Check if two enumeration types are layout-compatible.
6838bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6839 // C++11 [dcl.enum] p8:
6840 // Two enumeration types are layout-compatible if they have the same
6841 // underlying type.
6842 return ED1->isComplete() && ED2->isComplete() &&
6843 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6844}
6845
6846/// \brief Check if two fields are layout-compatible.
6847bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6848 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6849 return false;
6850
6851 if (Field1->isBitField() != Field2->isBitField())
6852 return false;
6853
6854 if (Field1->isBitField()) {
6855 // Make sure that the bit-fields are the same length.
6856 unsigned Bits1 = Field1->getBitWidthValue(C);
6857 unsigned Bits2 = Field2->getBitWidthValue(C);
6858
6859 if (Bits1 != Bits2)
6860 return false;
6861 }
6862
6863 return true;
6864}
6865
6866/// \brief Check if two standard-layout structs are layout-compatible.
6867/// (C++11 [class.mem] p17)
6868bool isLayoutCompatibleStruct(ASTContext &C,
6869 RecordDecl *RD1,
6870 RecordDecl *RD2) {
6871 // If both records are C++ classes, check that base classes match.
6872 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6873 // If one of records is a CXXRecordDecl we are in C++ mode,
6874 // thus the other one is a CXXRecordDecl, too.
6875 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6876 // Check number of base classes.
6877 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6878 return false;
6879
6880 // Check the base classes.
6881 for (CXXRecordDecl::base_class_const_iterator
6882 Base1 = D1CXX->bases_begin(),
6883 BaseEnd1 = D1CXX->bases_end(),
6884 Base2 = D2CXX->bases_begin();
6885 Base1 != BaseEnd1;
6886 ++Base1, ++Base2) {
6887 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6888 return false;
6889 }
6890 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6891 // If only RD2 is a C++ class, it should have zero base classes.
6892 if (D2CXX->getNumBases() > 0)
6893 return false;
6894 }
6895
6896 // Check the fields.
6897 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6898 Field2End = RD2->field_end(),
6899 Field1 = RD1->field_begin(),
6900 Field1End = RD1->field_end();
6901 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6902 if (!isLayoutCompatible(C, *Field1, *Field2))
6903 return false;
6904 }
6905 if (Field1 != Field1End || Field2 != Field2End)
6906 return false;
6907
6908 return true;
6909}
6910
6911/// \brief Check if two standard-layout unions are layout-compatible.
6912/// (C++11 [class.mem] p18)
6913bool isLayoutCompatibleUnion(ASTContext &C,
6914 RecordDecl *RD1,
6915 RecordDecl *RD2) {
6916 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6917 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6918 Field2End = RD2->field_end();
6919 Field2 != Field2End; ++Field2) {
6920 UnmatchedFields.insert(*Field2);
6921 }
6922
6923 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6924 Field1End = RD1->field_end();
6925 Field1 != Field1End; ++Field1) {
6926 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6927 I = UnmatchedFields.begin(),
6928 E = UnmatchedFields.end();
6929
6930 for ( ; I != E; ++I) {
6931 if (isLayoutCompatible(C, *Field1, *I)) {
6932 bool Result = UnmatchedFields.erase(*I);
6933 (void) Result;
6934 assert(Result);
6935 break;
6936 }
6937 }
6938 if (I == E)
6939 return false;
6940 }
6941
6942 return UnmatchedFields.empty();
6943}
6944
6945bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6946 if (RD1->isUnion() != RD2->isUnion())
6947 return false;
6948
6949 if (RD1->isUnion())
6950 return isLayoutCompatibleUnion(C, RD1, RD2);
6951 else
6952 return isLayoutCompatibleStruct(C, RD1, RD2);
6953}
6954
6955/// \brief Check if two types are layout-compatible in C++11 sense.
6956bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6957 if (T1.isNull() || T2.isNull())
6958 return false;
6959
6960 // C++11 [basic.types] p11:
6961 // If two types T1 and T2 are the same type, then T1 and T2 are
6962 // layout-compatible types.
6963 if (C.hasSameType(T1, T2))
6964 return true;
6965
6966 T1 = T1.getCanonicalType().getUnqualifiedType();
6967 T2 = T2.getCanonicalType().getUnqualifiedType();
6968
6969 const Type::TypeClass TC1 = T1->getTypeClass();
6970 const Type::TypeClass TC2 = T2->getTypeClass();
6971
6972 if (TC1 != TC2)
6973 return false;
6974
6975 if (TC1 == Type::Enum) {
6976 return isLayoutCompatible(C,
6977 cast<EnumType>(T1)->getDecl(),
6978 cast<EnumType>(T2)->getDecl());
6979 } else if (TC1 == Type::Record) {
6980 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6981 return false;
6982
6983 return isLayoutCompatible(C,
6984 cast<RecordType>(T1)->getDecl(),
6985 cast<RecordType>(T2)->getDecl());
6986 }
6987
6988 return false;
6989}
6990}
6991
6992//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6993
6994namespace {
6995/// \brief Given a type tag expression find the type tag itself.
6996///
6997/// \param TypeExpr Type tag expression, as it appears in user's code.
6998///
6999/// \param VD Declaration of an identifier that appears in a type tag.
7000///
7001/// \param MagicValue Type tag magic value.
7002bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7003 const ValueDecl **VD, uint64_t *MagicValue) {
7004 while(true) {
7005 if (!TypeExpr)
7006 return false;
7007
7008 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7009
7010 switch (TypeExpr->getStmtClass()) {
7011 case Stmt::UnaryOperatorClass: {
7012 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7013 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7014 TypeExpr = UO->getSubExpr();
7015 continue;
7016 }
7017 return false;
7018 }
7019
7020 case Stmt::DeclRefExprClass: {
7021 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7022 *VD = DRE->getDecl();
7023 return true;
7024 }
7025
7026 case Stmt::IntegerLiteralClass: {
7027 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7028 llvm::APInt MagicValueAPInt = IL->getValue();
7029 if (MagicValueAPInt.getActiveBits() <= 64) {
7030 *MagicValue = MagicValueAPInt.getZExtValue();
7031 return true;
7032 } else
7033 return false;
7034 }
7035
7036 case Stmt::BinaryConditionalOperatorClass:
7037 case Stmt::ConditionalOperatorClass: {
7038 const AbstractConditionalOperator *ACO =
7039 cast<AbstractConditionalOperator>(TypeExpr);
7040 bool Result;
7041 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7042 if (Result)
7043 TypeExpr = ACO->getTrueExpr();
7044 else
7045 TypeExpr = ACO->getFalseExpr();
7046 continue;
7047 }
7048 return false;
7049 }
7050
7051 case Stmt::BinaryOperatorClass: {
7052 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7053 if (BO->getOpcode() == BO_Comma) {
7054 TypeExpr = BO->getRHS();
7055 continue;
7056 }
7057 return false;
7058 }
7059
7060 default:
7061 return false;
7062 }
7063 }
7064}
7065
7066/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7067///
7068/// \param TypeExpr Expression that specifies a type tag.
7069///
7070/// \param MagicValues Registered magic values.
7071///
7072/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7073/// kind.
7074///
7075/// \param TypeInfo Information about the corresponding C type.
7076///
7077/// \returns true if the corresponding C type was found.
7078bool GetMatchingCType(
7079 const IdentifierInfo *ArgumentKind,
7080 const Expr *TypeExpr, const ASTContext &Ctx,
7081 const llvm::DenseMap<Sema::TypeTagMagicValue,
7082 Sema::TypeTagData> *MagicValues,
7083 bool &FoundWrongKind,
7084 Sema::TypeTagData &TypeInfo) {
7085 FoundWrongKind = false;
7086
7087 // Variable declaration that has type_tag_for_datatype attribute.
7088 const ValueDecl *VD = NULL;
7089
7090 uint64_t MagicValue;
7091
7092 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7093 return false;
7094
7095 if (VD) {
7096 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7097 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7098 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7099 I != E; ++I) {
7100 if (I->getArgumentKind() != ArgumentKind) {
7101 FoundWrongKind = true;
7102 return false;
7103 }
7104 TypeInfo.Type = I->getMatchingCType();
7105 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7106 TypeInfo.MustBeNull = I->getMustBeNull();
7107 return true;
7108 }
7109 return false;
7110 }
7111
7112 if (!MagicValues)
7113 return false;
7114
7115 llvm::DenseMap<Sema::TypeTagMagicValue,
7116 Sema::TypeTagData>::const_iterator I =
7117 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7118 if (I == MagicValues->end())
7119 return false;
7120
7121 TypeInfo = I->second;
7122 return true;
7123}
7124} // unnamed namespace
7125
7126void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7127 uint64_t MagicValue, QualType Type,
7128 bool LayoutCompatible,
7129 bool MustBeNull) {
7130 if (!TypeTagForDatatypeMagicValues)
7131 TypeTagForDatatypeMagicValues.reset(
7132 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7133
7134 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7135 (*TypeTagForDatatypeMagicValues)[Magic] =
7136 TypeTagData(Type, LayoutCompatible, MustBeNull);
7137}
7138
7139namespace {
7140bool IsSameCharType(QualType T1, QualType T2) {
7141 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7142 if (!BT1)
7143 return false;
7144
7145 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7146 if (!BT2)
7147 return false;
7148
7149 BuiltinType::Kind T1Kind = BT1->getKind();
7150 BuiltinType::Kind T2Kind = BT2->getKind();
7151
7152 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7153 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7154 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7155 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7156}
7157} // unnamed namespace
7158
7159void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7160 const Expr * const *ExprArgs) {
7161 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7162 bool IsPointerAttr = Attr->getIsPointer();
7163
7164 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7165 bool FoundWrongKind;
7166 TypeTagData TypeInfo;
7167 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7168 TypeTagForDatatypeMagicValues.get(),
7169 FoundWrongKind, TypeInfo)) {
7170 if (FoundWrongKind)
7171 Diag(TypeTagExpr->getExprLoc(),
7172 diag::warn_type_tag_for_datatype_wrong_kind)
7173 << TypeTagExpr->getSourceRange();
7174 return;
7175 }
7176
7177 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7178 if (IsPointerAttr) {
7179 // Skip implicit cast of pointer to `void *' (as a function argument).
7180 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00007181 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00007182 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007183 ArgumentExpr = ICE->getSubExpr();
7184 }
7185 QualType ArgumentType = ArgumentExpr->getType();
7186
7187 // Passing a `void*' pointer shouldn't trigger a warning.
7188 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7189 return;
7190
7191 if (TypeInfo.MustBeNull) {
7192 // Type tag with matching void type requires a null pointer.
7193 if (!ArgumentExpr->isNullPointerConstant(Context,
7194 Expr::NPC_ValueDependentIsNotNull)) {
7195 Diag(ArgumentExpr->getExprLoc(),
7196 diag::warn_type_safety_null_pointer_required)
7197 << ArgumentKind->getName()
7198 << ArgumentExpr->getSourceRange()
7199 << TypeTagExpr->getSourceRange();
7200 }
7201 return;
7202 }
7203
7204 QualType RequiredType = TypeInfo.Type;
7205 if (IsPointerAttr)
7206 RequiredType = Context.getPointerType(RequiredType);
7207
7208 bool mismatch = false;
7209 if (!TypeInfo.LayoutCompatible) {
7210 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7211
7212 // C++11 [basic.fundamental] p1:
7213 // Plain char, signed char, and unsigned char are three distinct types.
7214 //
7215 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7216 // char' depending on the current char signedness mode.
7217 if (mismatch)
7218 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7219 RequiredType->getPointeeType())) ||
7220 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7221 mismatch = false;
7222 } else
7223 if (IsPointerAttr)
7224 mismatch = !isLayoutCompatible(Context,
7225 ArgumentType->getPointeeType(),
7226 RequiredType->getPointeeType());
7227 else
7228 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7229
7230 if (mismatch)
7231 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7232 << ArgumentType << ArgumentKind->getName()
7233 << TypeInfo.LayoutCompatible << RequiredType
7234 << ArgumentExpr->getSourceRange()
7235 << TypeTagExpr->getSourceRange();
7236}